-
Notifications
You must be signed in to change notification settings - Fork 802
Expand file tree
/
Copy pathvopr.zig
More file actions
1809 lines (1577 loc) · 75.8 KB
/
vopr.zig
File metadata and controls
1809 lines (1577 loc) · 75.8 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
const std = @import("std");
const stdx = @import("stdx");
const builtin = @import("builtin");
const assert = std.debug.assert;
const maybe = stdx.maybe;
const mem = std.mem;
const ratio = stdx.PRNG.ratio;
const Ratio = stdx.PRNG.Ratio;
const range_inclusive_ms = @import("./testing/fuzz.zig").range_inclusive_ms;
const constants = @import("constants.zig");
const schema = @import("lsm/schema.zig");
const vsr = @import("vsr.zig");
const fuzz = @import("./testing/fuzz.zig");
const Header = vsr.Header;
pub const vsr_options = .{
.config_verify = true,
.git_commit = @import("vsr_options").git_commit,
.release = @import("vsr_options").release,
.release_client_min = @import("vsr_options").release_client_min,
};
const vsr_vopr_options = @import("vsr_vopr_options");
const state_machine = vsr_vopr_options.state_machine;
const StateMachineType = switch (state_machine) {
.accounting => @import("state_machine.zig").StateMachineType,
.testing => @import("testing/state_machine.zig").StateMachineType,
};
const Cluster = @import("testing/cluster.zig").ClusterType(StateMachineType);
const Release = @import("testing/cluster.zig").Release;
const StateMachine = Cluster.StateMachine;
const Failure = @import("testing/cluster.zig").Failure;
const PartitionMode = @import("testing/packet_simulator.zig").PartitionMode;
const PartitionSymmetry = @import("testing/packet_simulator.zig").PartitionSymmetry;
const Core = @import("testing/cluster/network.zig").Network.Core;
const ReplySequence = @import("testing/reply_sequence.zig").ReplySequence;
const Message = @import("message_pool.zig").MessagePool.Message;
const MiB = stdx.MiB;
const releases = [_]Release{
.{
.release = vsr.Release.from(.{ .major = 0, .minor = 0, .patch = 1 }),
.release_client_min = vsr.Release.from(.{ .major = 0, .minor = 0, .patch = 1 }),
},
.{
.release = vsr.Release.from(.{ .major = 0, .minor = 0, .patch = 2 }),
.release_client_min = vsr.Release.from(.{ .major = 0, .minor = 0, .patch = 1 }),
},
.{
.release = vsr.Release.from(.{ .major = 0, .minor = 0, .patch = 3 }),
.release_client_min = vsr.Release.from(.{ .major = 0, .minor = 0, .patch = 1 }),
},
};
const log = std.log.scoped(.simulator);
pub const std_options: std.Options = .{
// The -vopr-log=<full|short> build option selects two logging modes.
// In "short" mode, only state transitions are printed (see `Cluster.log_replica`).
// "full" mode is the usual logging according to the level.
.log_level = if (vsr_vopr_options.log == .short) .info else .debug,
.logFn = log_override,
// Uncomment if you need per-scope control over the log levels.
// pub const log_scope_levels: []const std.log.ScopeLevel = &.{
// .{ .scope = .cluster, .level = .info },
// .{ .scope = .replica, .level = .debug },
// };
};
pub const tigerbeetle_config = @import("config.zig").configs.test_min;
const cluster_id = 0;
const CLIArgs = struct {
// "lite" mode runs a small cluster and only looks for crashes.
lite: bool = false,
performance: bool = false,
// Feel free to add more runtime overrides here!
ticks_max_requests: u32 = 40_000_000,
ticks_max_convergence: u32 = 10_000_000,
packet_loss_ratio: ?Ratio = null,
replica_missing: ?u8 = null,
replica_missing_until_request: ?u32 = null,
requests_max: ?u32 = null,
@"--": void,
seed: ?[]const u8 = null,
};
pub fn main() !void {
comptime assert(constants.verify);
// This must be initialized at runtime as stderr is not comptime known on e.g. Windows.
log_buffer.unbuffered_writer = std.io.getStdErr().writer();
fuzz.limit_ram();
var gpa_instance: std.heap.GeneralPurposeAllocator(.{}) = .{};
defer {
_ = gpa_instance.detectLeaks();
switch (gpa_instance.deinit()) {
.ok => {},
.leak => @panic("memory leaked"),
}
}
const gpa = gpa_instance.allocator();
var flags = stdx.Flags.init(gpa);
defer flags.deinit(gpa);
const cli_args = flags.parse(CLIArgs);
if (cli_args.lite and cli_args.performance) {
return vsr.fatal(.cli, "--lite and --performance are mutually exclusive", .{});
}
if (cli_args.replica_missing != null and !cli_args.performance) {
return vsr.fatal(.cli, "--replica-missing requires --performance", .{});
}
if (cli_args.replica_missing == null and cli_args.replica_missing_until_request != null) {
return vsr.fatal(.cli, "--replica-missing-until-request requires --replica-missing", .{});
}
log_performance_mode = cli_args.performance;
const seed_random = std.crypto.random.int(u64);
const seed = seed_from_arg: {
const seed_argument = cli_args.seed orelse break :seed_from_arg seed_random;
break :seed_from_arg vsr.testing.parse_seed(seed_argument);
};
// We do not support ReleaseFast or ReleaseSmall because they disable assertions.
comptime assert(builtin.mode == .Debug or builtin.mode == .ReleaseSafe);
if (seed == seed_random) {
if (builtin.mode != .ReleaseSafe) {
// If no seed is provided, than Debug is too slow and ReleaseSafe is much faster.
return vsr.fatal(
.cli,
"no seed provided: the simulator must be run with -OReleaseSafe",
.{},
);
}
if (vsr_vopr_options.log != .short) {
log.warn("no seed provided: full debug logs are enabled, this will be slow", .{});
}
}
var prng = stdx.PRNG.from_seed(seed);
var options = if (cli_args.lite)
options_lite(&prng)
else if (cli_args.performance)
options_performance(&prng)
else
options_swarm(&prng);
options.replica_missing = cli_args.replica_missing;
options.replica_missing_until_request = cli_args.replica_missing_until_request;
if (cli_args.packet_loss_ratio) |packet_loss_ratio| {
options.network.packet_loss_probability = packet_loss_ratio;
}
if (cli_args.requests_max) |requests_max| {
options.requests_max = requests_max;
}
if (options.replica_missing_until_request != null and
options.requests_max < options.replica_missing_until_request.?)
{
return vsr.fatal(.cli, "--requests-max < --replica-missing-until-request", .{});
}
log.info(
\\
\\ SEED={}
\\
\\ replicas={}
\\ standbys={}
\\ clients={}
\\ request_probability={}
\\ idle_on_probability={}
\\ idle_off_probability={}
\\ one_way_delay_mean={}
\\ one_way_delay_min={}
\\ packet_loss_probability={}
\\ path_maximum_capacity={} messages
\\ path_clog_duration_mean={}
\\ path_clog_probability={}
\\ packet_replay_probability={}
\\ partition_mode={s}
\\ partition_symmetry={s}
\\ partition_probability={}
\\ unpartition_probability={}
\\ partition_stability={} ticks
\\ unpartition_stability={} ticks
\\ read_latency_min={}
\\ read_latency_mean={}
\\ write_latency_min={}
\\ write_latency_mean={}
\\ read_fault_probability={}
\\ write_fault_probability={}
\\ crash_probability={}
\\ crash_stability={} ticks
\\ restart_probability={}
\\ restart_stability={} ticks
, .{
seed,
options.cluster.replica_count,
options.cluster.standby_count,
options.cluster.client_count,
options.request_probability,
options.request_idle_on_probability,
options.request_idle_off_probability,
options.network.one_way_delay_mean,
options.network.one_way_delay_min,
options.network.packet_loss_probability,
options.network.path_maximum_capacity,
options.network.path_clog_duration_mean,
options.network.path_clog_probability,
options.network.packet_replay_probability,
@tagName(options.network.partition_mode),
@tagName(options.network.partition_symmetry),
options.network.partition_probability,
options.network.unpartition_probability,
options.network.partition_stability,
options.network.unpartition_stability,
options.storage.read_latency_min,
options.storage.read_latency_mean,
options.storage.write_latency_min,
options.storage.write_latency_mean,
options.storage.read_fault_probability,
options.storage.write_fault_probability,
options.replica_crash_probability,
options.replica_crash_stability,
options.replica_restart_probability,
options.replica_restart_stability,
});
var simulator = try Simulator.init(gpa, &prng, options);
defer simulator.deinit(gpa);
if (cli_args.performance) {
// Simulate a missing replica by crashing it with ∞ stability.
if (options.replica_missing) |replica_index| {
if (replica_index > options.network.node_count) {
vsr.fatal(.cli, "--replica-index too large", .{});
}
simulator.cluster.replica_crash(replica_index);
simulator.replica_crash_stability[replica_index] = std.math.maxInt(u32);
}
// Warm-up the cluster before performance testing to get past the initial view change.
simulator.options.request_probability = Ratio.zero();
for (0..500) |_| simulator.tick();
simulator.options.request_probability = options.request_probability;
}
for (0..options.cluster.client_count) |client_index| {
simulator.cluster.register(client_index);
}
// Safety: replicas crash and restart; at any given point in time arbitrarily many replicas may
// be crashed, but each replica restarts eventually. The cluster must process all requests
// without split-brain.
var tick_total: u64 = 0;
var tick: u64 = 0;
var requests_done: bool = false;
var upgrades_done: bool = false;
while (tick < cli_args.ticks_max_requests) : (tick += 1) {
const requests_replied_old = simulator.requests_replied;
simulator.tick();
tick_total += 1;
if (simulator.requests_replied > requests_replied_old) {
tick = 0;
}
requests_done = simulator.requests_replied == simulator.options.requests_max;
upgrades_done =
for (simulator.cluster.replicas, simulator.cluster.replica_health) |*replica, health| {
if (health != .up) continue;
const release_latest = releases[simulator.replica_releases_limit - 1].release;
if (replica.release.value == release_latest.value) {
break true;
}
} else false;
if (requests_done and upgrades_done) break;
}
if (cli_args.lite) {
// Don't care about convergence.
} else if (cli_args.performance) {
assert(requests_done and upgrades_done);
var core = full_core(
simulator.options.cluster.replica_count,
simulator.options.cluster.standby_count,
);
if (cli_args.replica_missing) |replica_missing| {
// If replica is permanently missing then exclude it from the core.
if (cli_args.replica_missing_until_request == null) core.unset(replica_missing);
}
simulator.transition_to_liveness_mode(core);
tick = 0;
while (tick < cli_args.ticks_max_convergence) : (tick += 1) {
simulator.tick();
tick_total += 1;
if (simulator.pending() == null) break;
}
assert(simulator.pending() == null);
} else {
const core = if (requests_done and upgrades_done)
// Liveness: a core set of replicas is up and fully connected. The rest of the replicas
// might be crashed or partitioned permanently. The core should converge to the same
// state.
random_core(
simulator.prng,
simulator.options.cluster.replica_count,
simulator.options.cluster.standby_count,
)
else
// Safety mode ran out of ticks without completing its requests, so now we check whether
// it was correct to do so.
//
// Run a fully-connected core of replicas to repair all faulty grid blocks, headers, and
// prepares that can be repaired. Thereafter, only correlated faults should remain.
full_core(
simulator.options.cluster.replica_count,
simulator.options.cluster.standby_count,
);
simulator.transition_to_liveness_mode(core);
tick = 0;
while (tick < cli_args.ticks_max_convergence) : (tick += 1) {
simulator.tick();
tick_total += 1;
if (simulator.pending() == null) {
break;
}
}
if (simulator.pending()) |reason| {
if (try simulator.cluster_recoverable(gpa)) {
log.info("no liveness, final cluster state (core={b}):", .{simulator.core.bits});
simulator.cluster.log_cluster();
log.err("you can reproduce this failure with seed={}", .{seed});
fatal(.liveness, "no state convergence: {s}", .{reason});
}
} else {
const commits = simulator.cluster.state_checker.commits.items;
const last_checksum = commits[commits.len - 1].header.checksum;
for (simulator.cluster.aofs, 0..) |*aof, replica_index| {
if (simulator.core.is_set(replica_index)) {
try aof.validate(gpa, last_checksum);
} else {
try aof.validate(gpa, null);
}
}
}
}
if (cli_args.performance) {
log.info("\nMessages:\n{}", .{simulator.cluster.network.message_summary});
} else {
log.debug("\nMessages:\n{}", .{simulator.cluster.network.message_summary});
}
log.info("\n PASSED ({} ticks)", .{tick_total});
}
fn options_swarm(prng: *stdx.PRNG) Simulator.Options {
const replica_count = prng.range_inclusive(u8, 1, constants.replicas_max);
const standby_count = prng.int_inclusive(u8, constants.standbys_max);
const node_count = replica_count + standby_count;
// -1 since otherwise it is possible that all clients will evict each other.
// (Due to retried register messages from the first set of evicted clients.
// See the "Cluster: eviction: session_too_low" replica test for a related scenario.)
const client_count = prng.range_inclusive(u8, 1, constants.clients_max * 2 - 1);
const batch_size_limit_min = comptime batch_size_limit_min: {
var event_size_max: u32 = @sizeOf(vsr.RegisterRequest);
for (std.enums.values(StateMachine.Operation)) |operation| {
event_size_max = @max(event_size_max, operation.event_size());
}
break :batch_size_limit_min event_size_max;
};
const batch_size_limit: u32 = if (prng.boolean())
constants.message_body_size_max
else
prng.range_inclusive(u32, batch_size_limit_min, constants.message_body_size_max);
const multi_batch_per_request_limit: u32 = multi_batch_per_request_limit: {
const event_max = @divFloor(batch_size_limit, batch_size_limit_min);
assert(event_max > 0);
break :multi_batch_per_request_limit if (event_max == 1) 1 else prng.range_inclusive(
u32,
1,
event_max - 1, // Minus one for the multi-batch trailer.
);
};
const storage_size_limit = vsr.sector_floor(
200 * MiB - prng.int_inclusive(u64, 20 * MiB),
);
const cluster_options: Cluster.Options = .{
.cluster_id = cluster_id,
.replica_count = replica_count,
.standby_count = standby_count,
.client_count = client_count,
.storage_size_limit = storage_size_limit,
.seed = prng.int(u64),
.releases = &releases,
.client_release = releases[0].release,
.reformats_max = replica_count + 2, // Arbitrary reformat limit.
.state_machine = switch (state_machine) {
.testing => .{
.batch_size_limit = batch_size_limit,
.lsm_forest_node_count = 4096,
},
.accounting => .{
.batch_size_limit = batch_size_limit,
.lsm_forest_compaction_block_count = prng.int_inclusive(u32, 256) +
StateMachine.Forest.Options.compaction_block_count_min,
.lsm_forest_node_count = 4096,
.cache_entries_accounts = if (prng.boolean()) 256 else 0,
.cache_entries_transfers = if (prng.boolean()) 256 else 0,
.cache_entries_transfers_pending = if (prng.boolean()) 256 else 0,
.log_trace = true,
.aof_recovery = false,
},
},
.replicate_options = .{
.closed_loop = prng.chance(ratio(1, 5)),
.star = prng.chance(ratio(1, 5)),
},
};
const network_options: Cluster.NetworkOptions = .{
.node_count = node_count,
.client_count = client_count,
.seed = prng.int(u64),
.one_way_delay_min = range_inclusive_ms(prng, 0, 30),
.one_way_delay_mean = range_inclusive_ms(prng, 30, 100),
.packet_loss_probability = ratio(prng.int_inclusive(u8, 30), 100),
.path_maximum_capacity = prng.range_inclusive(u8, 2, 20),
.path_clog_duration_mean = range_inclusive_ms(prng, 0, 5_000),
.path_clog_probability = ratio(prng.int_inclusive(u8, 2), 100),
.packet_replay_probability = ratio(prng.int_inclusive(u8, 50), 100),
.partition_mode = prng.enum_uniform(PartitionMode),
.partition_symmetry = prng.enum_uniform(PartitionSymmetry),
.partition_probability = ratio(prng.int_inclusive(u8, 3), 100),
.unpartition_probability = ratio(prng.range_inclusive(u8, 1, 10), 100),
.partition_stability = 100 + prng.int_inclusive(u32, 100),
.unpartition_stability = prng.int_inclusive(u32, 20),
};
const read_latency_min = range_inclusive_ms(prng, 0, 30);
const write_latency_min = range_inclusive_ms(prng, 0, 30);
const storage_options: Cluster.Storage.Options = .{
.size = cluster_options.storage_size_limit,
.seed = prng.int(u64),
.read_latency_min = read_latency_min,
.read_latency_mean = range_inclusive_ms(prng, read_latency_min, 100),
.write_latency_min = write_latency_min,
.write_latency_mean = range_inclusive_ms(prng, write_latency_min, 1_000),
.read_fault_probability = ratio(prng.range_inclusive(u8, 0, 10), 100),
.write_fault_probability = ratio(prng.range_inclusive(u8, 0, 10), 100),
.write_misdirect_probability = ratio(prng.range_inclusive(u8, 0, 10), 100),
.crash_fault_probability = ratio(prng.range_inclusive(u8, 80, 100), 100),
};
const storage_fault_atlas: Cluster.StorageFaultAtlas.Options = .{
.faulty_superblock = true,
.faulty_wal_headers = replica_count > 1,
.faulty_wal_prepares = replica_count > 1,
.faulty_client_replies = replica_count > 1,
// >2 instead of >1 because in R=2, a lagging replica may sync to the leading replica,
// but then the leading replica may have the only copy of a block in the cluster.
.faulty_grid = replica_count > 2,
};
const workload_options = StateMachine.Workload.Options.generate(prng, .{
.batch_size_limit = batch_size_limit,
.multi_batch_per_request_limit = multi_batch_per_request_limit,
.client_count = client_count,
// TODO(DJ) Once Workload no longer needs in_flight_max, make stalled_queue_capacity
// private. Also maybe make it dynamic (computed from the client_count instead of
// clients_max).
.in_flight_max = ReplySequence.stalled_queue_capacity *
multi_batch_per_request_limit,
});
return .{
.cluster = cluster_options,
.network = network_options,
.storage = storage_options,
.storage_fault_atlas = storage_fault_atlas,
.workload = workload_options,
// TODO Swarm testing: Test long+few crashes and short+many crashes separately.
.replica_crash_probability = ratio(2, 10_000_000),
.replica_crash_stability = prng.int_inclusive(u32, 1_000),
.replica_restart_probability = ratio(2, 1_000_000),
.replica_restart_stability = prng.int_inclusive(u32, 1_000),
.replica_reformat_probability = ratio(30, 100),
.replica_pause_probability = ratio(8, 10_000_000),
.replica_pause_stability = prng.int_inclusive(u32, 1_000),
.replica_unpause_probability = ratio(8, 1_000_000),
.replica_unpause_stability = prng.int_inclusive(u32, 1_000),
.replica_release_advance_probability = ratio(1, 1_000_000),
.replica_release_catchup_probability = ratio(1, 100_000),
.requests_max = constants.journal_slot_count * 3,
.request_probability = ratio(prng.range_inclusive(u8, 1, 100), 100),
.request_idle_on_probability = ratio(prng.range_inclusive(u8, 0, 20), 100),
.request_idle_off_probability = ratio(prng.range_inclusive(u8, 10, 20), 100),
};
}
fn options_lite(prng: *stdx.PRNG) Simulator.Options {
var base = options_swarm(prng);
base.cluster.replica_count = 3;
base.cluster.standby_count = 0;
base.network.node_count = 3;
return base;
}
fn options_performance(prng: *stdx.PRNG) Simulator.Options {
const cluster_options: Cluster.Options = .{
.cluster_id = cluster_id,
.replica_count = 6,
.standby_count = 0,
.client_count = 4,
.storage_size_limit = vsr.sector_floor(200 * MiB),
.seed = prng.int(u64),
.releases = releases[0..1],
.client_release = releases[0].release,
.reformats_max = 0,
.state_machine = switch (state_machine) {
.testing => .{
.batch_size_limit = constants.message_body_size_max,
.lsm_forest_node_count = 4096,
},
.accounting => .{
.batch_size_limit = constants.message_body_size_max,
.lsm_forest_compaction_block_count = 128 +
StateMachine.Forest.Options.compaction_block_count_min,
.lsm_forest_node_count = 4096,
.cache_entries_accounts = 256,
.cache_entries_transfers = 0,
.cache_entries_transfers_pending = 0,
.log_trace = true,
.aof_recovery = false,
},
},
};
const network_options: Cluster.NetworkOptions = .{
.node_count = cluster_options.replica_count,
.client_count = cluster_options.client_count,
.seed = prng.int(u64),
.one_way_delay_mean = .ms(50),
.one_way_delay_min = .{ .ns = 0 },
.packet_loss_probability = Ratio.zero(),
.path_maximum_capacity = 10,
.path_clog_duration_mean = .ms(2_000),
.path_clog_probability = Ratio.zero(),
.packet_replay_probability = Ratio.zero(),
.partition_mode = .none,
.partition_symmetry = .symmetric,
.partition_probability = Ratio.zero(),
.unpartition_probability = Ratio.zero(),
.partition_stability = 100,
.unpartition_stability = 10,
};
const storage_options: Cluster.Storage.Options = .{
.size = cluster_options.storage_size_limit,
.seed = prng.int(u64),
.read_latency_min = .{ .ns = 0 },
.read_latency_mean = .{ .ns = 0 },
.write_latency_min = .{ .ns = 0 },
.write_latency_mean = .{ .ns = 0 },
.read_fault_probability = Ratio.zero(),
.write_fault_probability = Ratio.zero(),
.write_misdirect_probability = Ratio.zero(),
.crash_fault_probability = Ratio.zero(),
};
const storage_fault_atlas: Cluster.StorageFaultAtlas.Options = .{
.faulty_superblock = false,
.faulty_wal_headers = false,
.faulty_wal_prepares = false,
.faulty_client_replies = false,
.faulty_grid = false,
};
var workload_prng = stdx.PRNG.from_seed(92); // Fix workload for perf testing.
const workload_options = StateMachine.Workload.Options.generate(&workload_prng, .{
.batch_size_limit = constants.message_body_size_max,
.multi_batch_per_request_limit = 1,
.client_count = cluster_options.client_count,
.in_flight_max = ReplySequence.stalled_queue_capacity,
});
return .{
.cluster = cluster_options,
.network = network_options,
.storage = storage_options,
.storage_fault_atlas = storage_fault_atlas,
.workload = workload_options,
.replica_crash_probability = Ratio.zero(),
.replica_crash_stability = 500,
.replica_restart_probability = Ratio.zero(),
.replica_restart_stability = 500,
.replica_reformat_probability = ratio(0, 100),
.replica_pause_probability = Ratio.zero(),
.replica_pause_stability = 500,
.replica_unpause_probability = Ratio.zero(),
.replica_unpause_stability = 500,
.replica_release_advance_probability = Ratio.zero(),
.replica_release_catchup_probability = Ratio.zero(),
.requests_max = constants.journal_slot_count * 8,
.request_probability = ratio(100, 100),
.request_idle_on_probability = Ratio.zero(),
.request_idle_off_probability = ratio(100, 100),
};
}
pub const Simulator = struct {
pub const Options = struct {
cluster: Cluster.Options,
network: Cluster.NetworkOptions,
storage: Cluster.Storage.Options,
storage_fault_atlas: Cluster.StorageFaultAtlas.Options,
workload: StateMachine.Workload.Options,
/// Probability per tick that a crash will occur.
replica_crash_probability: Ratio,
/// Minimum duration of a crash.
replica_crash_stability: u32,
/// Probability per tick that a crashed replica will recovery.
replica_restart_probability: Ratio,
/// Minimum time a replica is up until it is crashed again.
replica_restart_stability: u32,
/// Probability per restart that a replica will be reformatted with `tigerbeetle recover`
/// (immediately before being restarted).
replica_reformat_probability: Ratio,
// A replica permanently or temporarily missing from the cluster, used in performance mode.
replica_missing: ?u8 = null,
/// Restart `replica_missing` after the specified request has received its reply.
replica_missing_until_request: ?u32 = null,
replica_pause_probability: Ratio,
replica_pause_stability: u32,
replica_unpause_probability: Ratio,
replica_unpause_stability: u32,
/// Probability per tick that a healthy replica will be crash-upgraded.
/// This probability is set to 0 during liveness mode.
replica_release_advance_probability: Ratio,
/// Probability that a crashed with an outdated version will be upgraded as it restarts.
/// This helps ensure that when the cluster upgrades, that replicas without the newest
/// version don't take too long to receive that new version.
/// This probability is set to 0 during liveness mode.
replica_release_catchup_probability: Ratio,
/// The total number of requests to send. Does not count `register` messages.
requests_max: usize,
request_probability: Ratio,
request_idle_on_probability: Ratio,
request_idle_off_probability: Ratio,
};
prng: *stdx.PRNG,
options: Options,
cluster: *Cluster,
workload: StateMachine.Workload,
// The number of releases in each replica's "binary".
replica_releases: []usize,
/// The maximum number of releases available in any replica's "binary".
/// (i.e. the maximum of any `replica_releases`.)
replica_releases_limit: usize = 1,
/// Keep track of which replicas have possibly "lost" data.
// TODO We could unset this when a replica fully recovers.
replica_reformats: Core = .{},
/// Protect a replica from fast successive crash/restarts.
replica_crash_stability: []usize,
reply_sequence: ReplySequence,
reply_op_next: u64 = 1, // Skip the root op.
/// Fully-connected subgraph of replicas for liveness checking.
core: Core = .{},
/// Total number of requests sent, including those that have not been delivered.
/// Does not include `register` messages.
requests_sent: usize = 0,
/// Total number of replies received by non-evicted clients.
/// Does not include `register` messages.
requests_replied: usize = 0,
requests_idle: bool = false,
pub fn init(
gpa: std.mem.Allocator,
prng: *stdx.PRNG,
options: Options,
) !Simulator {
assert(options.requests_max > 0);
assert(options.request_probability.numerator > 0);
assert(options.request_idle_off_probability.numerator > 0);
var cluster = try Cluster.init(gpa, .{
.cluster = options.cluster,
.network = options.network,
.storage = options.storage,
.storage_fault_atlas = options.storage_fault_atlas,
.callbacks = .{
.on_cluster_reply = on_cluster_reply,
.on_client_reply = on_client_reply,
},
});
errdefer cluster.deinit();
var workload = try StateMachine.Workload.init(gpa, prng, options.workload);
errdefer workload.deinit(gpa);
const replica_releases = try gpa.alloc(
usize,
options.cluster.replica_count + options.cluster.standby_count,
);
errdefer gpa.free(replica_releases);
@memset(replica_releases, 1);
const replica_crash_stability = try gpa.alloc(
usize,
options.cluster.replica_count + options.cluster.standby_count,
);
errdefer gpa.free(replica_crash_stability);
@memset(replica_crash_stability, 0);
var reply_sequence = try ReplySequence.init(gpa);
errdefer reply_sequence.deinit(gpa);
return Simulator{
.prng = prng,
.options = options,
.cluster = cluster,
.workload = workload,
.replica_releases = replica_releases,
.replica_crash_stability = replica_crash_stability,
.reply_sequence = reply_sequence,
};
}
pub fn deinit(simulator: *Simulator, gpa: std.mem.Allocator) void {
gpa.free(simulator.replica_releases);
gpa.free(simulator.replica_crash_stability);
simulator.reply_sequence.deinit(gpa);
simulator.workload.deinit(gpa);
simulator.cluster.deinit();
}
pub fn pending(simulator: *const Simulator) ?[]const u8 {
assert(simulator.core.count() > 0);
assert(simulator.requests_sent - simulator.cluster.client_eviction_requests_cancelled <=
simulator.options.requests_max);
assert(simulator.reply_sequence.empty());
for (simulator.cluster.clients) |*client_maybe| {
if (client_maybe.*) |client| {
if (client.request_inflight) |_| return "pending request";
}
}
// Even though there are no client requests in progress, the cluster may be upgrading.
const release_max = simulator.core_release_max();
for (simulator.cluster.replicas) |*replica| {
if (simulator.core.is_set(replica.replica)) {
// (If down, the replica is waiting to be upgraded.)
maybe(simulator.cluster.replica_health[replica.replica] == .down);
if (replica.release.value != release_max.value) return "pending upgrade";
}
}
for (simulator.cluster.replicas) |*replica| {
if (simulator.core.is_set(replica.replica)) {
if (!simulator.cluster.state_checker.replica_convergence(replica.replica)) {
return "pending replica convergence";
}
}
}
simulator.cluster.state_checker.assert_cluster_convergence();
// Check whether the replica is still repairing prepares/tables/replies.
const commit_max: u64 = simulator.cluster.state_checker.commits.items.len - 1;
for (simulator.cluster.replicas) |*replica| {
if (simulator.core.is_set(replica.replica)) {
for (replica.op_checkpoint() + 1..commit_max + 1) |op| {
const header = simulator.cluster.state_checker.header_with_op(op);
if (!replica.journal.has_prepare(&header)) return "pending journal";
}
// It's okay for a replica to miss some prepares older than the current checkpoint.
maybe(replica.journal.faulty.count > 0);
if (!replica.sync_content_done()) return "pending sync content";
}
}
// Expect that all core replicas have arrived at an identical (non-divergent) checkpoint.
var checkpoint_id: ?u128 = null;
for (simulator.cluster.replicas) |*replica| {
if (simulator.core.is_set(replica.replica)) {
const replica_checkpoint_id = replica.superblock.working.checkpoint_id();
if (checkpoint_id) |id| {
assert(checkpoint_id == id);
} else {
checkpoint_id = replica_checkpoint_id;
}
}
}
assert(checkpoint_id != null);
return null;
}
pub fn tick(simulator: *Simulator) void {
// TODO(Zig): Remove (see on_cluster_reply()).
simulator.cluster.context = simulator;
simulator.cluster.tick();
simulator.tick_requests();
simulator.tick_upgrade();
simulator.tick_crash();
simulator.tick_pause();
if (simulator.options.replica_missing_until_request) |request| {
if (simulator.requests_replied >= request) {
simulator.options.replica_missing_until_request = null;
simulator.replica_restart(simulator.options.replica_missing.?, false);
}
}
}
pub fn cluster_recoverable(simulator: *Simulator, gpa: std.mem.Allocator) !bool {
if (simulator.core_missing_primary()) {
unimplemented("repair requires reachable primary");
} else if (simulator.core_missing_quorum()) {
log.warn("no liveness, core replicas cannot view-change", .{});
} else if (try simulator.core_missing_prepare(gpa)) |op| {
log.warn("no liveness, op={} is not available in core", .{op});
} else if (try simulator.core_missing_blocks(gpa)) |blocks| {
log.warn("no liveness, {} blocks are not available in core", .{blocks});
} else if (simulator.core_missing_reply()) |header| {
log.warn("no liveness, reply op={} is not available in core", .{header.op});
} else if (simulator.core_reformat_evicted()) {
log.warn("no liveness, one or more reformat clients was evicted", .{});
} else {
return true;
}
return false;
}
/// Executes the following:
/// * Restart any core replicas that are down at the moment
/// * Heal all network partitions between core replicas
/// * Disable storage faults on the core replicas
/// * For all failures involving non-core replicas, make those failures permanent.
///
/// See https://tigerbeetle.com/blog/2023-07-06-simulation-testing-for-liveness for broader
/// context.
pub fn transition_to_liveness_mode(simulator: *Simulator, core: Core) void {
log.debug("transition_to_liveness_mode: core={b}", .{core.bits});
assert(simulator.core.count() == 0);
defer assert(simulator.core.count() > 0);
simulator.core = core;
var it = core.iterate();
while (it.next()) |replica_index| {
const fault = false;
if (simulator.cluster.replica_health[replica_index] == .down) {
simulator.replica_restart(@intCast(replica_index), fault);
}
const replica_health = simulator.cluster.replica_health[replica_index];
if (replica_health == .up and replica_health.up.paused) {
simulator.cluster.replica_unpause(@intCast(replica_index));
}
simulator.cluster.storages[replica_index].transition_to_liveness_mode();
}
simulator.cluster.network.transition_to_liveness_mode(simulator.core);
simulator.options.replica_crash_probability = Ratio.zero();
simulator.options.replica_restart_probability = Ratio.zero();
simulator.options.replica_reformat_probability = Ratio.zero();
simulator.options.replica_pause_probability = Ratio.zero();
simulator.options.replica_release_advance_probability = Ratio.zero();
simulator.options.replica_release_catchup_probability = Ratio.zero();
}
// If a primary ends up being outside of a core, and is only partially connected to the core,
// the core might fail to converge, as parts of the repair protocol rely on primary-sent
// `.exit_view` messages. Until we fix this issue, we special-case this scenario in
// VOPR and don't treat it as a liveness failure.
//
// TODO: make sure that .recovering_head replicas can transition to normal even without direct
// connection to the primary
pub fn core_missing_primary(simulator: *const Simulator) bool {
assert(simulator.core.count() > 0);
for (simulator.cluster.replicas) |*replica| {
if (simulator.cluster.replica_health[replica.replica] == .up and
replica.status == .normal and replica.primary() and
!simulator.core.is_set(replica.replica))
{
// `replica` considers itself a primary, check that at least part of the core thinks
// so as well.
var it = simulator.core.iterate();
while (it.next()) |replica_core_index| {
if (simulator.cluster.replicas[replica_core_index].view == replica.view) {
return true;
}
}
}
}
return false;
}
/// The core contains at least a view-change quorum of replicas. But if one or more of those
/// replicas are in status=recovering_head (due to corruption) or are stuck reformatting, then
/// that may be insufficient.
pub fn core_missing_quorum(simulator: *const Simulator) bool {
assert(simulator.core.count() > 0);
var core_replicas: u8 = 0;
var core_recovering: u8 = 0;
for (
simulator.cluster.replicas,
simulator.cluster.replica_health,
) |*replica, health| {
if (simulator.core.is_set(replica.replica) and !replica.standby()) {
core_replicas += 1;
switch (health) {
.up => core_recovering += @intFromBool(replica.status == .recovering_head),
.down => unreachable,
.reformatting => core_recovering += 1,
}
}
}
const quorums = vsr.quorums(simulator.options.cluster.replica_count);
assert(quorums.view_change <= core_replicas);
return quorums.view_change > core_replicas - core_recovering;
}
fn core_repairable_replica(
simulator: *const Simulator,
comptime Replica: type,
replica: *const Replica,
) bool {
if (!simulator.core.is_set(replica.replica)) return false;
if (replica.standby()) return false;
if (simulator.cluster.replica_health[replica.replica] == .reformatting) return false;
assert(simulator.cluster.replica_health[replica.replica] == .up);
switch (replica.status) {
.normal => return true,
.recovering_head => return false,
// Lagging replicas do not initiate WAL repair during view change.
.view_change => return !vsr.Checkpoint.durable(
replica.op_checkpoint_next(),
replica.commit_max,
),
.recovering => unreachable,
}
}
// Returns an op for a prepare which can't be repaired by the core due to storage faults.