<?xml-model href='http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng' schematypens='http://relaxng.org/ns/structure/1.0'?><TEI xmlns="http://www.tei-c.org/ns/1.0">
	<teiHeader>
		<fileDesc>
			<titleStmt><title level='a'>Explaining Wrong Queries Using Small Examples</title></titleStmt>
			<publicationStmt>
				<publisher></publisher>
				<date>2019 June</date>
			</publicationStmt>
			<sourceDesc>
				<bibl> 
					<idno type="par_id">10190787</idno>
					<idno type="doi">10.1145/3299869.3319866</idno>
					<title level='j'>SIGMOD '19: Proceedings of the 2019 International Conference on Management of Data</title>
<idno></idno>
<biblScope unit="volume"></biblScope>
<biblScope unit="issue"></biblScope>					

					<author>Zhengjie Miao</author><author>Sudeepa Roy</author><author>Jun Yang</author>
				</bibl>
			</sourceDesc>
		</fileDesc>
		<profileDesc>
			<abstract><ab><![CDATA[For testing the correctness of SQL queries, a standard practice is to execute the query in question on some test database instance and compare its result with that of the correct query. Given two queries Q 1 and Q 2 , we say that a database instance D is a counterexample (for; such a counterexample can serve as an explanation of why Q 1 and Q 2 are not equivalent. While the test database instance may serve as a counterexample, it may be too large or complex to understand where the inequivalence arises. Therefore, in this paper, given a known counterexample D for Q 1 and Q 2 , we aim to find the smallest counterexampleThe problem in general is NP-hard. Drawing techniques from provenance and constraint solving, we develop a suite of algorithms for finding small counterexamples for different classes of queries, including those involving negation and aggregation. We evaluate the effectiveness and scalability of our algorithms on student queries from an undergraduate database course, and on queries from the TPC-H benchmark. We also report a user study from the course where we deployed our tool to help students with an assignment on relational algebra.]]></ab></abstract>
		</profileDesc>
	</teiHeader>
	<text><body xmlns="http://www.tei-c.org/ns/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink">
<div xmlns="http://www.tei-c.org/ns/1.0"><p>we have a test database instance D and a correct query Q 1 . The correctness of a student query Q 2 can be checked by testing whether Q 1 (D) = Q 2 (D). Assuming that Q 2 is at least syntactically correct and its output schema is compatible with that of Q 2 (which can be easily verified), if Q 2 does not solve the intended problem, then there will be at least one tuple in Q 1 (D) but not in Q 2 (D), or in Q 2 (D) but not in Q 1 (D). Another application scenario is when people rewrite complex SQL queries to obtain better performance. One approach for checking the correctness of complex rewritten queries is regression testing: execute the rewritten query Q 2 on test instances to make sure that Q 2 returns the same results as the original query Q 1 . Finding an answer tuple differentiating two queries and providing an explanation for its existence helps students or developers understand the error and fix their queries.</p><p>In both applications above, if the test database D is largeeither because it is a large real data set or it is synthesized to be large enough to test scalability or ensure coverage of numerous corner cases-it would take much effort to understand where the inequivalence of two queries came from. Suppose we teach a database course using DBLP data <ref type="bibr">[30]</ref> for an assignment on SQL or relational algebra. The database has more than 5 million entries, and giving this entire database (or the full query results) to students as a counterexample to their query is not very effective. In practice, the mistakes in most of the queries may be explained by only a small number of tuples, which is much more useful for debugging.</p><p>Of course, one could generate a completely different counterexample D &#8242; altogether, but using the test database instance D to help generate a counterexample has some distinct advantages. First, it helps to preserve the same context for users by using the same data values and relationships. Second, knowing that the original instance D is already a counterexample can help create the counterexample D &#8242; more efficiently. This motivates the problem we study in this paper: given a database instance D, a reference query Q 1 , and a test query Q 2 such that Q 1 (D) Q 2 (D), find a counterexample as a subinstance D &#8242; &#8838; D such that Q 1 (D &#8242; ) Q 2 (D &#8242; ) and the size of D &#8242; is minimized. We illustrate the setting with an example.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>E</head><p>1. Consider relations Student(name, major) and Registration(name, course, dept, grade) storing information about students and course registrations. In a database course, suppose the instructor asked the students to write a SQL Figure <ref type="figure">2</ref> shows the results of Q 1 and Q 2 . The tuples r 2 and r 4 are in the output of Q 2 but not in the output of Q 1 . To convince the student that his query is wrong, the instructor can provide the full contents of S, R as a counterexample comprising 11 tuples. However, a smaller and better counterexample can simply contain three tuples (e.g., t 1 t 4 t 5 ) to illustrate the inequivalence of Q 1 and Q 2 . The benefit can be much larger if we consider a real enrollment database from a university, whereas the size of the counterexample can remain small.</p><p>Prior work in the database community mainly focused on the theoretical study of decidability <ref type="bibr">[13,</ref><ref type="bibr">35]</ref> or generating a comprehensive set of test databases to "kill" as many erroneous queries as possible <ref type="bibr">[10]</ref>, but does not pay much attention to explaining why two queries are inequivalent. There are recent systems that aim to generate counterexamples for SQL queries. Cosette developed by Chu et al. <ref type="bibr">[12]</ref> used formal methods to encode SQL queries as logic formulas to generate a counterexample proving that two SQL queries are inequivalent. XData by Chandra et al. <ref type="bibr">[10]</ref> generates test data using mutation techniques. However, counterexamples generated by such systems can lead to arbitrary values, which may not be meaningful to the user. Our approach instead ensures that the user sees familiar values and relationships already present in the test database instances. Moreover, our approach focuses users on one issue with their query at a time, while XData gives instances that test multiple issues.</p><p>Specifically, this paper makes the following contributions.</p><p>&#8226; We formally define the smallest counterexample problem, and connect it to data provenance with the definition of the smallest witness problem. &#8226; We give results (NP-hardness proofs and poly-time algorithms) in terms of both data and combined complexity for different subclasses of SPJUD queries. &#8226; We give practical algorithms for SPJUD queries using SAT and SMT solvers, and discuss a suite of optimizations to improve efficiency. &#8226; For aggregate queries, we illustrate the challenges and propose methods to address them, which includes applying provenance for aggregate queries <ref type="bibr">[2]</ref>, adapting the problem definition using the idea of "parameterizing" the queries, and heuristics to improve efficiency. &#8226; We have implemented an end-to-end system called RAT , which has seen live deployment and will be demonstrated at this conference <ref type="bibr">[33]</ref>. &#8226; We evaluate the effectiveness and scalability of our approach on student queries from an undergraduate course, and on queries from the TPC-H benchmark. &#8226; We provide a case study in a large undergraduate database course at Duke University, where students use RAT to debug their queries in a homework. Quantitative analysis of usage statistics and homework scores show that use of RAT improved student performance; anonymous survey of the students also indicates that they found RAT helpful to their learning.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2">SPJUD QUERIES</head><p>In this section, we consider the class of non-aggregate queries with Select (S)-Project (P)-Join (J)-Union (U)-Difference (D) operations expressed as relational algebra (RA) expressions; queries with aggregates are considered in Section 3. We will use RA form and SQL form of queries interchangeably. A subset of these operators using abbreviations will denote the corresponding subclass of such queries; e.g., PJ queries will denote queries involving only projection and join operations. First, Section 2.1 gives a formal problem definition and covers some preliminaries. Then, Section 2.2 presents complexity results for different subclasses of SPJUD queries. Finally, Section 2.3 discusses practical algorithms and optimizations.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.1">Problem Definition and Preliminaries</head><p>For a database instance D (involving one or more relations) and a query Q, Q(D) denotes the result of Q on D. Let &#915; denote a set of integrity constraints on the schema of the database instance D. We consider the following standard integrity constraints: keys, foreign keys, not null, and functional dependencies. If D satisfies &#915;, we write D |= &#915;. We use |D| to denote the total number of tuples in D.</p><p>We will use unique identifiers to refer to the tuples in the database and query answers. In our example tables, they are written in the right-most column (see Figures <ref type="figure">1</ref> and<ref type="figure">2</ref>), e.g., in Figure <ref type="figure">1</ref>, t 1 refers to the tuple Student(Mar , CS). Based on D, we want to find a small counterexample D &#8242; &#8838; D that also explains the inequivalence of</p><p>Given a database schema with a set of integrity constraints &#915; and two queries Q 1 and Q 2 , we say that a database instance D is a counterexample for</p><p>In the above definition, we assume that the query results are union-compatible (i.e., Q 1 (D) and Q 2 (D) have the same schema), which is easy to check syntactically; otherwise the difference in their schema provides an explanation of their inequivalence. From now on, where it is clear from the context, we will implicitly assume that D &#8242; &#8838; D discussed as a counterexample conforms to the given constraints &#915;; we will discuss how constraints are handled in Section 2.3.4.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>E</head><p>2. In Example 1, the given test instance in Figure <ref type="figure">1</ref> is a counterexample for Q 1 and Q 2 . However, some subinstances are also counterexamples. Among these, two smallest counterexamples can be formed with t 1 in S and t 4 t 5 in R, or with t 3 in S and t 9 t 10 in R. (Two other subinstances that are smallest counterexamples can be formed by varying the two courses of Jesse, but no counterexample has fewer than 3 tuples.)</p><p>Our goal is to explain the query inequivalence to users by showing the smallest counterexample over which the two queries return different results. Even in our running example with a toy database instance, this reduced the number of tuples from 11 to only 3, whereas the benefit is likely to be much more for test database instances in practice as observed in our experiments. The brute-force method to find the smallest counterexample is to enumerate all subinstances of D, and search for the smallest subinstance D &#8242; where Q 1 (D &#8242; ) and Q 2 (D &#8242; ) differ. However, enumerating all possible subinstances is inefficient and it does not utilize the fact that D itself is a counterexample. Therefore, to solve this problem more efficiently, we relate it to the concepts of witnesses and data provenance as discussed below.</p><p>2.1.2 Smallest Witness Problem. Buneman et al. <ref type="bibr">[9]</ref> proposed the concept of witnesses to capture why-provenance of a query answer. Intuitively, a witness is a collection of input tuples that provides a proof for a given result tuple. Formally, given a database instance D, a query Q, and a tuple t &#8712; Q(D), a witness for t w.r.t. Q and D is a subinstance D &#8242; &#8838; D where t &#8712; Q(D &#8242; ). For instance, in Example 1, {t 1 , t 4 }, {t 1 , t 5 }, and {t 1 , t 4 , t 5 } are three witnesses of the result tuple r 2 w.r.t. Q 2 and D. We use W(Q, D, t) to denote the set of all witnesses for t &#8712; Q(D) w.r.t. Q and D. Since we also consider non-monotone queries, we extend the definition of witness with the concept of potential answers. We give the definition below, and will discuss more details later.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>D 2 (P A</head><p>). Given a query Q and a database instance D, we call a tuple t a potential answer w.r.t. Q and D if there exists</p><p>denote the set of all potential answers w.r.t. Q and D.</p><p>Intuitively, members of A(Q, D) can be obtained by deleting zero or more tuples from D and evaluating Q. Obviously, all tuples in Q(D) are potential answers.</p><p>For instance, in Example 1, only ( ohn, ECON ) is in the result of Q 1 . However, other tuples can also be potential answers. In particular, if we remove some registration records from R, then (Mary, CS) and (Jesse, CS) may appear in the query result of Q 1 over the modified database, so they are potential answers.</p><p>The following proposition states that the number of potential answers is polynomial in data complexity <ref type="bibr">[45]</ref> (when the query is fixed). The proof is by induction on the height of the operator tree for the query (we defer the proof to the full version of this paper <ref type="bibr">[32]</ref> because of space constraints).</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>1. Given a database instance D, an SPJUD query Q, the number of tuples in A(Q, D) is polynomial in terms of number of tuples in D.</p><p>Recall that witness is previously defined for a tuple in result of Q over D. With the notion of potential answers, we now extend the domain of witness so that it is also defined for any tuple in A(Q, D).</p><p>A witness may contain many tuples and is sensitive to the query structure. Buneman et al. <ref type="bibr">[9]</ref> defined minimal witness as a minimal element of W(Q, D, t); i.e., for a minimal witness w &#8712; W(Q, D, t), there exist no other witnesses w &#8242; &#8712; W(Q, D, t) such that w &#8242; &#8834; w. In Example 1, {t 1 , t 4 } and {t 1 , t 5 } are minimal witnesses of the result tuple r 2 w.r.t. Q 2 and D, but {t 1 , t 4 , t 5 } is not. Note that a witness with the smallest cardinality must be a minimal witness.</p><p>How do witnesses relate to counterexamples? It turns out that any counterexample for Q 1 and Q 2 is also a witness for some potential answer w.r.t. either</p><p>as the following proposition shows more formally.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>. Since D &#8242; is a counterexample, there exists a tuple  </p><p>From now on, without loss of generality, we will assume that in SCP(D,</p><p>In the rest of the paper, we will mainly focus on the smallest witness problem SWP(D, Q 1 , Q 2 , t) for such a tuple. We further discuss the connection between SCP and SWP in Section 2.3. Discussion. Note that we have to consider Q 1 and Q 2 jointly in general when finding counterexamples and witnesses. For instance, suppose t &#8712; Q 1 (D) -Q 2 (D), and we want to find a smallest subset</p><p>may happen to make t appear in the result of Q 2 (w), failing to differentiate Q 1 and Q 2 . 1 Similarly, answering both "why t is in Q 1 (D)" and "why t is not in Q 2 (D)" may also failif we find a witness w 1 &#8712; W(Q 1 , D, t) and a small subinstance w 2 of D with the help of a why-not approach <ref type="bibr">[21]</ref><ref type="bibr">[22]</ref><ref type="bibr">[23]</ref><ref type="bibr">29]</ref>, such that t &#8712; Q 1 (w 1 ) and t Q 2 (w 2 ), it is possible </p><p>. Therefore, we have to consider</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.2">Complexity for SPJUD Queries</head><p>Table <ref type="table">1</ref> summarizes the complexity of the smallest witness problem (SWP) for any subclass of SPJUD queries. In terms of complexity, we consider data complexity (fixed query size), query complexity (fixed data size), and combined complexity (in terms of both data and query size) <ref type="bibr">[45]</ref>. Thus polynomial combined complexity indicates polynomial data complexity.</p><p>In Table <ref type="table">1</ref>, the class JU * has the restriction that all unions appear after all joins. The class SPJUD * is defined as: Q &#8594; q + |Q -Q, where q + is a SPJU query. Proofs are given in Appendix A. For queries involving PJ, in general even the query evaluation problem is NP-hard in query complexity. It is the same for queries involving JU, however, the problem is in poly-time for the subclass JU * , because we can directly look into the join-only parts of a JU * query. For general SPJU queries, the problem has poly-time data complexity, and thus we can provide a poly-time algorithm for SPJUD * queries in data complexity. What is noteworthy is that for the class of queries involving projection, join, and difference without any restrictions, it is already NP-hard in data complexity to find the smallest witness for a result tuple; and the result holds even when the queries are of bounded sizes and the database instance only contains two relations. While in the complexity results, we assume both</p><p>, for all monotone cases the exact class of Q 2 does not matter as long as it is monotone. We can show that SCP for PJD queries is also NP-hard in data complexity by a simple reduction from SWP.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.3">Methods for SPJUD Queries</head><p>The smallest witness problem is in general NP-hard even for queries of bounded size, and the poly-time algorithms in Table <ref type="table">1</ref> are not efficient for practical purposes. To address these challenges, we introduce a constraint-based approach to the smallest witness problem. We map the problem into the min-ones satisfiability problem <ref type="bibr">[28]</ref> by tracking the Boolean provenance of potential answers. The min-ones satisfiability problem is an extension of the classic Satisfiability (SAT) problem: given a Boolean formula &#981;, it checks whether &#981; is satisfiable with at most k variables set to true. This problem can be solved by either using a SAT solver (e.g., MiniSAT <ref type="bibr">[43]</ref>, CaDiCaL <ref type="bibr">[7]</ref>), or an SMT Solver (e.g., CVC4 <ref type="bibr">[4]</ref>and Z3 <ref type="bibr">[15]</ref>). Satisfiability Modulo Theories (SMT) is a form of constraint satisfaction problem. It refers to the problem of determining whether a first-order formula is satisfiable w.r.t. other background first-order formulas, and is a generalization of the SAT problem <ref type="bibr">[6]</ref>. SAT and SMT problems are known to be NP-hard with respect to the number of clauses, constraints, and undetermined variables. However, there is a variety of solvers that work very well in practice, and with these solvers we can find a small solution to a SWP instance. The rest of this subsection will describe how to encode howprovenance, and then use a state-of-the-art solver to find the smallest witness for a potential answer. The implementation details will be discussed in Section 4.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.3.1">Boolean How-Provenance.</head><p>In order to compute the smallest witness efficiently for general SPJUD queries, we use the concept of how-provenance or lineage <ref type="bibr">[1,</ref><ref type="bibr">19]</ref> by provenance semirings. How-provenance encodes how a given result tuple is derived from the given input tuples using a Boolean expression, and its first use can be traced back to Imilienski and Lipski <ref type="bibr">[24]</ref> who used it to describe incomplete databases or c-tables. The computation of how-provenance of a tuple t &#8712; A(Q, D), denoted by Prv Q, D (t) or Prv(t) when clear from the context, is well known and intuitive: tuples in the given input relations are annotated with unique identifiers (as shown in the right-most columns in Figure <ref type="figure">1</ref>). As the query Q executes, for selections or duplicate-preserving projections, the annotations remain the same; for joint usages of sub-expressions (joins), their annotations are combined with conjunction (&#8743; or &#8226;), and for alternative usages of subexpressions (de-duplicates or unions), the annotations are combined with disjunction (&#8744; or +). For simplicity, we use + for disjunction, and omit symbols for conjunction. For instance, in Example 1, in Q 2 (D),</p><p>For set difference operation, the extension of provenance with potential answers is important.</p><p>, where &#968; = &#172;&#968; denotes the negation of the Boolean expression &#968; .</p><p>The tuple t appears in the final result of</p><p>, or if t appears in both of them and Prv Q, D (t) is true. The removal of any tuple from D will make its Boolean variable set to false and thus may affect the value of Prv Q, D (t). We consider all potential answers w.r.t. Q and D when computing the how-provenance for Q(D).</p><p>Example 2.1. In Example 1, consider the following RA expressions for Q 2 and Q 1 , using abbreviations S and R for Students and Registration, where denotes natural join.</p><p>Suppose</p><p>, where &#951; denotes the selection condition:</p><p>In other words, the tuple (Mary, CS) can distinguish the queries Q 1 , Q 2 in a small witness with t 1 in S and t 4 t 5 in R, which solves both SWP and SCP problems.</p><p>For the above example, the smallest witness or the smallest counterexample could be found by inspection, since Q 1 , Q 2 are similar. For arbitrary and more complex queries, howprovenance gives a systematic approach to find a small witness as we will discuss in the following two sections.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.3.2">Passing</head><p>How-Provenance to a Solver. Since Pr (t) is composed of a combination of Boolean variables annotating tuples in the input relations, a Boolean variable is true iff the corresponding tuple is present in the input relation. Then an instance of the smallest witness problem is mapped to an instance of the min-ones satisfiability problem: find a satisfying model to Pr (t) with least number of variables set to true, and the variables set to true in the satisfying model indicate tuples in the smallest witness.</p><p>The pseudocode of the algorithm to solve SWP and then SCP can be found in the full version <ref type="bibr">[32]</ref>. Briefly, one approach to solving SWP is by repeated invocation of a SAT solver. Since the solver will return an arbitrary satisfying model, to get the minimum model we need to ask the solver to return a different model every time we rerun it. We set a maximum number of runs to limit the running time, and the algorithm stops when there is no more satisfying models or it has reached the maximum number of runs. It may not find the minimum model when it stops, but it is likely to find a small one if given enough time.</p><p>To solve SCP, recall from Section 2.1 that it suffices to consider SWP for all potential answers in</p><p>Therefore, a basic algorithm for SCP, which we call SCP , will compute the provenance for Q 1 -Q 2 and Q 2 -Q 1 , identifying all potential answers and their provenance in the process. Then, for each potential answer, we solve SWP as described above. The overall smallest witness will be chosen.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>2.3.3</head><p>Improving the Basic Approach. The basic approach above has two limitations: 1) for SWP, it cannot find the smallest witness until it searches all possible models that satisfy Prv(t); 2) SCP computes provenance for every potential answer, resulting in high overhead. Therefore, we propose two improvements.</p><p>The first improvement is to pick only one tuple t from Q 1 (D)\Q 2 (D), and capture only the provenance of t by adding a selection operator to select tuple t on top of the query tree of Q 1 -Q 2 . During provenance computation, which we implemented by rewriting SQL queries (see Section 4 for more details), the SQL optimizer is likely to push down the additional selection operator, thereby reducing unnecessary intermediate computation and accelerating provenance computation. We call this strategy SCP for "selective" provenance, which solves only one instance of SWP. Of course, if</p><p>The second improvement is to treat SWP as an optimization problem instead of finding different models with a SAT solver. Integer linear programming solvers cannot be applied because transforming how-provenance into linear constraints can be exponential. To solve this problem, we use optimizing SMT solvers that are now available with recent advances in the programming languages and verification research community <ref type="bibr">[8,</ref><ref type="bibr">31]</ref>. Given a formula &#981; and an objective function F , an optimizing SMT solver finds a satisfying assignment of &#981; that maximizes or minimizes the value of F . In our case, we encode Prv(t) as the constraint of the optimizing SMT solver, set the number of true variables as the objective function, and solve for the optimal model. Our SMT formulation includes only Boolean variables, so we encode the number of true variables by first converting the variables into 0 or 1 and then summing them up. The pseudocode of this improved algorithm can be found in <ref type="bibr">[32]</ref>.</p><p>As an example, the following listing illustrates how we encode the provenance in the SMT-LIB standard format <ref type="bibr">[5]</ref> as the input to an SMT solver, which returns a solution to</p><p>( declare-const t1 Bool ) ... ( declare-const t11 Bool ) ( define-fun b2i (( x Bool )) Int ( ite x 1 0) ) ( assert ( and ( or t4 t5 ) ( not ( and ( or ( and t1 t4 ) ( and t1 t5 )) ( not ( and t1 ( and t4 t5 ))))))) ( minimize (+ ( b2i t1 ) ( b2i t2 ) ... ( b2i t11 )))</p><p>Lines 1-3 define Boolean variables for each tuple. Line 4 defines function b2i that converts Boolean variables into 0 and 1. Line 5 adds the how-provenance as an SMT constraint. Then with function b2i we take the sum of 0-1 variables to get the total number of variables set to true, and then set minimizing this sum as the objective function (Line 6).</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2.3.4">Handling Database</head><p>Constraints. Since we output a subinstance of the input database instance as the witness, database constraints like keys, not null, and functional dependencies are trivially satisfied if the input instance is valid. On the other hand, foreign key constraints can be naturally represented as Boolean formulas like provenance expressions. For instance, in our running example in Figure <ref type="figure">1</ref>  . Then, for each tuple that appears in the provenance expression added to the SAT or SMT solver, we add its foreign key constraint expression to the solver as a constraint.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3">AGGREGATE QUERIES</head><p>So far, we have focused on SPJUD queries. We now extend our discussion to aggregate queries. We make some assumptions on the form of such queries: 1) no aggregate values or NULL are allowed in group-by attributes; 2) selection predicates involving previously aggregated values (i.e., HAVING conditions) involve only numeric comparisons; 3) there is no difference operator above aggregation in either</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.1">Challenges of Aggregate Queries</head><p>First, (selective) how-provenance does not work well for SCP for aggregate queries. Recall from Section 2.3 that a practical heuristic we used for SPJUD queries, SCP , just picks one tuple t from the symmetric difference between Q 1 and Q 2 and focuses on computing how-provenance and finding a witness for t. Unfortunately, this heuristic may not work for an aggregates result tuple t, because its aggregate value generally depends on all member tuples in the input group corresponding to t; removal of any such tuple may change t's aggregate value, so there may not exist any proper subset of tuples in the input group that can serve as a witness for t.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>E</head><p>3 (C ). Suppose we have a reference query Q 1 aimed at computing the average grade of students in CS courses, using the two tables in Figure <ref type="figure">1</ref> To circumvent the problem, can we resort to considering witnesses for all potential answers instead of just t, as in SCP ? Indeed, in the above example, (Mary, 88) is a potential answer that can be constructed by extending howprovenance to aggregates, essentially through enumeration of all possible combinations of tuples in a group <ref type="bibr">[41]</ref>. However, this approach leads to exponential overhead and becomes impractical for even moderate-size groups.</p><p>Finally, as soon as we consider further selection involving aggregate values (such as HAVING), there can be cases where the size of any counterexample is necessarily large by our formulation of SCP in Definition 1. Consider the following. Q 1 and Q 2 would return the following results (recall that Q 2 misses the condition r.dept='CS'):</p><p>Because of the HAVING condition, we must include all (3) of Mary's registration records in a counterexample, or else the queries would be indistinguishable because neither would return Mary's group.</p><p>While the group size in the above example is small, it is trivial to construct examples where HAVING would force arbitrarily large groups of input tuples to be included in a counterexample. No approach (including painstakingly Q1 name avg_grade provenance Mary val1 : avg(t4 &#8855; 100, t5 &#8855; 75) Note that instead of infix notations for avg and sum as in <ref type="bibr">[2]</ref>, we use prefix notations for readability. considering all potential answers) would help because the problem is inherent in the formulation of SCP in Definition 1.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.2">Methods for Aggregate Queries</head><p>We first tackle the ineffectiveness of how-provenance, by applying provenance semirings for aggregate queries proposed by Amsterdamer et al. <ref type="bibr">[2]</ref> and proposing a baseline method called AGG</p><p>. We further address the inherent limitation of Definition 1 for handling aggregates by proposing a new definition based on the ideas of parameterizing queries, and showing how AGG can be adapted. Finally, we present a heuristic method called AGG that improves the running time of AGG for queries involving a single aggregation followed by an optional selection.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.2.1">Applying Provenance for</head><p>Aggregates. Following the approach in <ref type="bibr">[2]</ref>, we encode aggregate values computed by queries as symbolic expressions using abstract arithmetic operations and variables corresponding to tuples in the input relations. Selection conditions involving aggregate values are then encoded as symbolic logical expressions. Table <ref type="table">2</ref> shows the provenance for aggregate queries for Example 4. For instance, avg(t 4 &#8855; 100, t 5 &#8855; 75) represents the AVG value of a group containing two tuples t 4 and t 5 in the result of Q 1 , and the value of the attribute of tuple t 4 is 100, and for t 5 it is 75 . If t 4 is removed from the input relations, then t 4 &#8855; 100 will not contribute to the aggregate. Like the howprovenance, (t 1 (t 4 + t 5 )) (sum(t 4 &#8855; 1, t 5 &#8855; 1) &#8805; 3) indicates how the result tuple is derived from the input or intermediate tuples: t 1 (t 4 + t 5 ) means that the group exists iff t 1 exists and one of t 4 and t 5 exists; sum(t 4 &#8855; 1, t 5 &#8855; 1) &#8805; 3 represents the HAVING criterion: the COUNT (a special case of SUM) value should be greater or equal to 3. As with how-provenance, aggregate values and provenance expressions can be computed bottom-up during query evaluation. Unlike how-provenance, there is no longer a need to enumerate all possible aggregate values resulting from subsets of a group of tuples; one single symbolic expression succinctly captures these possibilities.</p><p>With this approach, we have a baseline method for finding counterexamples for aggregate queries, which we call AGG . Given Q 1 (D) and Q 2 (D) that differ, we pick a group that exists in one result but not the other, or a group that exists in both but the aggregate values differ. In either case, we can assert a symbolic Boolean expression derived using the aggregate provenance expressions, and let an SMT solver find a satisfying model with minimum number of input tuples included. For example, a counterexample for Q 1 and Q 2 w.r.t. tuple (Mary, 90) can be found by solving the constraint (pr 4 &#8853; pr 1 ) &#8744; ( al 4 al 1 ). Note that the constraint only insists that aggregate values produced by Q 1 and Q 2 are different; there is no stipulation that this counterexample reproduces the same aggregate value 90.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.2.2">Parameterizing the Problem.</head><p>To address the problem that certain queries require large counterexamples by Definition 1, we modify our problem definition by parameterizing the queries, thereby allowing extra degrees of freedom when constructing counterexamples. Specifically, we replace the constants in selection predicates (such as 3 used in the HAVING condition of Example 4) by a parameter; a subinstance can be a counterexample as long as it differentiates the two queries for some setting of the parameter, not necessarily the original one.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>D 4 (S P C P</head><p>). Given two queries Q 1 and Q 2 parameterized by &#955;, as well as a database instance D and a setting &#955; = , where Q 1 ( , D) Q 2 ( , D), the smallest parameterized counterexample problem (SPCP) is to find a subinstance D &#8242; of D and a parameter setting &#955; = &#8242; , such that such that If we insist on &#955; = 3, the smallest counterexample we can find would be t 1 t 4 t 5 t 6 (see Example 4). However, with the flexibility of SPCP, we can find a small counterexample t 1 t 6 , which differentiates Q 1 and Q 2 for &#955; = 1.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>We can adapt the algorithm AGG</head><p>to work for SPCP. The only change would be that we treat the query parameter &#955; as a symbolic variable when computing aggregate provenance. For example, doing so amounts to replacing occurrences of the constant 3 with &#955; in Table <ref type="table">2</ref> for Example 4. We impose no constraint on this variable to the solver, so it can find small counterexamples without adhering to the original parameter setting.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3.2.3">A Heuristic Improvement. AGG</head><p>may not scale very well when a group contains many tuples, because the SMT constraints will involve many variables and become difficult to solve. Thus, we develop a heuristic improvement called AGG , targeting Q 1 and Q 2 where both end with an aggregation operator followed by an optional selection operator. The key intuition behind AGG is to heuristically focus on differentiating two corresponding groups of tuples computed by Q 1 and Q 2 before they are aggregated. A counterexample that differentiates these two groups will likely lead to different result tuples after aggregation. Recall Example 3, where Q 1 and Q 2 differ in the aggregate value of result group for Mary (because Q 2 forgot to restrict to CS courses). Disregarding aggregation, if we simply focus on differentiating members in the Mary group, we will obtain a counterexample t 1 t 6 , which happens to differentiate Q 1 and Q 2 after aggregation.</p><p>In more detail, AGG works as follows. First, it picks one group, identified by a specific group-by value a, for which Q 1 (D) and Q 2 (D) differ (either the group is in one result but not the other, or its aggregate value differs). Then, we formulate two queries Q &#8242; 1 and Q &#8242; 2 that compute the members of group a for Q 1 and Q 2 (resp.); they are formed by taking the subqueries of Q 1 and Q 2 below the aggregation operator and subjecting them to a selection condition setting the group-by attribute to a. We simply solve SCP on</p><p>Next, AGG tests if C also works for Q 1 and Q 2 , and if not, tries to change any query parameter in the final selection to make it work. To this end, let Q * 1 and Q * 2 denote the "remainder" queries that produce the final result tuples for group a from the results of</p><p>2 should involve only one aggregation followed by a selection parameterized by &#955;. In general, following an approach similar to earlier sections, we can derive a Boolean expression from Q * 1 , Q * 2 , and the actual contents of Q &#8242; 1 (C) and Q &#8242; 2 (C) to check whether Q 1 (C) Q 2 (C), with only one variable &#955;. We then assert this expression and solve for a feasible setting of &#955;. In practice, the cases for various types of final selection conditions are simple enough that we use a set of hand-coded rules to set &#955;.</p><p>Finally, there is still a chance that C does not work for Q 1 and Q 2 . In this case, AGG can attempt another counterexample for Q &#8242; 1 and Q &#8242; 2 , and repeat this process a number of times before giving up.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4">IMPLEMENTATION &amp; EXPERIMENTS</head><p>Provenance has been not only studied extensively theoretically <ref type="bibr">[2,</ref><ref type="bibr">9,</ref><ref type="bibr">19]</ref>, but also implemented in various systems <ref type="bibr">[3,</ref><ref type="bibr">17,</ref><ref type="bibr">18,</ref><ref type="bibr">27,</ref><ref type="bibr">38,</ref><ref type="bibr">42]</ref>. However, to the best of our knowledge, no current system readily meets our need for supporting general SPJUD and aggregate queries. We have implemented our system, called RAT , on top of a SQL-based database system by translating relational queries and provenance computation into SQL for execution. RAT</p><p>builds on an open-source RA interpreter [48] that translates relational algebra queries (extended with group-by and aggregation) into SQL, using WITH to build up complex queries one relational operator at a time. To compute provenance, RAT rewrites the SQL fragment generated for each relational operator with logic to derive output provenance expressions from its input ones. All input and result (including intermediate) relations are augmented with an extra string-valued column for storing provenance expressions (Section 2.3); columns for aggregate values are replaced with string-valued ones for storing the corresponding symbolic expressions (Section 3.2.1). These expressions are computed using SQL in a bottom-up fashion through the query tree, by manipulating the strings encoding these expressions in the SMT-LIB format <ref type="bibr">[5]</ref>. For additional details, see <ref type="bibr">[32]</ref>.</p><p>Once provenance has been computed by evaluating the rewritten SQL queries, RAT generates the SMT constraints and solves them using Z3 4.7.1, an efficient optimizing SMT Solver by Microsoft Research <ref type="bibr">[8,</ref><ref type="bibr">15]</ref>, with the objective function minimizing the number of Boolean variables set to true. The satisfying models returned by the solver represent the counterexamples.</p><p>RAT is implemented mostly in Python, and the experiments in this section ran locally on a 64-bit Ubuntu 16.04 LTS server with 3.60GHz Intel Core i7-4790 CPU and 16GB 1600MHz DDR3 RAM, which also hosts the database (Microsoft SQLServer 2017). RAT additionally features a webbased interface, described in more detail in <ref type="bibr">[33]</ref>.</p><p>The following experiments focus on evaluating the efficiency and scalability of our algorithms as well as the quality of the counterexamples they find. Section 4.1 focuses on SPJUD queries collected from student submissions to a relational algebra assignment in an undergraduate database course at Duke University; therefore, the wrong queries were "real", although test database instances are synthetic. Section 4.2 uses TPC-H <ref type="bibr">[14]</ref>, where we manually created wrong versions of several benchmark queries.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.1">Real-World SPJUD Queries</head><p>Queries in these experiments come from submissions by 141 students to a relational algebra assignment in Fall 2017, where they were asked to write SPJUD queries using the RA interpreter. There were 8 questions, 7 of which are relevant to our experiments (the first question was so simple that all students got it correct). These questions are similar (but not identical) to those used in our user study in Fall 2018 (see Section 5 for more more details); the database schema is the same. We use a synthetic test database instance D whose size can be adjusted. It was designed to catch some corner cases but there is no guarantee that it has complete coverage (in the sense that it can reveal all incorrect queries), and we observed that as we increase its size, more incorrect queries were caught:    (using SCP ). SMT is the clear winner, consistently producing smaller counterexamples than SAT*128. For a closer look at the time-quality trade-off, Figure <ref type="figure">3b</ref> further compares the average solver running time and counterexample size produced by SMT vs. SAT*&#8710; for varying &#8710; (from 1 to 128); for comparison, we also show SCP with SMT. Overall, we see that SMT offers much better time-quality trade-offit is able find counterexamples smaller than any of SAT*&#8710; by spending just a little more time than SAT*4. Of course, results of these experiments heavily depend on the solver implementation; a comprehensive evaluation would be beyond the scope of this paper. Here, we simply observe that our implementation choice of SMT provides good performance and solution quality in practice, as it cannot be easily beaten by simply enumerating a number of satisfying models.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>Size of Counterexamples vs. Provenance Expressions.</head><p>Since our approach to finding counterexamples is based on provenance, an interesting question is whether provenance expressions themselves are small enough to serve as explanations instead. To this end, we compare the size of an counterexample given by our approach against the size of the provenance expression (for the same result tuple targeted by the counterexample). Here, we define the size of a provenance expression as the number of distinct variables (input tuples) it contains. <ref type="foot">3</ref> Figure <ref type="figure">4</ref> compares the average size of counterexamples and that of the corresponding provenance expressions, as we vary the size of the database D. We use SCP with SMT here. While the counterexample sizes depend on the particularities of each database instance, the general trend is that the average size of provenance increases with the database size, while the average size of counterexamples is much lower and remains stable even as the database becomes larger.</p><p>Running Time Breakdown vs. Database Size. To better understand the performance of our approach, we vary the size of the database and study the breakdown of running times in Figure <ref type="figure">5</ref>. Here, raw is the time to evaluate the difference between the student query and the reference query (without computing any provenance); prov-all is for evaluating the rewritten query, which computes all potential answers and their provenance (a step needed in SCP ); prov-sel is for evaluating the rewritten query with the extra selection targeting one specific tuple in the difference to obtain its provenance (a step used by SCP</p><p>). We also show the total times spent on the solver for SCP with SMT (solver-sel-SMT), SCP with SAT*128 (solver-sel-SAT*128), and SCP with SMT (solver-all-SMT). From the figure, we see that full provenance computation adds significant overhead compared with normal query evaluation (prov-all vs. raw). However, we can drastically reduce this overhead by focusing on only one tuple in the difference: e.g., prov-sel is about 42&#215; faster than prov-all and 29&#215; faster than raw when |D| = 100K. Also thanks to this focus, solver time for SCP with SMT becomes negligible in comparison with other components of the running time for large databases; as shown in earlier experiments, it still produce small counterexamples comparable to those of SCP with SMT, which can be prohibitive for large databases.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>Running Time vs. Query Complexity. Focusing on SCP</head><p>with SMT, we now study how query complexity affects the running time (and its breakdown) in Figure <ref type="figure">6</ref>. Besides the total running time, we also report its breakdown in terms of time spent on evaluating the difference between student and reference queries (raw), computing provenance for the selected tuple (prov), and solving the SMT (solver). We consider three measures of query complexity: number of operators, number of difference operators, and the height of the query tree. <ref type="foot">4</ref> If multiple queries have the same value for some complexity measure, we report their average running time.</p><p>From these plots, we see that the cost of (selective) provenance computation and solving the SMT tends to increase with query complexity, but the total running time is dominated by just the time of checking the difference between student and reference queries, which fluctuates more.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4.2">Synthetic Aggregate Queries</head><p>We experimented on the TPC-H benchmark database generated at scale 1 (8.5 million tuples) with queries Q4, Q16, Q18, Q21, and Q21-S, a modified version of Q21 that ends with a final selection on aggregate value. We choose these queries because they do not involve arithmetic operations on aggregate functions. First we dropped the ORDER BY operator and rewrote these queries using the RA interpreter, then we experimented both the baseline approach (AGG ) and the heuristic improvement (AGG ) discussed in Section 3. We also experimented with AGG with the parameterization extension on Q18 (it has a subquery involving selection predicate with aggregate value, and ends with another aggregation operator). We intentionally made two wrong queries for each query, whose errors include different selection conditions, incorrect use of difference, and incorrect position of projection. These are common errors in the students queries from the previous experiment.</p><p>Size of Counterexamples vs. Provenance Expressions. See Figure <ref type="figure">7</ref>. SC-Base and SC-Impr are the sizes of counterexample returned by AGG and AGG , respectively; Prov-Base and Prov-Impr are the sizes of provenance expressions used in AGG and AGG , respectively. AGG does not finish running on Q4. The sizes of the counterexamples by both AGG and AGG are significantly smaller than the original provenance for aggregate queries expressions for most queries (note the logarithmic scale). For some queries (Q4 and Q16), AGG does not reduce the size of counterexamples over the how-provenance expression, because these queries are much simpler in structure compared to those involving multiple projections and differences in Section 4.1.</p><p>For Q18, AGG with parameterization extension (not shown in figure) returns counterexamples with 3.5 tuples on average, reducing by half of the size of counterexamples by both AGG and AGG , while the solver running time only increases to 0.0210 seconds. This indicates that the parameterization extension helps us avoid large counterexamples required by selections involving aggregate values.</p><p>Running Time. Table <ref type="table">3</ref> reports the running time of our algorithms for finding the smallest counterexample for each TPC-H query we experiment with. We present a breakdown of the execution time into time spent on evaluating the difference between wrong and reference queries, computing provenance for the selected tuples, and solving the SMT constraints. We find that the scalability of AGG is much better than AGG , because it focuses on a single group member instead of the entire group. The performance of AGG is significantly affected by the number of tuples in the group, as the SMT solver struggles to scale.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="5">USER STUDY</head><p>Since one motivation of our work is to provide small examples as explanations of why queries are incorrect, we built our RAT system as a web-based teaching tool and deployed it in an undergraduate database class at Duke University in Fall 2018 with about 170 students. For one homework assignment, students needed to write relational algebra queries to answer 10 questions against a database of six tables about bars, beers, drinkers, and their relationships. The difficulties of these 10 problems range from simple to very difficult. The students had a small sample database instance to try their queries on. Their submissions were tested by an auto-grader against a large, hidden database instance designed to exercise more corner cases and catch more errors; if these answers differed from those returned by the correct queries (also hidden), the students would see the failed tests with some additional information about the error (but not the hidden database instance or the correct queries). The final submissions were then graded manually informed by the auto-grader results; partial credits were given. For the purpose of this user study, we normalize the student score for each question to [0, 100].</p><p>We did not wish to create unfair advantages for or undue burdens on students with our user study. This consideration constrained our user study design. For example, we ruled out the option of dividing students into groups where only some of them benefit from RAT ; we also ruled out creating additional homework problems without counting them towards the course grades. Therefore, we made the use of RAT completely optional (and with no extra incentives other than the help RAT offers itself). RAT was given the correct queries and the same database instance used by the auto-grader for testing. If a student query returned an incorrect result, RAT would show a small database instance (a subset of the hidden one), together with the results of the incorrect query and the hidden correct query on this small instance. We made RAT available for only 5 out of the 10 problems. Leaving some problems out allowed us to study  simply more diligent and therefore would generally perform better than others. While we cannot definitively attribute all improvement in student performance to RAT , we next provide some evidence that it did help in a significant way.</p><p>Here, we zoom in on the three most difficult problems, (h), (i), and (j); RAT was only made available for (i). Problem (h) (find all drinkers who frequent only those bars that serve some beers they like) is quite similar to (i) (the difference being "some beers" vs. "only beers"). Problem (j) (find all (bar1, bar2) pairs where the set of beer served at bar1 is a proper subset of those served at bar2) on other hand requires very different solution strategy. Between those who did not use RAT for (i) and those who did, Figure <ref type="figure">9</ref> (focus on the first three columns and ignore the rest for now) compares their scores on (h) and (j). We see that for the similar problem (h), those who used RAT on (i) significantly improved their scores on (h), with a degree comparable to the improvement on (i). For the dissimilar problem (j), those who used RAT no (i) showed no improvement in their scores on (j)-the two score distributions are practically the same. We make two observations here. First, it is clear that not all improvement in student performance can be explained by student "diligence" alone; otherwise we would have seen higher performance on (j) for students who used RAT on (i). Second, a learning effect seems to exist: using RAT for one problem can help with a similar problem: (i) helps (h).</p><p>Figure <ref type="figure">9</ref>, in its last four columns, also breaks down the statistics by when a student started to work on Problem (i). Not surprisingly, we see that "procrastinators" (those who started very close to the due date) performed clearly worse than others. If somebody started to work on (i) using RAT only the day before the homework was due, this individual would be expected to perform even worse than an "average" student who opted not to use RAT at all, especially for the last problem. It would have been nice if we can similarly break down the statistics for students who opted not to use RAT at all, but it was not possible in that case to know when they started to work on the problems. We could only conjecture that a similar trend might exist for procrastinators, so using RAT did not hurt any individual's performance. Results of Anonymous Questionnaire. We collected 134 valid responses to our anonymous questionnaire; Figure <ref type="figure">10</ref> summarizes these responses. The feedback was largely positive. For instance, 69.4% of the respondents agree or strongly agree that the explanation by counterexamples helped them understand or fix the bug in their queries, and 93.2% would like to use similar tools in the future for assignments on querying databases. We also asked students which problems they found RAT to be most helpful (multiple choices were allowed): 58% voted for (g) and 94% voted for (i), which were indeed the most challenging ones. We also solicited open-ended comments on RAT . These comments were overwhelming positive and reinforces our conclusions from the quantitative analysis, e.g.:</p><p>&#8226; "It was incredibly useful debugging edge cases in the larger dataset not provided in our sample dataset with behavior not explicitly described in the problem set. " &#8226; "Overall, very helpful and would like to see similar testers for future assignments. " &#8226; "I liked how it gave us a concise example showing what we did wrong. "</p><p>Summary. Overall, the conclusion of our user study is positive. Students who used RAT did better, and their improvement cannot be attributed all to merely the fact that they opted to use an additional tool-RAT did add real value. Also, using RAT on one problem could also help with another problem, provided that the problems are similar. Finally, most students found RAT very useful and would like to use similar systems in the future.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="6">RELATED AND FUTURE WORK</head><p>Test data generation. Cosette <ref type="bibr">[12]</ref>, which targets at deciding SQL equivalence without any test instances, encodes SQL queries to constraints using symbolic execution, and uses a constraint solver to find counterexamples that differentiates two input queries. The main difference of RAT with Cosette is in the use of the given test data instance D. While the reliance on D has its own issues, it also has a number of advantages. First, since RAT outputs a subinstance of D as the counterexample, it produces tuples that preserve the context and semantic of the input schema. Cosette returns counterexamples of arbitrary integer values, which may be harder for people to read and perceive. Second, since RAT computes provenance from actual input tuples, it is oblivious to complex or even black-box conditions in the input query. In contrast, Cosette only handles integer domains and queries that can be encoded into symbolic expressions. Technically, Cosette uses incremental solving to dynamically increase the size of each symbolic relation, thus it returns counterexamples with least number of distinct tuples, but the total number of tuples is not minimized. Further, Cosette does not handle database constraints explicitly and when there are selection predicates comparing aggregate values with numbers, i.e., the last challenge we discussed in Section 3.1, Cosette may fail to return a counterexample in minutes (we found such a case when there is a "having count(distinct column) &gt; 2" in our modified TPC-H Q21). However, we note that some of our strategies like encoding integrity constraints into symbolic constraints and parameterizing aggregate queries can also be applied to Cosette. More detailed comparison can be found in the full version <ref type="bibr">[32]</ref>.</p><p>XData <ref type="bibr">[10]</ref> generates test data by covering different types of query mutants of the standard query, without looking into wrong queries. Qex <ref type="bibr">[46]</ref> is a tool for generating input relations and parameter values for a parameterized SQL query that also uses the SMT solver Z3, and aims at unit testing of SQL queries. It does not support nested queries and set operations and hence it cannot work for our problem because of our use of difference. Olston et al. <ref type="bibr">[36]</ref> studied the problem of generating small example data for dataflow programs to help users understand the behavior of their dataflow programs.</p><p>Provenance and witness. Data provenance has primarily been studied for non-aggregate queries: Buneman et al. <ref type="bibr">[9]</ref> defined why-provenance of an output tuple in the result set, which they call the witness basis. Green et al. <ref type="bibr">[19]</ref> introduced how-provenance with the general framework of provenance semiring. Sarma et al. <ref type="bibr">[41]</ref> gave algorithms for computing how-provenance over various RA operators in the Trio system. Amsterdamer et al. <ref type="bibr">[2]</ref> extended the provenance semiring framework <ref type="bibr">[19]</ref> to support aggregate queries. Besides these theoretical works, there are systems that capture different forms of provenance <ref type="bibr">[3,</ref><ref type="bibr">17,</ref><ref type="bibr">18,</ref><ref type="bibr">27,</ref><ref type="bibr">38,</ref><ref type="bibr">42]</ref>. However, to the best of our knowledge, no prior work considered SWP/SCP, and there are no systems available that support provenance for general SPJUD and aggregate queries.</p><p>Missing answers and why-not questions. The problem of explaining "why a certain tuple is not in the query answer" has been studied using two approaches: instancebased <ref type="bibr">[21]</ref><ref type="bibr">[22]</ref><ref type="bibr">[23]</ref><ref type="bibr">29]</ref> where explanations are (missing) input tuples, and query-based <ref type="bibr">[11,</ref><ref type="bibr">44]</ref> where explanations are based on query predicates or operators. Since we are trying to answer "why a tuple t is in the result of (Q 1 -Q 2 )(D)", the problem "why t is not in Q 2 (D)" and the instance-based approach are quite related to our problem. However, it cannot be directly applied to solve our problem: on one hand, existing works only consider monotone queries; on the other hand, the instance-based solution provides input tuples whose insertion will make the missing tuple t appear in the query result of Q 2 , which does not help differentiate the two queries.</p><p>Teaching or grading tool for programming. Due to popularity of students taking programming-related courses, teaching and grading tools for programming assignments that automatically generate feedback for submissions are receiving a lot of attention <ref type="bibr">[20,</ref><ref type="bibr">26,</ref><ref type="bibr">37]</ref>. In the database community, Chandra et al. built XData <ref type="bibr">[10]</ref> that can be used for grading by generating multiple test cases for different query mutants, as well as giving immediate feedback to student. The latter is similar to our RAT tool. Jiang and Nandi <ref type="bibr">[25,</ref><ref type="bibr">34]</ref> designed and prototyped interactive electronic textbook to help students get rapid feedbacks from querying the database with novel interaction techniques.</p><p>Explanations for query answers. Explanations based on tuples in the provenance has been recently studied by Wu-Madden <ref type="bibr">[47]</ref> and Roy-Suciu <ref type="bibr">[40]</ref>. These works take an aggregate query and a user question as input, find tuples whose removal will change the answer in the opposite direction, and returns a compact summary as explanations.</p><p>Future work. Building user-friendly tools to help students or programmers learn and debug database queries is an interesting research direction. In particular, building a similar tool with the full functionality of SQL queries is a challenging open problem.</p><p>[48] Jun Yang. 2018. RA (radb): A relational algebra interpreter over relational databases. <ref type="url">https://github.com/junyang/radb</ref>.</p><p>A PROOFS FROM SECTION 2.2</p><p>We will give the proofs of theorems in Table <ref type="table">1</ref> in this section.</p><p>A.1 SJ and SPU Queries</p><p>, the poly-time algorithm for SJ and SPU queries involve finding a smallest witness of t in D for Q 1 , and using the fact that since Q 2 is monotone and</p><p>The SWP for two SJ queries is poly-time solvable in combined complexity.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>. Let R 1 , ..., R k be all relations that participate in the SJ query Q 1 . For each relation R i , i &#8712; [1, k], there must exist exactly one tuple t i = t .R i (the R i component of t), which is part of the witness of t (under set semantic). Since each t i must satisfy all selection conditions for t to appear in Q 1 (D), the set</p><p>When projection is allowed, an output tuple may have multiple minimal witnesses, and we pick any one of them.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>T</head><p>2. The SWP for two SPU queries is polynomialtime solvable in combined complexity.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>. For an SPU query Q 1 , if t &#8712; Q 1 (D), at least one tuple t &#8242; in one of the input relations must satisfy the selection condition (if any), and its projected attribute values must match that of t. The smallest witness D t only consists of only t &#8242; . Since Q 2 is monotone and t Q 2 (D), we have t Q 2 (D t ). The running time to find D t = {t &#8242; } is polynomial in the size of the Q 1 and the input database.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>A.2 PJ Queries</head><p>For queries involving both projection and join, we show that it is NP-hard in query complexity to find the smallest witness, even when the query can be evaluated in poly-time.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>T</head><p>3. The SWP for two PJ queries is NP-hard in query complexity.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>. We prove the theorem by a reduction from the vertex cover problem with vertex degree at most 3, which is known to be NP-complete <ref type="bibr">[16]</ref> and is defined as follows: Given an undirected graph G(V , E) with vertex set V and edge set E, where the degree of every vertex is at most 3, decide whether there exists a vertex cover C of at most p vertices such that each edge in E is adjacent to at least one vertex in the set.</p><p>Construction. Given G(V , E), suppose V = { 1 , ..., n }, and E = {e 1 , &#8226; &#8226; &#8226; , e m }. We encode each vertex as a tuple in the relation R(A, Z , E 1 , E 2 , E 3 ). For each vertex i &#8712; V , R contains a tuple t i = ( i , z, e i 1 , e i 2 , e i 3 ), where e i 1 , e i 2 , e i 3 are identifiers of edges adjacent to i , i 1 &lt; i 2 &lt; i 3 . If the degree of i is less than 3, the identifiers are replaced by a null symbol " * ". The attribute Z = z is a constant for all tuples. In addition to R, we have m relations S 1 , ..., S m . Each S i , i &#8712; [1, m], has schema S i (E, Z ). For the edge e i &#8712; E, S i contains a single tuple (e i , z). Let D = (R, S 1 , ..., S m ) be the database instance.</p><p>Next, we construct Q 1 involving P that consist of m subqueries as follows: For all</p><p>), which operates on S i and R, checks for match of R.E 1 , R.E 2 , or R.E 3 with S i .E, and then projects on to Z . Then we construct Q 1 = q 1 q 2 ... q m ] using natural join on Z . All queries q i and Q 1 have a single attribute Z . Note that, initially, q i (D) = {(z)} for all i &#8712; [1, m], and therefore Q 1 (D) = {(z)} as well. The query Q 2 also outputs the attribute Z , but not the tuple {(z)}. We set Q 2 = &#960; Z (R R .Z S 1 .Z S 1 ) (the choice of S 1 is arbitrary), and therefore Q 2 (D) = {} is empty. The tuple t for which we want to find the smallest witness in</p><p>Below we argue that G has a vertex cover of size &#8804; p, if and only if the SWP instance above has a witness D &#8242; of size &#8804; p + m where m is the number of edges in G.</p><p>The "Only If" direction. Suppose we are given a vertex cover C with at most p vertices in G. We construct R &#8242; i = {t j | j &#8712; C}, and S &#8242; i = S i for all i &#8712; [1, m]. Since |C | &#8804; p, |D &#8242; | &#8804; p + m since each S i contains a single tuple. Since C is a vertex cover, for all edge e i = ( j , &#8467; ) &#8712; E, either j &#8712; C or &#8467; &#8712; C. Suppose without loss of generality (wlog.) j &#8712; C. Then wlog. assume t j = ( j , z, e i , e &#8242; , e &#8242;&#8242; ) where e &#8242; , e &#8242;&#8242; are other two adjacent edges on j (they could be * as well if the degree of j is &lt; 3). The tuple t j and the tuple S i (e i , z) will satisfy the join condition of q i (irrespective of the position of e i in t i ), and the projection will output (z). Since C is a vertex cover, for all i &#8712; [1, m], q i (D &#8242; ) = {(z)}. Therefore, Q 1 (D &#8242; ) = {(z)}. Q 2 (D &#8242; ) remains empty. Hence (z) &#8712; Q 1 (D &#8242; ) \ Q 2 (D &#8242; ) Therefore, D &#8242; is a witness of (z) of size at most p + m.</p><p>The "If" direction. Note that if (z) &#8712; Q 1 (D &#8242; ), (z) must be in the result of all subqueries q i (D &#8242; ), i &#8712; <ref type="bibr">[1, m]</ref>. And q i (D &#8242; ) returns (z) if and only if (a) S &#8242; i is not empty (i.e., S &#8242; i = S i since S i had only one tuple), and (b) if e i = ( j , &#8467; ), at least one of t j or t &#8467; must appear in R &#8242; to satisfy the join condition in q i ; otherwise q i An example reduction is shown in Figure <ref type="figure">11</ref>.</p><p>A.3 JU Queries T 4. The SWP for two JU queries is NP-hard in query complexity.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>. We reduce from the vertex cover problem. Construction. Suppose V = { 1 , ..., n } and E = {e 1 , &#8226; &#8226; &#8226; , e m } in the input graph G(V , E) in the vertex cover problem. For each vertex i in G, there is a relation R i (Z ) which consists of a single tuple (z). For each edge e i = ( j , &#8467; ) &#8712; E, we construct a query q i = R j &#8746; R &#8467; . Then we construct a query Q 1 = q 1 &#8226; &#8226; &#8226; q m , where the join is a natural join on Z . We construct We show that there exists a vertex cover C in G of size &#8804; p if and only if there is a witness D &#8242; for (z) of size &#8804; p.</p><p>The "Only If" direction. Consider a vertex cover C of G such that |C | &#8804; p. If i &#8712; C, then R &#8242; i = {(z)}, otherwise R &#8242; i = {}. Since C is a vertex cover, all edges must be covered. For an edge e i = ( j , &#8467; ), suppose wlog. j &#8712; C. Hence the subquery q i = R j &#8746; R &#8467; returns (z) on D &#8242; . Therefore, i , then we add vertex i to a set C. If (z) is in the result of Q 1 (D &#8242; ), (z) must be in the result of all subqueries q i (D &#8242; ) for all i &#8712; <ref type="bibr">[1, m]</ref>. For e i = ( j , &#8467; ), q i (D &#8242; ) returns (z) if and only if at least one of R &#8242; j and R &#8242; &#8467; is not empty; otherwise q i returns an empty result and thus Q 1 returns an empty result. Therefore, for each edge e i &#8712; E, at least one of its adjacent vertices j or &#8467; must exist in C. Hence C is a vertex cover, and |C | = |D &#8242; | &#8804; p.</p><p>On the other hand, the following theorem shows that if all unions appear after all joins (which we call JU * queries), then the SWP can be solved in poly-time in combined complexity. T 5. The SWP for two JU * queries is polynomial time solvable in combined complexity.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>. Let t &#8712; Q 1 (D)\Q 2 (D). According to Theorem 1, the SWP for SJ queries is polynomial time solvable in combined complexity. Hence, we look for the smallest witness of t in join-only part of Q 1 , and choose the one with smallest number of tuples. The running time is polynomial in both n = |D| and the size of the query.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>A.4 Size-Bounded SPJU Queries</head><p>Theorem 6 shows that if the SPJU queries are of bounded size (i.e. if we consider data complexity), there is a polynomial time algorithm for SWP. We prove this theorem using Proposition A.1, which is intuitive and known (e.g., <ref type="bibr">[39]</ref>). We use m-DNF to refer to a DNF where each minterm has at most m literals.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>A.1. Given an SPJU query Q, a database instance D, and an output tuple t &#8712; Q(D), the how-provenance of t in Q(D) can be transformed into a k + 1-DNF in polynomial time when Q is of bounded size, where k is the number of join operations in Q. T 6. The SWP for two SPJU queries is polynomialtime solvable in data complexity.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>P</head><p>. Let t be an output tuple in Q 1 (D) \ Q 2 (D). Since Q 2 is monotone, t Q 2 (D &#8242; ) for any D &#8242; &#8838; D. According to Proposition A.1, we can compute the how-provenance Prv Q 1 -Q 2 , D (t) in DNF in poly-time in data complexity. Then we scan the DNF to find the minterm with least number of literals, and this minterm represents the smallest witness for t in Q 1 (D) -Q 2 (D). The literals in this clause are the identifiers of tuples in the smallest witness. E.g., if Prv(t) = a + bc, then a forms the smallest witness.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>A.5 Queries Involving Difference</head><p>Before discussing general SPJUD queries, let's focus on one special class of SPJUD queries where all differences appear after all SPJU operators (which we call SPJUD * queries). More formally, we define this class using formal grammar: Q &#8594; q + |Q -Q, where q + is a terminal that represents SPJU queries. For instance, queries Q 1 and Q 2 in Example 1 are SPJUD * queries. The following theorem shows that the SWP can be solved in poly-time for SPJUD * queries.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>T</head><p>7. The SWP for two SPJUD * queries is polynomialtime solvable in data complexity.</p></div><note xmlns="http://www.tei-c.org/ns/1.0" place="foot" n="2" xml:id="foot_0"><p>Interestingly, we also found big synthetic test databases to be far more effective in catching incorrect queries than human graders, who had no auto-grading support back in Fall 2017.</p></note>
			<note xmlns="http://www.tei-c.org/ns/1.0" place="foot" n="3" xml:id="foot_1"><p>We note that the length of the expression can be much greater than this number because a variable may appear multiple times, and that simply setting variables to true may not lead to valid counterexample. In other words, the burden on the user to decipher a provenance expression will be higher than this particular definition of size implies.</p></note>
			<note xmlns="http://www.tei-c.org/ns/1.0" place="foot" n="4" xml:id="foot_2"><p>Here, a "query" refers to one (and only one) ofQ 1 -Q 2 and Q 2 -Q 1 that SCPchooses to focus on, so the top operator is always a difference.</p></note>
		</body>
		</text>
</TEI>
