-
Notifications
You must be signed in to change notification settings - Fork 448
/
ShardedTableEpochConsistencyTest.cpp
1178 lines (984 loc) · 39.8 KB
/
ShardedTableEpochConsistencyTest.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2022 HEAVY.AI, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "DBHandlerTestHelpers.h"
#include "Shared/SysDefinitions.h"
#include "TestHelpers.h"
#ifndef BASE_PATH
#define BASE_PATH "./tmp"
#endif
extern bool g_enable_fsi;
class EpochConsistencyTest : public DBHandlerTestFixture {
protected:
static void SetUpTestSuite() {
createDBHandler();
dropUser();
sql("create user non_super_user (password = 'HyperInteractive');");
sql("grant all on database " + shared::kDefaultDbName + " to non_super_user;");
}
static void TearDownTestSuite() { dropUser(); }
static void dropUser() {
switchToAdmin();
sql("drop user IF EXISTS non_super_user;");
}
static void loginTestUser() { login("non_super_user", "HyperInteractive"); }
void SetUp() override {
DBHandlerTestFixture::SetUp();
sql("drop table if exists test_table;");
}
void TearDown() override {
sql("drop table if exists test_table;");
DBHandlerTestFixture::TearDown();
}
std::string getGoodFilePath() {
return "../../Tests/Import/datafiles/sharded_example_1.csv";
}
std::string getBadFilePath() {
return "../../Tests/Import/datafiles/sharded_example_2.csv";
}
std::string getShardedMultiFragmentFilePath() {
return "../../Tests/Import/datafiles/sharded_2_col_1_20.csv";
}
void assertTableEpochs(const std::vector<int32_t>& expected_table_epochs) {
auto [db_handler, session_id] = getDbHandlerAndSessionId();
const auto& catalog = getCatalog();
auto table_id = catalog.getMetadataForTable("test_table", false)->tableId;
std::vector<TTableEpochInfo> table_epochs;
db_handler->get_table_epochs(
table_epochs, session_id, catalog.getDatabaseId(), table_id);
ASSERT_EQ(expected_table_epochs.size(), table_epochs.size());
for (size_t i = 0; i < expected_table_epochs.size(); i++) {
EXPECT_EQ(expected_table_epochs[i], table_epochs[i].table_epoch);
}
}
void setUpTestTableWithInconsistentEpochs(const std::string& db_name = {}) {
sql("create table test_table(a int, b tinyint, c text encoding none, shard key(a)) "
"with (shard_count = 2, max_rollback_epochs = 25);");
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1});
assertInitialImportResultSet();
// Inconsistent epochs have to be set manually, since all write queries now level
// epochs
setTableEpochs({1, 2}, db_name);
assertTableEpochs({1, 2});
assertInitialImportResultSet();
}
// Asserts that the result set is equal to the expected value after the initial import
void assertInitialImportResultSet() {
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(10), "test_10"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
// Sets table epochs across shards and leaves as indicated by the flattened epoch
// vector. For instance, in order to set the epochs for a table with 3 shards on
// a distributed setup with 2 leaves, the epochs vector will contain epochs for
// corresponding shards/leaves in the form: { shard_1_leaf_1, shard_2_leaf_1,
// shard_3_leaf_1, shard_1_leaf_2, shard_2_leaf_2, shard_3_leaf_2 }
void setTableEpochs(const std::vector<int32_t>& table_epochs,
const std::string& db_name = {}) {
auto [db_handler, session_id] = getDbHandlerAndSessionId();
const auto& catalog = getCatalog();
auto logical_table = catalog.getMetadataForTable("test_table", false);
auto physical_tables = catalog.getPhysicalTablesDescriptors(logical_table);
std::vector<TTableEpochInfo> table_epoch_info_vector;
for (size_t i = 0; i < table_epochs.size(); i++) {
TTableEpochInfo table_epoch_info;
auto table_index = i % physical_tables.size();
table_epoch_info.table_id = physical_tables[table_index]->tableId;
table_epoch_info.table_epoch = table_epochs[i];
table_epoch_info.leaf_index = i / physical_tables.size();
table_epoch_info_vector.emplace_back(table_epoch_info);
}
if (db_name.empty()) {
switchToAdmin();
} else {
login("admin", "HyperInteractive", db_name);
}
db_handler->set_table_epochs(
session_id, catalog.getDatabaseId(), table_epoch_info_vector);
}
};
/**
* Class that provides an interface for checkpoint failure mocking
*/
class CheckpointFailureMock {
public:
CheckpointFailureMock() : throw_on_checkpoint_(false) {}
virtual ~CheckpointFailureMock() = default;
void throwOnCheckpoint(bool throw_on_checkpoint) {
throw_on_checkpoint_ = throw_on_checkpoint;
}
protected:
bool throw_on_checkpoint_;
};
/**
* Mock file mgr class mainly used for testing checkpoint failure.
* However, in addition to the `checkpoint` method, calls to
* `putBuffer` and `fetchBuffer` are proxied to the original/parent
* file mgr, since these methods are called as part of checkpoint
* calls that originate from CPU buffers.
*/
class MockFileMgr : public CheckpointFailureMock, public File_Namespace::FileMgr {
public:
MockFileMgr(std::shared_ptr<File_Namespace::FileMgr> file_mgr)
: File_Namespace::FileMgr(file_mgr->lastCheckpointedEpoch())
, parent_file_mgr_(file_mgr) {
CHECK(parent_file_mgr_);
}
File_Namespace::FileBuffer* putBuffer(const ChunkKey& chunk_key,
AbstractBuffer* buffer,
const size_t num_bytes) override {
return parent_file_mgr_->putBuffer(chunk_key, buffer, num_bytes);
}
void fetchBuffer(const ChunkKey& chunk_key,
AbstractBuffer* dest_buffer,
const size_t num_bytes) override {
parent_file_mgr_->fetchBuffer(chunk_key, dest_buffer, num_bytes);
}
void checkpoint() override {
if (throw_on_checkpoint_) {
throw std::runtime_error{"Mock checkpoint exception"};
} else {
parent_file_mgr_->checkpoint();
}
}
private:
std::shared_ptr<File_Namespace::FileMgr> parent_file_mgr_;
};
class EpochRollbackTest : public EpochConsistencyTest,
public testing::WithParamInterface<bool> {
public:
static std::string testParamsToString(const testing::TestParamInfo<bool>& param_info) {
auto is_checkpoint_error = param_info.param;
return is_checkpoint_error ? "checkpoint_error" : "query_error";
}
protected:
static void SetUpTestSuite() { EpochConsistencyTest::SetUpTestSuite(); }
static void TearDownTestSuite() { EpochConsistencyTest::TearDownTestSuite(); }
void SetUp() override {
EpochConsistencyTest::SetUp();
loginTestUser();
}
bool isCheckpointError() { return GetParam(); }
void setUpReplicatedTestTableWithInconsistentEpochs() {
sql("create table test_table(a int, b tinyint, c text encoding none) "
"with (partitions = 'REPLICATED');");
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1});
assertInitialImportResultSet();
// Inconsistent epochs have to be set manually, since all write queries now level
// epochs
setTableEpochs({2});
assertTableEpochs({2});
assertInitialImportResultSet();
}
void assertInitialTableState() {
assertTableEpochs({1, 2});
assertInitialImportResultSet();
}
void sendFailedImportQuery() {
if (isCheckpointError()) {
queryAndAssertCheckpointError("copy test_table from '" + getGoodFilePath() + "';");
} else {
sql("copy test_table from '" + getBadFilePath() + "' with (max_reject = 0);");
}
}
void sendFailedInsertQuery() {
if (isCheckpointError()) {
queryAndAssertCheckpointError(
"insert into test_table values (1, 110, 'test_110');");
} else {
EXPECT_ANY_THROW(sql("insert into test_table values (1, 10000, 'test_10000');"));
}
}
void sendReplicatedTableFailedInsertQuery() { sendFailedInsertQuery(); }
void sendFailedUpdateQuery() {
if (isCheckpointError()) {
queryAndAssertCheckpointError(
"update test_table set b = b + 1 where b = 100 or b = 20;");
} else {
EXPECT_ANY_THROW(
sql("update test_table set b = case when b = 10 then 10000 else b + 1 end;"));
}
}
void sendFailedVarlenUpdateQuery() {
if (isCheckpointError()) {
queryAndAssertCheckpointError(
"update test_table set b = 110, c = 'test_110' where b = 10;");
} else {
EXPECT_ANY_THROW(
sql("update test_table set b = case when b = 10 then 10000 else b + 1 end, c = "
"'test';"));
}
}
void sendFailedDeleteQuery() {
if (isCheckpointError()) {
queryAndAssertCheckpointError("delete from test_table where b = 100 or b = 20;");
} else {
EXPECT_ANY_THROW(sql("delete from test_table where b = 2 or b = 10/0;"));
}
}
void sendFailedItasQuery() {
if (isCheckpointError()) {
queryAndAssertCheckpointError(
"insert into test_table (select * from test_table where b = 1 or b = 20);");
} else {
EXPECT_ANY_THROW(
sql("insert into test_table (select a, case when b = 10 then 10000 else b + 1 "
"end, c from test_table);"));
}
}
void queryAndAssertCheckpointError(const std::string& query) {
initializeCheckpointFailureMock();
queryAndAssertException(query, "Mock checkpoint exception");
resetCheckpointFailureMock();
}
void initializeCheckpointFailureMock() {
const auto& catalog = getCatalog();
auto global_file_mgr = catalog.getDataMgr().getGlobalFileMgr();
auto physical_tables = getPhysicalTestTables();
auto file_mgr = getFileMgr();
CHECK(file_mgr);
auto mock_file_mgr = std::make_shared<MockFileMgr>(file_mgr);
global_file_mgr->setFileMgr(
catalog.getDatabaseId(), physical_tables.back()->tableId, mock_file_mgr);
checkpoint_failure_mock_ = mock_file_mgr.get();
ASSERT_EQ(checkpoint_failure_mock_, dynamic_cast<MockFileMgr*>(getFileMgr().get()));
checkpoint_failure_mock_->throwOnCheckpoint(true);
}
void resetCheckpointFailureMock() {
// GlobalFileMgr resets the file mgr for the table on rollback
// and so the assertion here is to ensure that the mock file
// mgr is no longer used.
ASSERT_EQ(dynamic_cast<MockFileMgr*>(getFileMgr().get()), nullptr);
checkpoint_failure_mock_ = nullptr;
}
std::vector<const TableDescriptor*> getPhysicalTestTables() {
const auto& catalog = getCatalog();
auto logical_table = catalog.getMetadataForTable("test_table", false);
if (logical_table->partitions != "REPLICATED") {
CHECK_GT(logical_table->nShards, 0);
}
auto physical_tables = catalog.getPhysicalTablesDescriptors(logical_table);
if (logical_table->partitions != "REPLICATED") {
CHECK_EQ(physical_tables.size(), static_cast<size_t>(logical_table->nShards));
}
return physical_tables;
}
std::shared_ptr<File_Namespace::FileMgr> getFileMgr() {
const auto& catalog = getCatalog();
auto global_file_mgr = catalog.getDataMgr().getGlobalFileMgr();
auto physical_tables = getPhysicalTestTables();
return global_file_mgr->getSharedFileMgr(catalog.getDatabaseId(),
physical_tables.back()->tableId);
}
CheckpointFailureMock* checkpoint_failure_mock_;
CheckpointFailureMock* checkpoint_failure_no_to_mock_;
};
TEST_P(EpochRollbackTest, Import) {
setUpTestTableWithInconsistentEpochs();
loginTestUser();
sendFailedImportQuery();
assertInitialTableState();
// Ensure that a subsequent import still works as expected
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({2, 3});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(1), "test_1"},
{i(1), i(10), "test_10"},
{i(1), i(10), "test_10"},
{i(2), i(2), "test_2"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"},
{i(2), i(20), "test_20"}});
// clang-format on
}
TEST_P(EpochRollbackTest, Insert) {
setUpTestTableWithInconsistentEpochs();
loginTestUser();
sendFailedInsertQuery();
assertInitialTableState();
// Ensure that a subsequent insert query still works as expected
sql("insert into test_table values (1, 110, 'test_110');");
assertTableEpochs({2, 3});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(10), "test_10"},
{i(1), i(110), "test_110"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
TEST_P(EpochRollbackTest, InsertOnReplicatedTable) {
setUpReplicatedTestTableWithInconsistentEpochs();
loginTestUser();
sendReplicatedTableFailedInsertQuery();
assertTableEpochs({2});
assertInitialImportResultSet();
// Ensure that a subsequent insert query still works as expected
sql("insert into test_table values (1, 110, 'test_110');");
assertTableEpochs({3});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(10), "test_10"},
{i(1), i(110), "test_110"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
TEST_P(EpochRollbackTest, Update) {
// The checkpoint error case exercises the same path as the query error case in
// distributed mode. Specifically, both come back as exceptions when
// `execute_query_step` is called on leaf nodes.
if (isDistributedMode() && isCheckpointError()) {
GTEST_SKIP();
}
setUpTestTableWithInconsistentEpochs();
loginTestUser();
sendFailedUpdateQuery();
assertInitialTableState();
// Ensure that a subsequent update query still works as expected
sql("update test_table set b = b + 1 where b = 10 or b = 20;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 4});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(11), "test_10"},
{i(2), i(2), "test_2"},
{i(2), i(21), "test_20"}});
// clang-format on
}
// Updates execute different code paths when variable length columns are updated
TEST_P(EpochRollbackTest, VarlenUpdate) {
// The checkpoint error case exercises the same path as the query error case in
// distributed mode. Specifically, both come back as exceptions when
// `execute_query_step` is called on leaf nodes.
if (isDistributedMode() && isCheckpointError()) {
GTEST_SKIP();
}
setUpTestTableWithInconsistentEpochs();
loginTestUser();
sendFailedVarlenUpdateQuery();
assertInitialTableState();
// Ensure that a subsequent update query still works as expected
sql("update test_table set b = 110, c = 'test_110' where b = 10;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 4});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(110), "test_110"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
TEST_P(EpochRollbackTest, Delete) {
// The checkpoint error case exercises the same path as the query error case in
// distributed mode. Specifically, both come back as exceptions when
// `execute_query_step` is called on leaf nodes.
if (isDistributedMode() && isCheckpointError()) {
GTEST_SKIP();
}
setUpTestTableWithInconsistentEpochs();
loginTestUser();
sendFailedDeleteQuery();
assertInitialTableState();
// Ensure that a delete query still works as expected
sql("delete from test_table where b = 10 or b = 20;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 4});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(2), i(2), "test_2"}});
// clang-format on
}
TEST_P(EpochRollbackTest, InsertTableAsSelect) {
setUpTestTableWithInconsistentEpochs();
loginTestUser();
sendFailedItasQuery();
assertInitialTableState();
// Ensure that a subsequent ITAS query still works as expected
sql("insert into test_table (select * from test_table where b = 1 or b = 20);");
assertTableEpochs({2, 3});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(1), "test_1"},
{i(1), i(10), "test_10"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"},
{i(2), i(20), "test_20"}});
// clang-format on
}
INSTANTIATE_TEST_SUITE_P(EpochRollbackTest,
EpochRollbackTest,
testing::Values(true, false),
EpochRollbackTest::testParamsToString);
class EpochLevelingTest : public EpochConsistencyTest {
void SetUp() override {
EpochConsistencyTest::SetUp();
sql("create table test_table(a int, b tinyint, c text encoding none, shard key(a)) "
"with (shard_count = 4);");
assertTableEpochs({0, 0, 0, 0});
}
};
TEST_F(EpochLevelingTest, Import) {
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(10), "test_10"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
TEST_F(EpochLevelingTest, Insert) {
sql("insert into test_table values (1, 100, 'test_100');");
assertTableEpochs({1, 1, 1, 1});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(100), "test_100"}});
// clang-format on
}
TEST_F(EpochLevelingTest, Update) {
// Import data to be updated by the following query
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
sql("update test_table set b = b + 1 where b = 1;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 3, 3, 3});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(2), "test_1"},
{i(1), i(10), "test_10"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
// Updates execute different code paths when variable length columns are updated
TEST_F(EpochLevelingTest, VarlenUpdate) {
// Import data to be updated by the following query
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
sql("update test_table set b = 110, c = 'test_110' where b = 10;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 3, 3, 3});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(110), "test_110"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
TEST_F(EpochLevelingTest, UpdateQueryButDataNotChanged) {
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
sql("update test_table set b = b + 1 where b = 1000;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 3, 3, 3});
assertInitialImportResultSet();
}
TEST_F(EpochLevelingTest, Delete) {
// Import data to be deleted by the following query
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
sql("delete from test_table where b = 10 or b = 20;");
// 1 checkpoint for delete and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 3, 3, 3});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(2), i(2), "test_2"}});
// clang-format on
}
TEST_F(EpochLevelingTest, DeleteQueryButNoDataDeleted) {
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
sql("delete from test_table where b = 1000;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 3, 3, 3});
assertInitialImportResultSet();
}
TEST_F(EpochLevelingTest, InsertTableAsSelect) {
// Import data to be selected by the following query
sql("copy test_table from '" + getGoodFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
sql("insert into test_table (select * from test_table where b = 1);");
assertTableEpochs({2, 2, 2, 2});
// clang-format off
sqlAndCompareResult("select * from test_table order by a, b;",
{{i(1), i(1), "test_1"},
{i(1), i(1), "test_1"},
{i(1), i(10), "test_10"},
{i(2), i(2), "test_2"},
{i(2), i(20), "test_20"}});
// clang-format on
}
TEST_F(EpochLevelingTest, Optimize) {
sql("drop table if exists test_table;");
sql("create table test_table(a int, b int, shard key(a)) "
"with (shard_count = 4, fragment_size = 2);");
assertTableEpochs({0, 0, 0, 0});
sql("copy test_table from '" + getShardedMultiFragmentFilePath() + "';");
assertTableEpochs({1, 1, 1, 1});
sql("delete from test_table where mod(b, 2) = 0;");
// 1 checkpoint for update and 1 checkpoint for automatic vacuum
assertTableEpochs({3, 3, 3, 3});
sql("optimize table test_table with (vacuum = 'true');");
// Vacuum does a checkpoint and metadata re-computation does another checkpoint
assertTableEpochs({5, 5, 5, 5});
// clang-format off
// Assert subsequent query returns expected result
sqlAndCompareResult("select * from test_table order by a;",
{{i(1), i(1)}, {i(3), i(3)}, {i(5), i(5)}, {i(7), i(7)},
{i(9), i(9)}, {i(11), i(11)}, {i(13), i(13)},
{i(15), i(15)}, {i(17), i(17)}, {i(19), i(19)}});
// clang-format on
}
class SetTableEpochsTest : public EpochConsistencyTest {
protected:
static void SetUpTestSuite() { EpochConsistencyTest::SetUpTestSuite(); }
static void TearDownTestSuite() { EpochConsistencyTest::TearDownTestSuite(); }
void SetUp() override {
EpochConsistencyTest::SetUp();
sql("drop table if exists test_table;");
sql("drop table if exists test_table_2;");
}
void TearDown() override {
sql("drop table if exists test_table;");
sql("drop table if exists test_table_2;");
EpochConsistencyTest::TearDown();
}
std::pair<int32_t, std::vector<TTableEpochInfo>> getDbIdAndTableEpochs() {
const auto& catalog = getCatalog();
auto td = catalog.getMetadataForTable("test_table", false);
auto tables = catalog.getPhysicalTablesDescriptors(td, false);
std::vector<TTableEpochInfo> table_epoch_info_vector;
for (auto table : tables) {
for (size_t i = 0; i < 2; i++) {
TTableEpochInfo table_epoch_info;
table_epoch_info.table_epoch = 1;
table_epoch_info.table_id = table->tableId;
table_epoch_info.leaf_index = i;
table_epoch_info_vector.emplace_back(table_epoch_info);
}
}
return {catalog.getDatabaseId(), table_epoch_info_vector};
}
// assert all epochs are equal to current_epoch, then set to new_epoch
void assertAndSetTableEpoch(int32_t current_epoch, int32_t new_epoch) {
std::vector<TTableEpochInfo> epochs_vector;
const auto& catalog = getCatalog();
auto [db_handler, session_id] = getDbHandlerAndSessionId();
auto [db_id, epoch_vector] = getDbIdAndTableEpochs();
auto table_id = catalog.getMetadataForTable("test_table", false)->tableId;
db_handler->get_table_epochs(epochs_vector, session_id, db_id, table_id);
for (auto& tei : epochs_vector) {
CHECK_EQ(tei.table_epoch, current_epoch);
tei.table_epoch = new_epoch;
}
db_handler->set_table_epochs(session_id, db_id, epochs_vector);
}
std::string getTableIdString() {
const auto& catalog = getCatalog();
auto table_id = catalog.getMetadataForTable("test_table", false)->tableId;
std::stringstream id_ss;
// +1 as message will be from first shard
id_ss << "(" << catalog.getDatabaseId() << ", " << table_id + 1 << ")";
return id_ss.str();
}
};
TEST_F(SetTableEpochsTest, Admin) {
loginAdmin();
sql("create table test_table(a int);");
auto [db_handler, session_id] = getDbHandlerAndSessionId();
auto [db_id, epoch_vector] = getDbIdAndTableEpochs();
db_handler->set_table_epochs(session_id, db_id, epoch_vector);
}
TEST_F(SetTableEpochsTest, NonSuperUser) {
login("non_super_user", "HyperInteractive");
sql("create table test_table(a int);");
executeLambdaAndAssertException(
[this] {
auto [db_handler, session_id] = getDbHandlerAndSessionId();
auto [db_id, epoch_vector] = getDbIdAndTableEpochs();
db_handler->set_table_epochs(session_id, db_id, epoch_vector);
},
"Only super users can set table epochs");
}
TEST_F(SetTableEpochsTest, ShardedTable) {
loginAdmin();
sql("create table test_table (a int, shard key(a)) with (shard_count = 4);");
auto [db_handler, session_id] = getDbHandlerAndSessionId();
auto [db_id, epoch_vector] = getDbIdAndTableEpochs();
db_handler->set_table_epochs(session_id, db_id, epoch_vector);
}
TEST_F(SetTableEpochsTest, EpochWithDifferentLogicalTable) {
loginAdmin();
sql("create table test_table (a int, shard key(a)) with (shard_count = 4);");
sql("create table test_table_2 (a int);");
executeLambdaAndAssertException(
[this] {
auto [db_handler, session_id] = getDbHandlerAndSessionId();
auto [db_id, epoch_vector] = getDbIdAndTableEpochs();
ASSERT_GT(epoch_vector.size(), static_cast<size_t>(1));
epoch_vector[0].table_id =
getCatalog().getMetadataForTable("test_table_2")->tableId;
db_handler->set_table_epochs(session_id, db_id, epoch_vector);
},
"Table epochs do not reference the same logical table");
}
TEST_F(SetTableEpochsTest, Capped) {
loginAdmin();
const int row_count = 20;
sql("create table test_table(a int, shard key(a)) with (max_rollback_epochs = 5, "
"shard_count =2);");
for (int i = 0; i < row_count; i++) {
sql("insert into test_table values (" + std::to_string(i) + ");");
}
assertTableEpochs({row_count, row_count});
sqlAndCompareResult("select count(*) from test_table;", {{i(row_count)}});
auto [db_handler, session_id] = getDbHandlerAndSessionId();
auto [db_id, not_good_to_use] = getDbIdAndTableEpochs();
std::vector<TTableEpochInfo> epochs_vector;
const auto& catalog = getCatalog();
auto table_id = catalog.getMetadataForTable("test_table", false)->tableId;
db_handler->get_table_epochs(epochs_vector, session_id, db_id, table_id);
for (auto& tei : epochs_vector) {
CHECK_EQ(tei.table_epoch, row_count);
tei.table_epoch = 10;
}
// This should fail as we are attempting to rollback too far
EXPECT_ANY_THROW(db_handler->set_table_epochs(session_id, db_id, epochs_vector));
for (auto& tei : epochs_vector) {
tei.table_epoch = 15;
}
db_handler->set_table_epochs(session_id, db_id, epochs_vector);
sqlAndCompareResult("select count(*) from test_table;", {{i(15)}});
assertTableEpochs({15, 15});
}
TEST_F(SetTableEpochsTest, CappedAlter) {
loginAdmin();
int row_count = 20;
auto doInserts = [&row_count]() {
for (int i = 0; i < row_count; i++) {
sql("insert into test_table values (" + std::to_string(i) + ");");
}
};
sql("create table test_table(a int, shard key(a)) with (shard_count = 2, "
"max_rollback_epochs = 25);");
doInserts();
assertTableEpochs({row_count, row_count});
sqlAndCompareResult("select count(*) from test_table;", {{i(row_count)}});
auto [db_handler, session_id] = getDbHandlerAndSessionId();
auto [db_id, not_good_to_use] = getDbIdAndTableEpochs();
std::vector<TTableEpochInfo> epochs_vector;
const auto& catalog = getCatalog();
auto table_id = catalog.getMetadataForTable("test_table", false)->tableId;
db_handler->get_table_epochs(epochs_vector, session_id, db_id, table_id);
// rollback to zero
for (auto& tei : epochs_vector) {
CHECK_EQ(tei.table_epoch, row_count);
tei.table_epoch = 0;
}
db_handler->set_table_epochs(session_id, db_id, epochs_vector);
assertTableEpochs({0, 0});
// insert another 21 rows
row_count = 21;
doInserts();
assertTableEpochs({row_count, row_count});
sqlAndCompareResult("select count(*) from test_table;", {{i(row_count)}});
sql("alter table test_table set max_rollback_epochs = 5;");
for (auto& tei : epochs_vector) {
tei.table_epoch = 12;
}
// This should fail as we are attempting to rollback too far
EXPECT_ANY_THROW(db_handler->set_table_epochs(session_id, db_id, epochs_vector));
sql("alter table test_table set epoch = 16;");
sqlAndCompareResult("select count(*) from test_table;", {{i(16)}});
assertTableEpochs({16, 16});
}
TEST_F(SetTableEpochsTest, AddColumn) {
loginAdmin();
std::string select = "select * from test_table order by a;";
sql("create table test_table(a int, shard key(a)) with (shard_count = 2, "
"max_rollback_epochs = 25);");
sql("insert into test_table values (0);");
assertTableEpochs({1, 1});
sqlAndCompareResult(select, {{i(0)}});
sql("alter table test_table add b int default 0;");
assertTableEpochs({2, 2});
sqlAndCompareResult(select, {{i(0), i(0)}});
sql("insert into test_table values (1,1);");
sqlAndCompareResult(select, {{i(0), i(0)}, {i(1), i(1)}});
assertTableEpochs({3, 3});
try {
assertAndSetTableEpoch(3, 1);
} catch (const std::exception& e) {
ASSERT_EQ("Cannot set epoch for table " + getTableIdString() +
" lower than the minimum rollback epoch (2).",
std::string(e.what()));
}
sqlAndCompareResult(select, {{i(0), i(0)}, {i(1), i(1)}});
// Make sure rollback to just after schema change works
assertAndSetTableEpoch(3, 2);
sqlAndCompareResult(select, {{i(0), i(0)}});
}
TEST_F(SetTableEpochsTest, DropColumn) {
loginAdmin();
std::string select = "select * from test_table order by a;";
sql("create table test_table(a int, shard key(a), b int ) with (shard_count = 2, "
"max_rollback_epochs = 25);");
sql("insert into test_table values (0,0);");
assertTableEpochs({1, 1});
sqlAndCompareResult(select, {{i(0), i(0)}});
sql("alter table test_table drop b;");
assertTableEpochs({2, 2});
sqlAndCompareResult(select, {{i(0)}});
sql("insert into test_table values (1);");
sqlAndCompareResult(select, {{i(0)}, {i(1)}});
assertTableEpochs({3, 3});
try {
assertAndSetTableEpoch(3, 1);
} catch (const std::exception& e) {
ASSERT_EQ("Cannot set epoch for table " + getTableIdString() +
" lower than the minimum rollback epoch (2).",
std::string(e.what()));
}
sqlAndCompareResult(select, {{i(0)}, {i(1)}});
// Make sure rollback to just after schema change works
assertAndSetTableEpoch(3, 2);
sqlAndCompareResult(select, {{i(0)}});
}
class EpochValidationTest : public EpochConsistencyTest {
protected:
static void SetUpTestSuite() {
DBHandlerTestFixture::SetUpTestSuite();
switchToAdmin();
sql("DROP DATABASE IF EXISTS test_db;");
sql("CREATE DATABASE test_db;");
}
static void TearDownTestSuite() {
switchToAdmin();
sql("DROP DATABASE IF EXISTS test_db;");
DBHandlerTestFixture::TearDownTestSuite();
}
void SetUp() override {
DBHandlerTestFixture::SetUp();
login("admin", "HyperInteractive", "test_db");
dropTestTables();
}
void TearDown() override {
dropTestTables();
DBHandlerTestFixture::TearDown();
}
void dropTestTables() {
sql("DROP TABLE IF EXISTS test_table;");
sql("DROP TABLE IF EXISTS test_temp_table;");
sql("DROP TABLE IF EXISTS test_arrow_table;");
sql("DROP VIEW IF EXISTS test_view;");
if (!isDistributedMode()) {
sql("DROP FOREIGN TABLE IF EXISTS test_foreign_table;");
}
}
std::string getValidateStatement() {
if (isDistributedMode()) {
return "VALIDATE CLUSTER;";
} else {
return "VALIDATE;";
}
}
std::string getWrongValidateStatement() {
if (isDistributedMode()) {
return "VALIDATE;";
} else {
return "VALIDATE CLUSTER;";
}
}
std::string getSuccessfulValidationResult() {
if (isDistributedMode()) {
return "Cluster OK";
} else {
return "Instance OK";
}
}
std::string getInconsistentEpochsValidationResult() {