-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_replication_ha.cpp
More file actions
5584 lines (4489 loc) · 202 KB
/
test_replication_ha.cpp
File metadata and controls
5584 lines (4489 loc) · 202 KB
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
/*
╔═════════════════════════════════════════════════════════════════════╗
║ ThemisDB - Hybrid Database System ║
╠═════════════════════════════════════════════════════════════════════╣
File: test_replication_ha.cpp ║
Version: 0.0.37 ║
Last Modified: 2026-04-06 04:34:04 ║
Author: unknown ║
╠═════════════════════════════════════════════════════════════════════╣
Quality Metrics: ║
• Maturity Level: 🔴 ALPHA ║
• Quality Score: 31.0/100 ║
• Total Lines: 5584 ║
• Open Issues: TODOs: 0, Stubs: 0 ║
╠═════════════════════════════════════════════════════════════════════╣
Revision History: ║
• 5bee4e8e41 2026-04-03 Implement Disaster Recovery Manager and associated tests ║
• 25f9a09910 2026-04-02 Refactor tests and improve assertions ║
• 64a9ae4eb6 2026-03-31 feat: enhance cache warmup logic and improve replication ... ║
• 387fde93e0 2026-03-13 feat(replication): implement MultiTierReplicationManager ... ║
• 4a853813e8 2026-03-13 fix(replication): audit fixes — honor bidirectional_sync/... ║
╠═════════════════════════════════════════════════════════════════════╣
Status: 🚧 Early Development ║
╚═════════════════════════════════════════════════════════════════════╝
*/
/**
* ThemisDB Replication HA Tests
*
* Unit tests covering the production-readiness improvements made to the
* replication module:
* 1. Configuration validation
* 2. WAL checksum verification on read
* 3. LastWriteWinsResolver conflict resolution
* 4. CRDTMergeResolver conflict resolution
* 5. LeaderElection quorum-based promotion
* 6. Thread-safe replica list operations
* 7. Error handling in replicate()
* 8. Witness node support (vote-only, no data) for 2-node cluster quorum
*/
#include <gtest/gtest.h>
#include "replication/replication_manager.h"
#include "replication/multi_master_replication.h"
#include "replication/multi_tier_replication.h"
#include <filesystem>
#include <fstream>
#include <future>
#include <thread>
#include <vector>
#include <atomic>
#include <unordered_map>
#include <zstd.h>
#include <lz4.h>
#include <snappy.h>
using namespace themisdb::replication;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
static ReplicationConfig makeConfig(const std::string& wal_dir = "/tmp/themis_repl_test_wal") {
ReplicationConfig cfg;
cfg.enabled = true;
cfg.mode = ReplicationMode::ASYNC;
cfg.heartbeat_interval_ms = 100;
cfg.election_timeout_min_ms = 150;
cfg.election_timeout_max_ms = 300;
cfg.batch_size = 100;
cfg.batch_timeout_ms = 50;
cfg.wal_directory = wal_dir;
cfg.failure_detection_timeout_ms = 1000;
cfg.degraded_lag_threshold_ms = 5000;
cfg.min_sync_replicas = 1;
cfg.wal_sync_on_commit = false;
// Keep generic helper configs valid for short election timeouts used by
// many focused tests. Lease-specific tests use makeLeaseConfig().
cfg.enable_leader_lease = false;
cfg.leader_lease_duration_ms = 0;
return cfg;
}
// RAII helper that removes the WAL directory on destruction.
struct TempWALDir {
std::string path;
explicit TempWALDir(const std::string& p) {
const auto ticks = std::chrono::high_resolution_clock::now()
.time_since_epoch()
.count();
const auto tid_hash = std::hash<std::thread::id>{}(std::this_thread::get_id());
const std::string base = std::filesystem::path(p).filename().string();
path = (std::filesystem::temp_directory_path() /
(base + "_" + std::to_string(ticks) + "_" + std::to_string(tid_hash)))
.string();
std::error_code ec;
std::filesystem::remove_all(path, ec);
std::filesystem::create_directories(path, ec);
}
~TempWALDir() {
for (int i = 0; i < 5; ++i) {
std::error_code ec;
std::filesystem::remove_all(path, ec);
if (!ec) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
}
};
// ============================================================================
// 1. Configuration Validation
// ============================================================================
class ReplicationConfigTest : public ::testing::Test {};
TEST_F(ReplicationConfigTest, InvalidBatchSizeZeroFails) {
TempWALDir wd("/tmp/themis_repl_cfg_test");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.batch_size = 0;
ReplicationManager mgr(cfg);
EXPECT_FALSE(mgr.initialize());
}
TEST_F(ReplicationConfigTest, InvalidBatchSizeTooLargeFails) {
TempWALDir wd("/tmp/themis_repl_cfg_test2");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.batch_size = 2000000;
ReplicationManager mgr(cfg);
EXPECT_FALSE(mgr.initialize());
}
TEST_F(ReplicationConfigTest, InvalidHeartbeatIntervalFails) {
TempWALDir wd("/tmp/themis_repl_cfg_test3");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.heartbeat_interval_ms = 0;
ReplicationManager mgr(cfg);
EXPECT_FALSE(mgr.initialize());
}
TEST_F(ReplicationConfigTest, ElectionTimeoutMinGEMaxFails) {
TempWALDir wd("/tmp/themis_repl_cfg_test4");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.election_timeout_min_ms = 300;
cfg.election_timeout_max_ms = 300; // min == max → invalid
ReplicationManager mgr(cfg);
EXPECT_FALSE(mgr.initialize());
}
TEST_F(ReplicationConfigTest, LeaseDurationGEElectionTimeoutFails) {
TempWALDir wd("/tmp/themis_repl_cfg_lease_invalid");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.enable_leader_lease = true;
cfg.election_timeout_min_ms = 3000;
cfg.election_timeout_max_ms = 5000;
cfg.leader_lease_duration_ms = 3000; // equal → invalid (must be strictly less)
ReplicationManager mgr(cfg);
EXPECT_FALSE(mgr.initialize());
}
TEST_F(ReplicationConfigTest, LeaseDurationLTElectionTimeoutSucceeds) {
TempWALDir wd("/tmp/themis_repl_cfg_lease_valid");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.enable_leader_lease = true;
cfg.election_timeout_min_ms = 3000;
cfg.election_timeout_max_ms = 5000;
cfg.leader_lease_duration_ms = 2999; // strictly less → valid
ReplicationManager mgr(cfg);
EXPECT_TRUE(mgr.initialize());
mgr.shutdown();
}
TEST_F(ReplicationConfigTest, LeaseDisabledIgnoresLeaseDuration) {
TempWALDir wd("/tmp/themis_repl_cfg_lease_off");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.enable_leader_lease = false;
cfg.election_timeout_min_ms = 500;
cfg.election_timeout_max_ms = 1000;
// duration >= election_timeout but lease is disabled → should still succeed
cfg.leader_lease_duration_ms = 5000;
ReplicationManager mgr(cfg);
EXPECT_TRUE(mgr.initialize());
mgr.shutdown();
}
TEST_F(ReplicationConfigTest, ValidConfigInitializesSuccessfully) {
TempWALDir wd("/tmp/themis_repl_cfg_test5");
ReplicationConfig cfg = makeConfig(wd.path);
ReplicationManager mgr(cfg);
EXPECT_TRUE(mgr.initialize());
mgr.shutdown();
}
TEST_F(ReplicationConfigTest, InvalidWALCompressionLevelFails) {
TempWALDir wd("/tmp/themis_repl_cfg_compress_test");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.enable_wal_compression = true;
cfg.wal_compression_level = 0; // Out of range (must be 1-9)
ReplicationManager mgr(cfg);
EXPECT_FALSE(mgr.initialize());
}
TEST_F(ReplicationConfigTest, ValidWALCompressionLevelSucceeds) {
TempWALDir wd("/tmp/themis_repl_cfg_compress_ok");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.enable_wal_compression = true;
cfg.wal_compression_level = 6;
ReplicationManager mgr(cfg);
EXPECT_TRUE(mgr.initialize());
mgr.shutdown();
}
// ============================================================================
// 2. WAL Checksum Verification
// ============================================================================
class WALChecksumTest : public ::testing::Test {};
TEST_F(WALChecksumTest, AppendAndReadBackVerifiesChecksum) {
TempWALDir wd("/tmp/themis_wal_csum_test");
ReplicationConfig cfg = makeConfig(wd.path);
WALManager wal(cfg);
WALEntry entry;
entry.operation = "INSERT";
entry.collection = "users";
entry.document_id = "doc1";
entry.data = "{\"name\":\"Alice\"}";
uint64_t seq = wal.append(entry);
ASSERT_GT(seq, 0u);
auto entries = wal.readFrom(seq, 1);
ASSERT_EQ(entries.size(), 1u);
EXPECT_EQ(entries[0].operation, "INSERT");
EXPECT_EQ(entries[0].document_id, "doc1");
EXPECT_FALSE(entries[0].checksum.empty());
}
TEST_F(WALChecksumTest, CorruptChecksumEntryIsDropped) {
TempWALDir wd("/tmp/themis_wal_corrupt_test");
ReplicationConfig cfg = makeConfig(wd.path);
WALManager wal(cfg);
// Append a valid entry
WALEntry entry;
entry.operation = "UPDATE";
entry.collection = "products";
entry.document_id = "prod1";
entry.data = "{\"price\":99}";
uint64_t seq = wal.append(entry);
ASSERT_GT(seq, 0u);
// Manually corrupt the checksum inside the WAL segment file
std::string seg_path = wd.path + "/wal_0.log";
ASSERT_TRUE(std::filesystem::exists(seg_path));
{
// Open the file for read+write; the checksum is near the end of the record.
std::fstream fs(seg_path, std::ios::in | std::ios::out | std::ios::binary);
ASSERT_TRUE(fs.is_open());
// Seek close to end and flip a byte to corrupt the checksum field
fs.seekp(-4, std::ios::end);
char dummy = 0xFF;
fs.write(&dummy, 1);
}
// readFrom should skip the corrupted entry
auto entries = wal.readFrom(seq, 10);
EXPECT_EQ(entries.size(), 0u)
<< "Corrupted entry should have been filtered out by checksum verification";
}
// ============================================================================
// 3. LastWriteWinsResolver
// ============================================================================
class LWWResolverTest : public ::testing::Test {
protected:
LWWConflictResolver resolver;
};
TEST_F(LWWResolverTest, SelectsNewerTimestamp) {
std::string older = R"({"id":"1","updated_at":1000,"value":"old"})";
std::string newer = R"({"id":"1","updated_at":2000,"value":"new"})";
std::string result = resolver.resolve(older, newer, "col", "1");
EXPECT_EQ(result, newer);
}
TEST_F(LWWResolverTest, KeepsLocalWhenLocalIsNewer) {
std::string local = R"({"id":"2","updated_at":5000,"value":"local"})";
std::string remote = R"({"id":"2","updated_at":3000,"value":"remote"})";
std::string result = resolver.resolve(local, remote, "col", "2");
EXPECT_EQ(result, local);
}
TEST_F(LWWResolverTest, FallsBackToRemoteWhenNoTimestamp) {
std::string local = R"({"id":"3","value":"notime"})";
std::string remote = R"({"id":"3","value":"remote_notime"})";
std::string result = resolver.resolve(local, remote, "col", "3");
EXPECT_EQ(result, remote)
<< "When neither document has a timestamp the remote version should win";
}
TEST_F(LWWResolverTest, ChoosesRemoteOnTie) {
// Equal timestamps → remote should win (conservative)
std::string local = R"({"id":"4","updated_at":100,"value":"A"})";
std::string remote = R"({"id":"4","updated_at":100,"value":"B"})";
std::string result = resolver.resolve(local, remote, "col", "4");
EXPECT_EQ(result, remote);
}
// ============================================================================
// 4. CRDTMergeResolver
// ============================================================================
class CRDTResolverTest : public ::testing::Test {
protected:
CRDTConflictResolver resolver;
};
TEST_F(CRDTResolverTest, MergeKeepsMaxNumericValue) {
// Local has a higher counter for "views"; remote has a higher counter for "likes"
std::string local = R"({"updated_at":200,"views":50,"likes":5})";
std::string remote = R"({"updated_at":100,"views":30,"likes":20})";
// LWW winner is local (updated_at=200); CRDT should promote likes to 20
std::string result = resolver.resolve(local, remote, "col", "doc");
EXPECT_FALSE(result.empty());
// The merged document must contain likes:20 (the max)
EXPECT_NE(result.find("20"), std::string::npos)
<< "CRDT merge should keep the max value (20) for 'likes'";
}
TEST_F(CRDTResolverTest, EmptyLocalReturnsRemote) {
std::string result = resolver.resolve("", R"({"a":1})", "c", "d");
EXPECT_EQ(result, R"({"a":1})");
}
TEST_F(CRDTResolverTest, EmptyRemoteReturnsLocal) {
std::string result = resolver.resolve(R"({"a":1})", "", "c", "d");
EXPECT_EQ(result, R"({"a":1})");
}
// ============================================================================
// 5. LeaderElection quorum logic
// ============================================================================
class LeaderElectionTest : public ::testing::Test {
protected:
void SetUp() override {
std::filesystem::remove_all(wal_path_);
std::filesystem::create_directories(wal_path_);
config_ = makeConfig(wal_path_);
wal_ = std::make_shared<WALManager>(config_);
}
void TearDown() override {
std::filesystem::remove_all(wal_path_);
}
const std::string wal_path_ = "/tmp/themis_le_test";
ReplicationConfig config_;
std::shared_ptr<WALManager> wal_;
};
TEST_F(LeaderElectionTest, SingleNodeWinsElectionImmediately) {
LeaderElection le("node-1", config_, wal_);
le.setClusterSize(1); // Single-node cluster → quorum = 1 = self vote
le.startElection();
EXPECT_TRUE(le.isLeader());
}
TEST_F(LeaderElectionTest, ThreeNodeClusterRequiresQuorum) {
LeaderElection le("node-1", config_, wal_);
le.setClusterSize(3); // Need 2 votes (quorum = 3/2+1 = 2)
le.startElection();
// With only 1 vote (self) and cluster_size=3, quorum is not yet reached
EXPECT_FALSE(le.isLeader())
<< "Should not become leader with only 1 out of 3 votes";
// Simulate a peer granting a vote for the current term
le.grantVote(wal_->getCurrentTerm());
EXPECT_TRUE(le.isLeader())
<< "Should become leader after receiving quorum (2/3) votes";
}
TEST_F(LeaderElectionTest, StaleVoteIsIgnored) {
LeaderElection le("node-2", config_, wal_);
le.setClusterSize(3);
le.startElection();
uint64_t election_term = wal_->getCurrentTerm();
// A vote for an older term must not promote to leader
le.grantVote(election_term > 0 ? election_term - 1 : 0);
EXPECT_FALSE(le.isLeader())
<< "Vote for an older term should be ignored";
// Now grant vote for the correct term
le.grantVote(election_term);
EXPECT_TRUE(le.isLeader());
}
TEST_F(LeaderElectionTest, HeartbeatConvertsCandidateToFollower) {
LeaderElection le("node-3", config_, wal_);
le.setClusterSize(3);
le.startElection();
ASSERT_FALSE(le.isLeader());
// Receiving a heartbeat from a leader with higher term demotes us
le.receiveHeartbeat(wal_->getCurrentTerm() + 1, "node-leader", 0);
EXPECT_EQ(le.getRole(), ReplicationRole::FOLLOWER);
EXPECT_EQ(le.getLeaderId(), "node-leader");
}
TEST_F(LeaderElectionTest, HeartbeatAdvancesCommitIndex) {
LeaderElection le("node-ci", config_, wal_);
le.setClusterSize(3);
// Initial commit index must be 0
EXPECT_EQ(le.getCommitIndex(), 0u);
// Append some WAL entries so that last_log_sequence > 0
WALEntry entry;
entry.operation = "INSERT";
entry.collection = "ci_test";
entry.document_id = "doc1";
entry.data = "{}";
uint64_t seq = wal_->append(entry);
ASSERT_GT(seq, 0u);
// Simulate a heartbeat from the leader that has committed up to seq
le.receiveHeartbeat(wal_->getCurrentTerm() + 1, "node-leader", seq);
// commit_index must be updated to min(leader_commit, our last_log_seq) = seq
EXPECT_EQ(le.getCommitIndex(), seq);
}
TEST_F(LeaderElectionTest, CommitIndexNeverGoesBackward) {
LeaderElection le("node-ci2", config_, wal_);
le.setClusterSize(3);
WALEntry entry;
entry.operation = "INSERT";
entry.collection = "ci_test";
entry.document_id = "d1";
entry.data = "{}";
uint64_t seq = wal_->append(entry);
ASSERT_GT(seq, 0u);
// First heartbeat: advance to seq
le.receiveHeartbeat(1, "leader", seq);
EXPECT_EQ(le.getCommitIndex(), seq);
// Second heartbeat: try to go backward (leader_commit < current)
le.receiveHeartbeat(1, "leader", 0);
// commit_index must not decrease
EXPECT_EQ(le.getCommitIndex(), seq);
}
TEST_F(LeaderElectionTest, RequestVoteGrantedWhenLogIsUpToDate) {
LeaderElection le("node-4", config_, wal_);
bool granted = le.requestVote(
wal_->getCurrentTerm() + 1, // Higher term
"candidate-5",
0, 0);
EXPECT_TRUE(granted);
}
TEST_F(LeaderElectionTest, RequestVoteRejectedForStaleTerm) {
LeaderElection le("node-5", config_, wal_);
// Advance our own term first
le.startElection();
// Now a peer with a lower term asks for a vote
bool granted = le.requestVote(0, "old-candidate", 0, 0);
EXPECT_FALSE(granted);
}
// ============================================================================
// 6. Thread-safe replica list – concurrent add/remove/read
// ============================================================================
TEST(ReplicationManagerThreadSafety, ConcurrentAddRemoveReplicas) {
TempWALDir wd("/tmp/themis_ts_test");
ReplicationConfig cfg = makeConfig(wd.path);
ReplicationManager mgr(cfg);
ASSERT_TRUE(mgr.initialize());
std::atomic<bool> stop{false};
std::atomic<int> errors{0};
// Writer thread: repeatedly adds and removes a replica
std::thread writer([&]() {
for (int i = 0; i < 50 && !stop.load(); ++i) {
ReplicaInfo r;
r.node_id = "replica-" + std::to_string(i);
r.endpoint = "127.0.0.1:" + std::to_string(9000 + i);
r.role = ReplicationRole::FOLLOWER;
r.is_voting_member = true;
r.last_heartbeat = std::chrono::system_clock::now();
r.health_status = HealthStatus::HEALTHY;
try {
mgr.addReplica(r);
mgr.removeReplica(r.node_id);
} catch (...) {
errors++;
}
}
});
// Reader thread: concurrently reads the replica list
std::thread reader([&]() {
for (int i = 0; i < 200 && !stop.load(); ++i) {
try {
auto replicas = mgr.getReplicas();
(void)replicas;
} catch (...) {
errors++;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
stop.store(true);
});
writer.join();
reader.join();
EXPECT_EQ(errors.load(), 0) << "No exceptions expected during concurrent access";
mgr.shutdown();
}
// ============================================================================
// 7. replicate() error handling
// ============================================================================
TEST(ReplicationManagerErrorHandling, ReplicateBeforeInitFails) {
TempWALDir wd("/tmp/themis_err_test");
ReplicationConfig cfg = makeConfig(wd.path);
ReplicationManager mgr(cfg);
// Do NOT call initialize()
WALEntry entry;
entry.operation = "INSERT";
entry.collection = "test";
entry.document_id = "doc1";
entry.data = "{}";
// Should fail gracefully since manager is not initialized
EXPECT_FALSE(mgr.replicate(entry));
}
TEST(ReplicationManagerErrorHandling, ReplicateAsFollowerFails) {
TempWALDir wd("/tmp/themis_err_test2");
ReplicationConfig cfg = makeConfig(wd.path);
// Add a seed node so we start as FOLLOWER (single-node won't auto-win election
// with cluster_size>1)
cfg.seed_nodes = {"127.0.0.1:9999"};
ReplicationManager mgr(cfg);
ASSERT_TRUE(mgr.initialize());
WALEntry entry;
entry.operation = "INSERT";
entry.collection = "test";
entry.document_id = "doc1";
entry.data = "{}";
// Node starts as FOLLOWER (cluster_size=2) and has not won an election
EXPECT_FALSE(mgr.replicate(entry))
<< "Follower must not accept writes";
mgr.shutdown();
}
// ============================================================================
// 8. electionLoop – randomized timeout triggers election
// ============================================================================
TEST(ElectionLoopTest, TimeoutTriggersElectionOnSingleNode) {
// Single-node cluster: after an election timeout, node should become leader
TempWALDir wd("/tmp/themis_elt_test");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.election_timeout_min_ms = 50; // Very short for fast test
cfg.election_timeout_max_ms = 100;
auto wal = std::make_shared<WALManager>(cfg);
LeaderElection le("node-elt", cfg, wal);
le.setClusterSize(1);
le.start();
// Wait up to 500ms for the election loop to fire
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(500);
while (!le.isLeader() &&
std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
EXPECT_TRUE(le.isLeader())
<< "Single-node cluster should become leader after election timeout";
}
TEST(ElectionLoopTest, HeartbeatResetsElectionTimer) {
// When heartbeats arrive within the timeout, election must NOT be triggered
TempWALDir wd("/tmp/themis_elt_hb_test");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.election_timeout_min_ms = 200;
cfg.election_timeout_max_ms = 300;
auto wal = std::make_shared<WALManager>(cfg);
LeaderElection le("node-hb", cfg, wal);
le.setClusterSize(3); // Need quorum of 2; never grant 2nd vote → stays follower
le.start();
// Send heartbeats every 50ms for 400ms – keep resetting the timer
for (int i = 0; i < 8; ++i) {
le.receiveHeartbeat(1, "leader-node", 0);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
// Node should still be FOLLOWER because heartbeats kept resetting the timer
EXPECT_EQ(le.getRole(), ReplicationRole::FOLLOWER)
<< "Regular heartbeats should prevent election timeout";
}
TEST(ElectionLoopTest, StopDoesNotHang) {
// Destroying a started LeaderElection should join cleanly
TempWALDir wd("/tmp/themis_elt_stop_test");
ReplicationConfig cfg = makeConfig(wd.path);
cfg.election_timeout_min_ms = 5000; // Long timeout so loop is sleeping
cfg.election_timeout_max_ms = 6000;
auto start = std::chrono::steady_clock::now();
{
auto wal = std::make_shared<WALManager>(cfg);
LeaderElection le("node-stop", cfg, wal);
le.setClusterSize(1);
le.start();
// Destructor stops the thread
}
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start).count();
EXPECT_LT(elapsed, 500)
<< "Destruction should complete quickly even with long election timeout";
}
// ============================================================================
// 9. VectorClock
// ============================================================================
TEST(VectorClockTest, IncrementAndGet) {
VectorClock vc("node-A");
EXPECT_EQ(vc.get("node-A"), 0u); // initialised to 0
vc.increment("node-A");
EXPECT_EQ(vc.get("node-A"), 1u);
vc.increment("node-A");
EXPECT_EQ(vc.get("node-A"), 2u);
// Unknown node returns 0
EXPECT_EQ(vc.get("node-Z"), 0u);
}
TEST(VectorClockTest, MergeInHAContext) {
VectorClock a("node-A");
a.increment("node-A");
a.increment("node-A"); // A: {A:2}
VectorClock b("node-B");
b.increment("node-B");
b.increment("node-B");
b.increment("node-B"); // B: {B:3}
a.merge(b); // A should now be {A:2, B:3}
EXPECT_EQ(a.get("node-A"), 2u);
EXPECT_EQ(a.get("node-B"), 3u);
}
TEST(VectorClockTest, Compare_HappensBefore) {
VectorClock a("A");
a.increment("A"); // a: {A:1}
VectorClock b("A");
b.increment("A");
b.increment("A"); // b: {A:2}
// a happened before b
EXPECT_TRUE(a.happensBefore(b));
EXPECT_FALSE(b.happensBefore(a));
}
TEST(VectorClockTest, Compare_Concurrent) {
VectorClock a("A");
a.increment("A");
VectorClock b("B");
b.increment("B");
// Neither happened before the other (different partitions)
EXPECT_TRUE(a.isConcurrent(b));
EXPECT_TRUE(b.isConcurrent(a));
}
TEST(VectorClockTest, Compare_EqualIsConcurrent) {
VectorClock a;
VectorClock b;
// Both empty (equal) clocks should be treated as concurrent (compare returns 0)
EXPECT_EQ(a.compare(b), 0);
EXPECT_FALSE(a.happensBefore(b));
}
TEST(VectorClockTest, ToJsonRoundTrip) {
VectorClock vc;
vc.increment("node-1");
vc.increment("node-1");
vc.increment("node-2");
std::string json = vc.toJson();
EXPECT_FALSE(json.empty());
VectorClock restored = VectorClock::fromJson(json);
EXPECT_EQ(restored.get("node-1"), 2u);
EXPECT_EQ(restored.get("node-2"), 1u);
}
TEST(VectorClockTest, CopyConstructor) {
VectorClock original("X");
original.increment("X");
original.increment("X");
VectorClock copy(original);
EXPECT_EQ(copy.get("X"), 2u);
// Mutating copy should not affect original
copy.increment("X");
EXPECT_EQ(original.get("X"), 2u);
EXPECT_EQ(copy.get("X"), 3u);
}
// ============================================================================
// 10. HybridLogicalClock
// ============================================================================
TEST(HLCTest, NowReturnsMonotonicTimestamps) {
HybridLogicalClock hlc("node-1");
auto t1 = hlc.now();
auto t2 = hlc.now();
// Each call must produce a non-decreasing timestamp (t2 >= t1)
EXPECT_FALSE(t2 < t1)
<< "now() must produce monotonic HLC timestamps";
}
TEST(HLCTest, ReceiveAdvancesClockBeyondSender) {
HybridLogicalClock sender("sender");
HybridLogicalClock receiver("receiver");
auto sent = sender.now();
// Simulate receiving a message with the sender's timestamp
auto received_ts = receiver.receive(sent);
// After receiving, the receiver's logical component must be > sender's
EXPECT_FALSE(received_ts < sent)
<< "After receive(), local clock must not be less than the sender's";
}
TEST(HLCTest, CurrentReturnsLastGeneratedTimestamp) {
HybridLogicalClock hlc("node-c");
auto t = hlc.now();
auto cur = hlc.current();
EXPECT_EQ(t.physical, cur.physical);
EXPECT_EQ(t.logical, cur.logical);
}
TEST(HLCTest, TimestampOrdering) {
HybridLogicalClock::Timestamp t1{1000, 0, "A"};
HybridLogicalClock::Timestamp t2{1000, 1, "A"};
HybridLogicalClock::Timestamp t3{2000, 0, "A"};
EXPECT_TRUE(t1 < t2); // Same physical, higher logical
EXPECT_TRUE(t2 < t3); // Higher physical wins
EXPECT_FALSE(t3 < t1);
}
TEST(HLCTest, TimestampToString) {
HybridLogicalClock::Timestamp ts{12345, 7, "node-x"};
std::string s = ts.toString();
EXPECT_NE(s.find("12345"), std::string::npos);
EXPECT_NE(s.find("7"), std::string::npos);
EXPECT_NE(s.find("node-x"), std::string::npos);
}
// ============================================================================
// 11. Multi-master MM resolvers (MMWriteEntry variants)
// ============================================================================
static HybridLogicalClock::Timestamp makeHLCTimestamp(uint64_t phys, uint32_t log,
const std::string& node) {
return HybridLogicalClock::Timestamp{phys, log, node};
}
TEST(MMLastWriteWinsTest, SelectsLatestHLCTimestamp) {
LastWriteWinsResolver resolver;
MMWriteEntry e1;
e1.write_id = "w1"; e1.data = "old"; e1.hlc = makeHLCTimestamp(1000, 0, "A");
MMWriteEntry e2;
e2.write_id = "w2"; e2.data = "new"; e2.hlc = makeHLCTimestamp(2000, 0, "B");
auto result = resolver.resolve("doc1", {e1, e2});
EXPECT_EQ(result.data, "new");
EXPECT_EQ(result.write_id, "w2");
}
TEST(MMLastWriteWinsTest, EmptyInputReturnsDefault) {
LastWriteWinsResolver resolver;
auto result = resolver.resolve("doc1", {});
EXPECT_TRUE(result.write_id.empty());
}
TEST(MMCRDTResolverTest, LWWRegisterPicksLatest) {
CRDTMergeResolver resolver(CRDTMergeResolver::CRDTType::LWW_REGISTER);
MMWriteEntry e1;
e1.write_id = "w1"; e1.data = R"({"v":1})";
e1.hlc = makeHLCTimestamp(100, 0, "A");
MMWriteEntry e2;
e2.write_id = "w2"; e2.data = R"({"v":2})";
e2.hlc = makeHLCTimestamp(200, 0, "B");
auto result = resolver.resolve("doc", {e1, e2});
EXPECT_EQ(result.data, R"({"v":2})");
}
TEST(MMCRDTResolverTest, GCounterMergesMaxPerKey) {
CRDTMergeResolver resolver(CRDTMergeResolver::CRDTType::G_COUNTER);
MMWriteEntry e1;
e1.write_id = "w1"; e1.data = R"({"counter":5})";
e1.hlc = makeHLCTimestamp(100, 0, "A");
MMWriteEntry e2;
e2.write_id = "w2"; e2.data = R"({"counter":3})";
e2.hlc = makeHLCTimestamp(200, 0, "B");
auto result = resolver.resolve("doc", {e1, e2});
// The data should contain the max counter value (5)
EXPECT_NE(result.data.find("5"), std::string::npos)
<< "G-Counter merge should keep max value";
}
TEST(MMCRDTResolverTest, GSetUnionOfValues) {
CRDTMergeResolver resolver(CRDTMergeResolver::CRDTType::G_SET);
MMWriteEntry e1;
e1.write_id = "w1"; e1.data = R"(["apple","banana"])";
e1.hlc = makeHLCTimestamp(100, 0, "A");
MMWriteEntry e2;
e2.write_id = "w2"; e2.data = R"(["banana","cherry"])";
e2.hlc = makeHLCTimestamp(200, 0, "B");
auto result = resolver.resolve("doc", {e1, e2});
// Result should contain all three unique values
EXPECT_NE(result.data.find("apple"), std::string::npos);
EXPECT_NE(result.data.find("banana"), std::string::npos);
EXPECT_NE(result.data.find("cherry"), std::string::npos);
}
TEST(MMCRDTResolverTest, StrategyNameMatchesType) {
EXPECT_EQ(CRDTMergeResolver(CRDTMergeResolver::CRDTType::LWW_REGISTER).strategyName(),
"LWW_REGISTER");
EXPECT_EQ(CRDTMergeResolver(CRDTMergeResolver::CRDTType::G_COUNTER).strategyName(),
"G_COUNTER");
EXPECT_EQ(CRDTMergeResolver(CRDTMergeResolver::CRDTType::G_SET).strategyName(),
"G_SET");
EXPECT_EQ(CRDTMergeResolver(CRDTMergeResolver::CRDTType::TWO_P_SET).strategyName(),
"TWO_P_SET");
EXPECT_EQ(CRDTMergeResolver(CRDTMergeResolver::CRDTType::RGA).strategyName(),
"RGA");
}
// PN_COUNTER: proper positive/negative sub-counter merge
TEST(MMCRDTResolverTest, PNCounterMergesPositiveAndNegativeSeparately) {
CRDTMergeResolver resolver(CRDTMergeResolver::CRDTType::PN_COUNTER);
// nodeA incremented 5 times and decremented 2 times
MMWriteEntry e1;
e1.write_id = "w1";
e1.data = R"({"P":{"nodeA":5},"N":{"nodeA":2}})";
e1.hlc = makeHLCTimestamp(100, 0, "nodeA");
// nodeB incremented 3 times and decremented 1 time; also sees nodeA incremented 4
MMWriteEntry e2;
e2.write_id = "w2";
e2.data = R"({"P":{"nodeA":4,"nodeB":3},"N":{"nodeA":1,"nodeB":1}})";
e2.hlc = makeHLCTimestamp(200, 0, "nodeB");
auto result = resolver.resolve("doc", {e1, e2});
// Merged P: nodeA=max(5,4)=5, nodeB=3
// Merged N: nodeA=max(2,1)=2, nodeB=1
EXPECT_NE(result.data.find("\"P\""), std::string::npos);
EXPECT_NE(result.data.find("\"N\""), std::string::npos);
EXPECT_NE(result.data.find("\"nodeA\":5"), std::string::npos) << result.data;
EXPECT_NE(result.data.find("\"nodeB\":3"), std::string::npos) << result.data;
EXPECT_NE(result.data.find("\"nodeA\":2"), std::string::npos) << result.data;
EXPECT_NE(result.data.find("\"nodeB\":1"), std::string::npos) << result.data;
}
// OR_SET: elements removed via tombstones are excluded; others survive
TEST(MMCRDTResolverTest, ORSetRemovesTombstonedElements) {
CRDTMergeResolver resolver(CRDTMergeResolver::CRDTType::OR_SET);
// nodeA added "apple" with tag-1 and "banana" with tag-2
MMWriteEntry e1;
e1.write_id = "w1";
e1.data = R"({"add":[["apple","tag-1"],["banana","tag-2"]],"tombstones":[]})";
e1.hlc = makeHLCTimestamp(100, 0, "nodeA");
// nodeB removed "apple" by tombstoning tag-1
MMWriteEntry e2;
e2.write_id = "w2";
e2.data = R"({"add":[["apple","tag-1"],["banana","tag-2"]],"tombstones":["tag-1"]})";
e2.hlc = makeHLCTimestamp(200, 0, "nodeB");
auto result = resolver.resolve("doc", {e1, e2});
// "apple" was tombstoned (tag-1 removed) → should not appear
EXPECT_EQ(result.data.find("apple"), std::string::npos) << result.data;
// "banana" was not tombstoned → should appear
EXPECT_NE(result.data.find("banana"), std::string::npos) << result.data;
}
TEST(MMCRDTResolverTest, ORSetKeepsElementAddedOnBothNodes) {
CRDTMergeResolver resolver(CRDTMergeResolver::CRDTType::OR_SET);
MMWriteEntry e1;
e1.write_id = "w1";
e1.data = R"({"add":[["cherry","tag-10"]],"tombstones":[]})";
e1.hlc = makeHLCTimestamp(100, 0, "A");
MMWriteEntry e2;
e2.write_id = "w2";
e2.data = R"({"add":[["cherry","tag-11"]],"tombstones":["tag-10"]})";
e2.hlc = makeHLCTimestamp(200, 0, "B");
auto result = resolver.resolve("doc", {e1, e2});
// "cherry" still has live tag tag-11 → must survive
EXPECT_NE(result.data.find("cherry"), std::string::npos) << result.data;
}
// TWO_P_SET: added elements minus removed elements
TEST(MMCRDTResolverTest, TwoPSetExcludesRemovedElements) {
CRDTMergeResolver resolver(CRDTMergeResolver::CRDTType::TWO_P_SET);
MMWriteEntry e1;
e1.write_id = "w1";
e1.data = R"({"add":["alpha","beta","gamma"],"remove":["beta"]})";
e1.hlc = makeHLCTimestamp(100, 0, "A");
MMWriteEntry e2;
e2.write_id = "w2";
e2.data = R"({"add":["alpha","delta"],"remove":[]})";
e2.hlc = makeHLCTimestamp(200, 0, "B");
auto result = resolver.resolve("doc", {e1, e2});