Debian Codegraph @

unittest/gunit/graph_simplification-t.cc

raw symbols SCIP
1 /* Copyright (c) 2021, 2026, Oracle and/or its affiliates.
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License, version 2.0,
5 as published by the Free Software Foundation.
6
7 This program is designed to work with certain software (including
8 but not limited to OpenSSL) that is licensed under separate terms,
9 as designated in a particular file or component or in included license
10 documentation. The authors of MySQL hereby grant you an additional
11 permission to link the program and your derivative works with the
12 separately licensed software that they have either included with
13 the program or referenced in the documentation.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License, version 2.0, for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
23
24 #include <gtest/gtest.h>
25 #include <stdio.h>
26 #include <memory>
27 #include <random>
28 #include <utility>
29 #include <vector>
30
31 #include "my_alloc.h"
32 #include "scope_guard.h"
33 #include "sql/handler.h"
34 #include "sql/join_optimizer/access_path.h"
35 #include "sql/join_optimizer/bit_utils.h"
36 #include "sql/join_optimizer/graph_simplification.h"
37 #include "sql/join_optimizer/hypergraph.h"
38 #include "sql/join_optimizer/make_join_hypergraph.h"
39 #include "sql/join_optimizer/node_map.h"
40 #include "sql/join_optimizer/online_cycle_finder.h"
41 #include "sql/join_optimizer/relational_expression.h"
42 #include "sql/join_optimizer/subgraph_enumeration.h"
43 #include "sql/join_optimizer/trivial_receiver.h"
44 #include "sql/mem_root_array.h"
45 #include "sql/table.h"
46 #include "unittest/gunit/benchmark.h"
47 #include "unittest/gunit/fake_table.h"
48 #include "unittest/gunit/test_utils.h"
49
50 class Item;
51 class THD;
52
53 using hypergraph::NodeMap;
54 using testing::UnorderedElementsAre;
55
56 TEST(OnlineCycleFinderTest, SelfEdges) {
57 MEM_ROOT mem_root;
58 OnlineCycleFinder cycles(&mem_root, 10);
59 EXPECT_TRUE(cycles.AddEdge(5, 5));
60 EXPECT_TRUE(cycles.EdgeWouldCreateCycle(5, 5));
61 }
62
63 TEST(OnlineCycleFinderTest, Simple) {
64 MEM_ROOT mem_root;
65 OnlineCycleFinder cycles(&mem_root, 10);
66 EXPECT_FALSE(cycles.EdgeWouldCreateCycle(3, 5));
67 EXPECT_FALSE(cycles.EdgeWouldCreateCycle(5, 3));
68 EXPECT_FALSE(cycles.AddEdge(3, 5));
69 EXPECT_TRUE(cycles.EdgeWouldCreateCycle(5, 3));
70 }
71
72 TEST(OnlineCycleFinderTest, InverseOrderIsFine) {
73 MEM_ROOT mem_root;
74 OnlineCycleFinder cycles(&mem_root, 10);
75 EXPECT_FALSE(cycles.AddEdge(5, 3));
76 EXPECT_TRUE(cycles.EdgeWouldCreateCycle(3, 5));
77 }
78
79 TEST(OnlineCycleFinderTest, Transitive) {
80 MEM_ROOT mem_root;
81 OnlineCycleFinder cycles(&mem_root, 10);
82 EXPECT_FALSE(cycles.AddEdge(1, 3));
83 EXPECT_FALSE(cycles.AddEdge(3, 5));
84 EXPECT_FALSE(cycles.AddEdge(5, 6));
85 EXPECT_FALSE(cycles.AddEdge(5, 9));
86 EXPECT_FALSE(cycles.EdgeWouldCreateCycle(7, 1));
87 EXPECT_TRUE(cycles.EdgeWouldCreateCycle(6, 1));
88 EXPECT_TRUE(cycles.EdgeWouldCreateCycle(9, 1));
89 EXPECT_FALSE(cycles.EdgeWouldCreateCycle(1, 7));
90 EXPECT_FALSE(cycles.EdgeWouldCreateCycle(1, 5));
91 }
92
93 static void AddEdge(THD *thd, RelationalExpression::Type join_type,
94 NodeMap left, NodeMap right, double selectivity,
95 MEM_ROOT *mem_root, JoinHypergraph *graph) {
96 JoinPredicate pred;
97 pred.selectivity = selectivity;
98 pred.expr = new (mem_root) RelationalExpression(thd);
99 pred.expr->type = join_type;
100 pred.expr->nodes_in_subtree = left | right;
101 pred.estimated_bytes_per_row = 0; // To keep the compiler happy.
102 graph->edges.push_back(std::move(pred));
103 graph->graph.AddEdge(left, right);
104 }
105
106 namespace {
107
108 // Helper for destroying all the Fake_TABLE objects in a JoinHypergraph.
109 class DestroyNodes {
110 public:
111 explicit DestroyNodes(const JoinHypergraph *graph) : m_graph(graph) {}
112 void operator()() const {
113 for (const JoinHypergraph::Node &node : m_graph->nodes) {
114 destroy(static_cast<Fake_TABLE *>(node.table));
115 }
116 }
117
118 private:
119 const JoinHypergraph *m_graph;
120 };
121
122 // RAII class which destroys Fake_TABLE objects when it goes out of scope.
123 using NodeGuard = Scope_guard<DestroyNodes>;
124
125 } // namespace
126
127 [[nodiscard]] static NodeGuard AddNodes(int num_nodes, MEM_ROOT *mem_root,
128 JoinHypergraph *g) {
129 for (int i = 0; i < num_nodes; ++i) {
130 TABLE *table =
131 new (mem_root) Fake_TABLE(/*num_columns=*/1, /*nullable=*/true);
132 table->file->stats.records = 1000;
133
134 char *alias = mem_root->ArrayAlloc<char>(20);
135 snprintf(alias, 20, "t%d", i + 1);
136 table->alias = alias;
137
138 g->nodes.push_back(JoinHypergraph::Node{table, {}, {}});
139 g->graph.AddNode();
140 }
141
142 return {DestroyNodes(g)};
143 }
144
145 TEST(GraphSimplificationTest, SimpleStar) {
146 my_testing::Server_initializer initializer;
147 initializer.SetUp();
148
149 // A simple star-join with four tables, similar to what's in the paper.
150 MEM_ROOT mem_root;
151 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
152
153 NodeGuard node_guard = AddNodes(4, &mem_root, &g);
154 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b10, 0.999,
155 &mem_root, &g);
156 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b100, 0.5,
157 &mem_root, &g);
158 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b1000,
159 0.01, &mem_root, &g);
160
161 GraphSimplifier s(&g, &mem_root);
162
163 // Based on the selectivities, joining t1/t4 before t1/t2 will be the best
164 // choice. This means we'll broaden the t1/t2 edge to {t1,t4}/t2.
165 // (We could have put t4 on any side.)
166 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
167 EXPECT_EQ(0b1001, g.graph.edges[0].left);
168 EXPECT_EQ(0b10, g.graph.edges[0].right);
169 EXPECT_EQ(g.graph.edges[0].left, g.graph.edges[1].right);
170 EXPECT_EQ(g.graph.edges[0].right, g.graph.edges[1].left);
171
172 // The t1/t2 edge is no longer simple; verify we updated the graph right.
173 EXPECT_EQ(0b1100, g.graph.nodes[0].simple_neighborhood);
174 EXPECT_EQ(0b0000, g.graph.nodes[1].simple_neighborhood);
175 EXPECT_THAT(g.graph.nodes[0].simple_edges, UnorderedElementsAre(2, 4));
176 EXPECT_THAT(g.graph.nodes[0].complex_edges, UnorderedElementsAre(0));
177 EXPECT_THAT(g.graph.nodes[1].simple_edges, UnorderedElementsAre());
178 EXPECT_THAT(g.graph.nodes[1].complex_edges, UnorderedElementsAre(1));
179
180 // Next, we'll do t1/t4 before t1/t3 (again based on selectivities),
181 // broadening t1/t3 to {t1,t4}/t3.
182 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
183 EXPECT_EQ(0b1001, g.graph.edges[2].left);
184 EXPECT_EQ(0b100, g.graph.edges[2].right);
185 EXPECT_EQ(g.graph.edges[2].left, g.graph.edges[3].right);
186 EXPECT_EQ(g.graph.edges[2].right, g.graph.edges[3].left);
187
188 // Finally, t1-t3 before t1-t2, but these edges were already hyperedges.
189 // So {t1,t4}-{t2} will be extended to {t1,t3,t4}-{t2}.
190 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
191 EXPECT_EQ(0b1101, g.graph.edges[0].left);
192 EXPECT_EQ(0b10, g.graph.edges[0].right);
193 EXPECT_EQ(g.graph.edges[0].left, g.graph.edges[1].right);
194 EXPECT_EQ(g.graph.edges[0].right, g.graph.edges[1].left);
195
196 // No further simplification should be possible.
197 EXPECT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
198 s.DoSimplificationStep());
199 }
200
201 TEST(GraphSimplificationTest, TwoCycles) {
202 my_testing::Server_initializer initializer;
203 initializer.SetUp();
204
205 // Based on a real test case.
206 //
207 // .--t1\ .
208 // / | \ .
209 // | t2 t4
210 // \ | /
211 // `--t3/
212 //
213 MEM_ROOT mem_root;
214 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
215
216 NodeGuard node_guard = AddNodes(4, &mem_root, &g);
217 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b10, 0.999,
218 &mem_root, &g);
219 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b10, 0b100, 0.5,
220 &mem_root, &g);
221 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b100, 0.01,
222 &mem_root, &g);
223 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b1000, 0.2,
224 &mem_root, &g);
225 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b100, 0b1000,
226 0.8, &mem_root, &g);
227
228 // Do simplification steps until we can't do more. (The number doesn't matter
229 // all that much, but it should definitely be more than one.)
230 GraphSimplifier s(&g, &mem_root);
231 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
232 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
233 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
234 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
235 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
236 ASSERT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
237 ASSERT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
238 s.DoSimplificationStep());
239
240 // Finally, run DPhyp to make sure the graph is still consistent
241 // enough to find a solution.
242 TrivialReceiver receiver(g, &mem_root, /*subgraph_pair_limit=*/-1);
243 EXPECT_FALSE(EnumerateAllConnectedPartitions(g.graph, &receiver));
244 EXPECT_EQ(4, receiver.seen_nodes);
245 EXPECT_EQ(5, receiver.seen_subgraph_pairs);
246 EXPECT_TRUE(receiver.HasSeen(0b1111));
247 }
248
249 TEST(GraphSimplificationTest, ExistingHyperedge) {
250 my_testing::Server_initializer initializer;
251 initializer.SetUp();
252
253 // Based on a real test case.
254 //
255 // t1 --- t2 --- t3
256 // \ /
257 // \ /
258 // |
259 // |
260 // t4
261 //
262 MEM_ROOT mem_root;
263 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
264
265 NodeGuard node_guard = AddNodes(4, &mem_root, &g);
266 g.nodes[0].table->file->stats.records = 690;
267 g.nodes[1].table->file->stats.records = 6;
268 g.nodes[2].table->file->stats.records = 1;
269 g.nodes[3].table->file->stats.records = 1;
270
271 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b10, 0.2,
272 &mem_root, &g);
273 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b100, 0b10, 1.0,
274 &mem_root, &g);
275 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b11, 0b1000,
276 0.1, &mem_root, &g);
277
278 GraphSimplifier s(&g, &mem_root);
279
280 // First, one of t1-t2 and t2-t3 should come before the other.
281 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
282
283 // However, now all that can be done is to put t1-t2 before {t1,t2}-t4,
284 // and that is already always the case, so no further simplifications
285 // can be done.
286 EXPECT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
287 s.DoSimplificationStep());
288
289 // Finally, run DPhyp to make sure the graph is still consistent
290 // enough to find a solution, and that we are fully simplified.
291 TrivialReceiver receiver(g, &mem_root, /*subgraph_pair_limit=*/-1);
292 EXPECT_FALSE(EnumerateAllConnectedPartitions(g.graph, &receiver));
293 EXPECT_EQ(4, receiver.seen_nodes);
294 EXPECT_EQ(3, receiver.seen_subgraph_pairs);
295 EXPECT_TRUE(receiver.HasSeen(0b1111));
296 }
297
298 TEST(GraphSimplificationTest, IndirectHierarcicalJoins) {
299 my_testing::Server_initializer initializer;
300 initializer.SetUp();
301
302 // Based on yet another real test case.
303 //
304 // t3 ---- t2 -.
305 // \ / \ .
306 // \ / \ .
307 // \ / --- t1
308 // | /
309 // | /
310 // t4 ____/
311 //
312 // The only possible join order here is first the simple t2-t3 edge,
313 // then join in t4, and then t1. But since t1 has zero rows, it seems
314 // attractive to take the t1-{t2,t4} join first, and we need to disallow that.
315 MEM_ROOT mem_root;
316 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
317
318 NodeGuard node_guard = AddNodes(4, &mem_root, &g);
319 g.nodes[0].table->file->stats.records = 0;
320 g.nodes[1].table->file->stats.records = 171;
321 g.nodes[2].table->file->stats.records = 6;
322 g.nodes[3].table->file->stats.records = 3824;
323
324 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b10, 0b100, 0.2,
325 &mem_root, &g);
326 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b110, 0b1000,
327 1.0, &mem_root, &g);
328 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b1010, 0.1,
329 &mem_root, &g);
330
331 GraphSimplifier s(&g, &mem_root);
332
333 // No simplification steps should be possible, except for that we should
334 // discover that t1-{t2,t4} must come late (see above).
335 EXPECT_EQ(GraphSimplifier::APPLIED_NOOP, s.DoSimplificationStep());
336 EXPECT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
337 s.DoSimplificationStep());
338
339 // Finally, run DPhyp to make sure the graph is still consistent
340 // enough to find a solution, and that we are fully simplified.
341 TrivialReceiver receiver(g, &mem_root, /*subgraph_pair_limit=*/-1);
342 EXPECT_FALSE(EnumerateAllConnectedPartitions(g.graph, &receiver));
343 EXPECT_EQ(4, receiver.seen_nodes);
344 EXPECT_EQ(3, receiver.seen_subgraph_pairs);
345 EXPECT_TRUE(receiver.HasSeen(0b1111));
346 }
347
348 TEST(GraphSimplificationTest, IndirectHierarcicalJoins2) {
349 my_testing::Server_initializer initializer;
350 initializer.SetUp();
351
352 // An even more complicated case.
353 //
354 // t1----.
355 // / | |
356 // / | / \ .
357 // t5 | t4-t3
358 // \ | /
359 // \ | /
360 // \|/
361 // |
362 // |
363 // t2
364 //
365 // We need to understand that the join {t1,t4,t5}-t2 depends on the join t3-t4
366 // (i.e., we cannot say it should be done before that join). This isn't
367 // obvious at all; we need to understand that t3-t4 must be done before
368 // t1-{t3,t4} and propagate that information up to the t1 joins.
369 // (This is a case where our join inference algorithm fails, but we are being
370 // saved by the impossibility check.)
371 MEM_ROOT mem_root;
372 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
373
374 NodeGuard node_guard = AddNodes(5, &mem_root, &g);
375 g.nodes[0].table->file->stats.records = 1;
376 g.nodes[1].table->file->stats.records = 1;
377 g.nodes[2].table->file->stats.records = 1;
378 g.nodes[3].table->file->stats.records = 1;
379 g.nodes[4].table->file->stats.records = 1;
380
381 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b10000,
382 0.1, &mem_root, &g); // t1-t5.
383 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b100, 0b1000,
384 1.0, &mem_root, &g); // t3-t4.
385 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b1100, 0.1,
386 &mem_root, &g); // t1-{t3,t4}.
387 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b11001, 0b10,
388 0.01, &mem_root, &g); // {t1,t4,t5}-t2.
389
390 GraphSimplifier s(&g, &mem_root);
391
392 // We want first to put {t1,t4,t5}-t2 before t3-t4, but discover it is
393 // impossible, so we apply the opposite.
394 EXPECT_EQ(GraphSimplifier::APPLIED_NOOP, s.DoSimplificationStep());
395
396 // t1-{t3,t4} can be ordered relative to {t1}-{t5}, but after that,
397 // no further simplifications should be possible.
398 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
399 EXPECT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
400 s.DoSimplificationStep());
401
402 // Finally, run DPhyp to make sure the graph is still consistent
403 // enough to find a solution, and that we are fully simplified.
404 TrivialReceiver receiver(g, &mem_root, /*subgraph_pair_limit=*/-1);
405 EXPECT_FALSE(EnumerateAllConnectedPartitions(g.graph, &receiver));
406 EXPECT_EQ(5, receiver.seen_nodes);
407 EXPECT_EQ(4, receiver.seen_subgraph_pairs);
408 EXPECT_TRUE(receiver.HasSeen(0b11111));
409 }
410
411 TEST(GraphSimplificationTest, ConflictRules) {
412 my_testing::Server_initializer initializer;
413 initializer.SetUp();
414
415 // We set up a simple t1-t2-t3 chain join, but with a twist;
416 // we'd like to do t2-t3 before t1-t2 (because t3 has zero rows),
417 // but we add a conflict rule {t2} → t1 on the edge to prevent that.
418 // Naturally, in a real query, that conflict rule would be absorbed
419 // into a hyperedge, but we specifically want to test our handling
420 // of unabsorbed conflict rules here (which can occur
421 // in more complex graphs).
422 MEM_ROOT mem_root;
423 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
424
425 NodeGuard node_guard = AddNodes(3, &mem_root, &g);
426 g.nodes[0].table->file->stats.records = 100;
427 g.nodes[1].table->file->stats.records = 10000;
428 g.nodes[2].table->file->stats.records = 0;
429
430 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b10, 1.0,
431 &mem_root, &g);
432 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b10, 0b100, 1.0,
433 &mem_root, &g);
434
435 g.edges[1].expr->conflict_rules.init(&mem_root);
436 g.edges[1].expr->conflict_rules.push_back(ConflictRule{0b10, 0b1});
437
438 GraphSimplifier s(&g, &mem_root);
439
440 // It would be fine here to have one simplification step,
441 // in theory (t1-t2 before t2-t3), because it's not immediately
442 // obvious that it's a no-op. But our implementation chooses to
443 // force-insert that as an edge when we try the failed “t2-t3
444 // before t1-t2” simplification, so we get the opposite first.
445 EXPECT_EQ(GraphSimplifier::APPLIED_NOOP, s.DoSimplificationStep());
446 EXPECT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
447 s.DoSimplificationStep());
448
449 // Finally, run DPhyp to make sure the graph is still consistent
450 // enough to find a solution, and that we are fully simplified.
451 TrivialReceiver receiver(g, &mem_root, /*subgraph_pair_limit=*/-1);
452 EXPECT_FALSE(EnumerateAllConnectedPartitions(g.graph, &receiver));
453 EXPECT_EQ(3, receiver.seen_nodes);
454 EXPECT_EQ(2, receiver.seen_subgraph_pairs);
455 EXPECT_TRUE(receiver.HasSeen(0b111));
456 }
457
458 TEST(GraphSimplificationTest, Antijoin) {
459 my_testing::Server_initializer initializer;
460 initializer.SetUp();
461
462 // (t1_100 JOIN t2_100) ANTIJOIN t3_10000. Normally, it would be better to
463 // delay the t2-t3 join to get a more even cost, but since the antijoin
464 // produces effectively zero rows, it should be taken immediately.
465 MEM_ROOT mem_root;
466 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
467
468 NodeGuard node_guard = AddNodes(3, &mem_root, &g);
469 g.nodes[0].table->file->stats.records = 100;
470 g.nodes[1].table->file->stats.records = 100;
471 g.nodes[2].table->file->stats.records = 10000;
472
473 AddEdge(initializer.thd(), RelationalExpression::INNER_JOIN, 0b1, 0b10, 1.0,
474 &mem_root, &g);
475 AddEdge(initializer.thd(), RelationalExpression::ANTIJOIN, 0b10, 0b100, 1.0,
476 &mem_root, &g);
477
478 GraphSimplifier s(&g, &mem_root);
479
480 // t1-t2 should be broadened to t1-{t2,t3}, so that t2-t3 is taken first.
481 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
482 EXPECT_EQ(0b1, g.graph.edges[0].left);
483 EXPECT_EQ(0b110, g.graph.edges[0].right);
484 EXPECT_EQ(g.graph.edges[0].left, g.graph.edges[1].right);
485 EXPECT_EQ(g.graph.edges[0].right, g.graph.edges[1].left);
486
487 EXPECT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
488 s.DoSimplificationStep());
489 }
490
491 TEST(GraphSimplificationTest, CycleNeighboringHyperedges) {
492 my_testing::Server_initializer initializer;
493 initializer.SetUp();
494
495 MEM_ROOT mem_root;
496 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
497
498 /*
499 * Based on a real test case:
500 *
501 * t1___
502 * | \ t6
503 * | \ /
504 * /|\ +-- t5
505 * / | \ / \
506 * / | \ / t7
507 * t2--t3--t4
508 * \____/
509 *
510 * The problem with simplifying this graph is that the initial set of
511 * constraints says that all three of t2-t3, t2-t4 and t3-t4 must come
512 * before t1-{t2,t3,t4}. So if we later try to add a constraint that makes the
513 * latter join come before one of those three joins, the online cycle finder
514 * will tell us it's impossible because we get a cycle in the before-after
515 * relationship. Which is true, but it doesn't take into account that the
516 * final plan will never use more than two of those joins in order to join t2,
517 * t3 and t4. So the graph can still be joinable using two of the edges even
518 * if the third edge is involved in a cycle in the before-after graph.
519 */
520
521 NodeGuard node_guard = AddNodes(7, &mem_root, &g);
522 g.nodes[0].table->file->stats.records = 1500;
523 g.nodes[1].table->file->stats.records = 6000;
524 g.nodes[2].table->file->stats.records = 700;
525 g.nodes[3].table->file->stats.records = 200;
526 g.nodes[4].table->file->stats.records = 150;
527 g.nodes[5].table->file->stats.records = 1000;
528 g.nodes[6].table->file->stats.records = 1000;
529
530 THD *thd = initializer.thd();
531 AddEdge(thd, RelationalExpression::LEFT_JOIN, 0b1, 0b1110, 0.0007, &mem_root,
532 &g);
533 AddEdge(thd, RelationalExpression::INNER_JOIN, 0b10, 0b100, 0.005, &mem_root,
534 &g);
535 AddEdge(thd, RelationalExpression::INNER_JOIN, 0b10, 0b1000, 0.005, &mem_root,
536 &g);
537 AddEdge(thd, RelationalExpression::INNER_JOIN, 0b100, 0b1000, 0.005,
538 &mem_root, &g);
539 AddEdge(thd, RelationalExpression::INNER_JOIN, 0b1001, 0b010000, 0.01,
540 &mem_root, &g);
541 AddEdge(thd, RelationalExpression::INNER_JOIN, 0b10000, 0b100000, 0.02,
542 &mem_root, &g);
543 AddEdge(thd, RelationalExpression::INNER_JOIN, 0b10000, 0b1000000, 0.021,
544 &mem_root, &g);
545
546 // Simplify the above graph as much as possible. The exact steps are not all
547 // that important. What matters, is that we're able to get past the third call
548 // to DoSimplificationStep(), where we previously hit infinite recursion, and
549 // continue to simplify the graph also after we hit the problematic condition.
550 GraphSimplifier s(&g, &mem_root);
551
552 // First two simplifications are applied by adding the following constraints:
553 //
554 // t3-t4 before t2-t3
555 // t1-t5 before t2-t4
556 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
557 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
558
559 // Here we hit the condition that we want to exercise with this test case. We
560 // want to add the constraint that {t1,t4}-t5 is before t1-{t2,t3,t4}, but we
561 // detect that the graph is not joinable if we do that. Usually, when we
562 // detect this, we would add the opposite constraint and return APPLIED_NOOP.
563 // However, the online cycle finder detects that adding the opposite
564 // constraint will cause a cycle in the before-after graph, and refuses to add
565 // it (this is because the online cycle finder doesn't take into account that
566 // a cyclic hypergraph contains redundant edges, so we won't end up following
567 // all the edges). Since we can't apply the opposite constraint, we instead
568 // remove the problematic constraint from the set of potential simplifications
569 // and retry with the second most promising simplification. This step
570 // completes successfully and adds the constraint t2-t3 is before t2-t4.
571 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
572
573 // The next two simplifications we try are:
574 //
575 // {t1,t4}-t5 before t3-t4
576 // {t1,t4}-t5 before t2-t3
577 //
578 // Both of these make the resulting graph not joinable, so we reject both and
579 // instead add the opposite constraint. This time, the opposite constraints
580 // are added successfully (as seen by returning APPLIED_NOOP).
581 EXPECT_EQ(GraphSimplifier::APPLIED_NOOP, s.DoSimplificationStep());
582 EXPECT_EQ(GraphSimplifier::APPLIED_NOOP, s.DoSimplificationStep());
583
584 // Attempts to add the following constraints are successful:
585 //
586 // t5-t6 before t2-t4
587 // t5-t7 before t2-t4
588 // t5-t6 before {t1,t4}-t5
589 // t5-t7 before {t1,t4}-t5
590 // t5-t6 before t5-t7
591 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
592 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
593 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
594 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
595 EXPECT_EQ(GraphSimplifier::APPLIED_SIMPLIFICATION, s.DoSimplificationStep());
596
597 // Nothing more to simplify.
598 EXPECT_EQ(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
599 s.DoSimplificationStep());
600
601 // Verify that the simplified graph is consistent.
602 TrivialReceiver receiver(g, &mem_root, /*subgraph_pair_limit=*/-1);
603 EXPECT_FALSE(EnumerateAllConnectedPartitions(g.graph, &receiver));
604 EXPECT_EQ(7, receiver.seen_nodes);
605 EXPECT_EQ(6, receiver.seen_subgraph_pairs);
606 EXPECT_TRUE(receiver.HasSeen(0b1111111));
607 }
608
609 TEST(GraphSimplificationTest, CyclicInformationSchemaView) {
610 my_testing::Server_initializer initializer;
611 initializer.SetUp();
612
613 MEM_ROOT mem_root;
614 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
615
616 /*
617 This test case is based on the INFORMATION_SCHEMA.STATISTICS view. When
618 invoking graph simplification on it, the resulting simplified graph could in
619 some circumstances (depending on table sizes and statistics) be impossible
620 to join.
621 */
622
623 NodeGuard node_guard = AddNodes(8, &mem_root, &g);
624 g.nodes[0].table->file->stats.records = 1399;
625 g.nodes[1].table->file->stats.records = 4706;
626 g.nodes[2].table->file->stats.records = 316;
627 g.nodes[3].table->file->stats.records = 222;
628 g.nodes[4].table->file->stats.records = 259;
629 g.nodes[5].table->file->stats.records = 6;
630 g.nodes[6].table->file->stats.records = 1;
631 g.nodes[7].table->file->stats.records = 1;
632
633 THD *thd = initializer.thd();
634 // t0-t1
635 AddEdge(thd, RelationalExpression::INNER_JOIN, TableBitmap(0), TableBitmap(1),
636 0.000212, &mem_root, &g);
637 // t3-t4
638 AddEdge(thd, RelationalExpression::INNER_JOIN, TableBitmap(3), TableBitmap(4),
639 0.00386, &mem_root, &g);
640 // t5-t6
641 AddEdge(thd, RelationalExpression::INNER_JOIN, TableBitmap(5), TableBitmap(6),
642 1.0, &mem_root, &g);
643 // t3-t5
644 AddEdge(thd, RelationalExpression::INNER_JOIN, TableBitmap(3), TableBitmap(5),
645 0.167, &mem_root, &g);
646 // t2-t3
647 AddEdge(thd, RelationalExpression::INNER_JOIN, TableBitmap(2), TableBitmap(3),
648 0.0045, &mem_root, &g);
649 // t0-{t2,t3}
650 AddEdge(thd, RelationalExpression::INNER_JOIN, TableBitmap(0),
651 TableBitmap(2, 3), 0.00316, &mem_root, &g);
652 // {t1,t2,t3,t5}-t7
653 AddEdge(thd, RelationalExpression::LEFT_JOIN, TableBitmap(1, 2, 3, 5),
654 TableBitmap(7), 0.001, &mem_root, &g);
655 // t0-t2
656 AddEdge(thd, RelationalExpression::INNER_JOIN, TableBitmap(0), TableBitmap(2),
657 0.00316, &mem_root, &g);
658
659 // Simplify the above graph as much as possible. The exact steps are not all
660 // that important. What matters, is that we're not making a hypergraph that is
661 // not joinable.
662 GraphSimplifier s(&g, &mem_root);
663 while (s.DoSimplificationStep() !=
664 GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE) {
665 }
666
667 // Verify that the simplified graph is joinable.
668 TrivialReceiver receiver(g, &mem_root, /*subgraph_pair_limit=*/-1);
669 EXPECT_FALSE(EnumerateAllConnectedPartitions(g.graph, &receiver));
670 EXPECT_EQ(8, receiver.seen_nodes);
671 EXPECT_TRUE(receiver.HasSeen(0b11111111));
672
673 // And it should have limited the search space as much as possible (N-1 joins
674 // considered to join together N tables).
675 EXPECT_EQ(7, receiver.seen_subgraph_pairs);
676 }
677
678 [[nodiscard]] static NodeGuard CreateStarJoin(THD *thd, int graph_size,
679 std::mt19937 *engine,
680 MEM_ROOT *mem_root,
681 JoinHypergraph *g) {
682 std::uniform_int_distribution<int> table_size(1, 10000);
683 NodeGuard node_guard = AddNodes(graph_size, mem_root, g);
684 for (int node_idx = 0; node_idx < graph_size; ++node_idx) {
685 g->nodes[node_idx].table->file->stats.records = table_size(*engine);
686 }
687
688 std::uniform_real_distribution<double> selectivity(0.001, 1.000);
689 for (int node_idx = 1; node_idx < graph_size; ++node_idx) {
690 AddEdge(thd, RelationalExpression::INNER_JOIN, 0b1, NodeMap{1} << node_idx,
691 selectivity(*engine), mem_root, g);
692 }
693
694 return node_guard;
695 }
696
697 [[nodiscard]] static NodeGuard CreateCliqueJoin(THD *thd, int graph_size,
698 std::mt19937 *engine,
699 MEM_ROOT *mem_root,
700 JoinHypergraph *g) {
701 std::uniform_int_distribution<int> table_size(1, 10000);
702 NodeGuard node_guard = AddNodes(graph_size, mem_root, g);
703 for (int node_idx = 0; node_idx < graph_size; ++node_idx) {
704 g->nodes[node_idx].table->file->stats.records = table_size(*engine);
705 }
706
707 std::uniform_real_distribution<double> selectivity(0.001, 1.000);
708 for (int node1_idx = 0; node1_idx < graph_size; ++node1_idx) {
709 for (int node2_idx = node1_idx + 1; node2_idx < graph_size; ++node2_idx) {
710 AddEdge(thd, RelationalExpression::INNER_JOIN, NodeMap{1} << node1_idx,
711 NodeMap{1} << node2_idx, selectivity(*engine), mem_root, g);
712 }
713 }
714
715 return node_guard;
716 }
717
718 TEST(GraphSimplificationTest, UndoRedo) {
719 my_testing::Server_initializer initializer;
720 initializer.SetUp();
721
722 // Get consistent seeds between runs and platforms.
723 std::mt19937 engine(1234);
724
725 MEM_ROOT mem_root;
726 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
727 NodeGuard node_guard = CreateStarJoin(initializer.thd(), /*graph_size=*/20,
728 &engine, &mem_root, &g);
729 GraphSimplifier s(&g, &mem_root);
730
731 std::uniform_int_distribution<int> back_or_forward(0, 4);
732 for (;;) { // Termination condition within loop.
733 if (s.num_steps_done() == 0) {
734 // We can only go forward.
735 ASSERT_NE(GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE,
736 s.DoSimplificationStep());
737 } else {
738 // With 20% probability, undo a step. Otherwise, do one.
739 // This ensures we get to try both undos and redos.
740 if (back_or_forward(engine) == 0) {
741 s.UndoSimplificationStep();
742 } else {
743 if (s.DoSimplificationStep() ==
744 GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE) {
745 // We're all simplified.
746 break;
747 }
748 }
749 }
750 }
751
752 // This is just an empirical number; it can change if the heuristics change.
753 // But it shouldn't change if we remove the undo code or change the seed.
754 EXPECT_EQ(171, s.num_steps_done());
755 }
756
757 static void BM_FullySimplifyStarJoin(int graph_size, size_t num_iterations) {
758 StopBenchmarkTiming();
759
760 // Get consistent seeds between runs and platforms.
761 std::mt19937 engine(1234);
762
763 for (size_t i = 0; i < num_iterations; ++i) {
764 MEM_ROOT mem_root;
765 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
766 my_testing::Server_initializer initializer;
767 initializer.SetUp();
768
769 NodeGuard node_guard =
770 CreateStarJoin(initializer.thd(), graph_size, &engine, &mem_root, &g);
771
772 StartBenchmarkTiming();
773 GraphSimplifier s(&g, &mem_root);
774 while (s.DoSimplificationStep() !=
775 GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE)
776 ;
777 StopBenchmarkTiming();
778 }
779 }
780
781 static void BM_FullySimplifyStarJoin10(size_t num_iterations) {
782 BM_FullySimplifyStarJoin(10, num_iterations);
783 }
784 static void BM_FullySimplifyStarJoin20(size_t num_iterations) {
785 BM_FullySimplifyStarJoin(20, num_iterations);
786 }
787 static void BM_FullySimplifyStarJoin30(size_t num_iterations) {
788 BM_FullySimplifyStarJoin(30, num_iterations);
789 }
790 static void BM_FullySimplifyStarJoin40(size_t num_iterations) {
791 BM_FullySimplifyStarJoin(40, num_iterations);
792 }
793 static void BM_FullySimplifyStarJoin50(size_t num_iterations) {
794 BM_FullySimplifyStarJoin(50, num_iterations);
795 }
796 BENCHMARK(BM_FullySimplifyStarJoin10)
797 BENCHMARK(BM_FullySimplifyStarJoin20)
798 BENCHMARK(BM_FullySimplifyStarJoin30)
799 BENCHMARK(BM_FullySimplifyStarJoin40)
800 BENCHMARK(BM_FullySimplifyStarJoin50)
801 // NOTE: 100-way star joins are quoted as 160 ms in the paper,
802 // but since MAX_TABLES == 61, we cannot compare directly.
803 // Extrapolation indicates that we are doing fairly well, though.
804
805 static void BM_FullySimplifyCliqueJoin(int graph_size, size_t num_iterations) {
806 StopBenchmarkTiming();
807
808 // Get consistent seeds between runs and platforms.
809 std::mt19937 engine(1234);
810
811 for (size_t i = 0; i < num_iterations; ++i) {
812 MEM_ROOT mem_root;
813 JoinHypergraph g(&mem_root, /*query_block=*/nullptr);
814 my_testing::Server_initializer initializer;
815 initializer.SetUp();
816
817 NodeGuard node_guard =
818 CreateCliqueJoin(initializer.thd(), graph_size, &engine, &mem_root, &g);
819
820 StartBenchmarkTiming();
821 GraphSimplifier s(&g, &mem_root);
822 while (s.DoSimplificationStep() !=
823 GraphSimplifier::NO_SIMPLIFICATION_POSSIBLE)
824 ;
825 StopBenchmarkTiming();
826 }
827 }
828
829 static void BM_FullySimplifyCliqueJoin10(size_t num_iterations) {
830 BM_FullySimplifyCliqueJoin(10, num_iterations);
831 }
832 static void BM_FullySimplifyCliqueJoin20(size_t num_iterations) {
833 BM_FullySimplifyCliqueJoin(20, num_iterations);
834 }
835 static void BM_FullySimplifyCliqueJoin30(size_t num_iterations) {
836 BM_FullySimplifyCliqueJoin(30, num_iterations);
837 }
838 // static void BM_FullySimplifyCliqueJoin40(size_t num_iterations) {
839 // BM_FullySimplifyCliqueJoin(40, num_iterations);
840 // }
841 // static void BM_FullySimplifyCliqueJoin50(size_t num_iterations) {
842 // BM_FullySimplifyCliqueJoin(50, num_iterations);
843 // }
844 BENCHMARK(BM_FullySimplifyCliqueJoin10)
845 BENCHMARK(BM_FullySimplifyCliqueJoin20)
846 BENCHMARK(BM_FullySimplifyCliqueJoin30)
847
848 // Too slow to run on every commit, but can be enabled manually without
849 // problems.
850 // BENCHMARK(BM_FullySimplifyCliqueJoin40)
851 // BENCHMARK(BM_FullySimplifyCliqueJoin50)