Skip to content

Commit d2f4997

Browse files
committed
update madsim and docs for deterministic
1 parent 9951331 commit d2f4997

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ description = "The labs of Raft consensus algorithm on MadSim."
88
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
99

1010
[dependencies]
11-
madsim = { version = "0.1", features = ["rpc", "macros", "logger"]}
11+
madsim = { version = "0.1.1", features = ["rpc", "macros", "logger"]}
1212
log = "0.4"
1313
rand = "0.8"
1414
futures = "0.3"

README.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ If a test fails, you will see a seed in the output:
3737
---- raft::tests::initial_election_2a stdout ----
3838
thread 'raft::tests::initial_election_2a' panicked at 'expected one leader, got none', src/raft/tester.rs:91:9
3939
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
40-
seed=1629626496
40+
MADSIM_TEST_SEED=1629626496
4141
```
4242

4343
Run the test again with the seed, and you will get exactly the same output:
@@ -58,6 +58,26 @@ Run the test multiple times to make sure you solution can stably pass the test:
5858
MADSIM_TEST_NUM=100 cargo test --release
5959
```
6060

61+
### Ensure Determinism
62+
63+
Sometimes you may find that the test is not deterministic :(
64+
65+
Although the testing framework itself (MadSim) provides determinism, the entire system is not deterministic if your code introduces randomness.
66+
67+
Here are some tips to avoid randomness:
68+
69+
* Use `madsim::rand::rng` instead of `rand::thread_rng` to generate random numbers.
70+
* Use `futures::select_biased` instead of `futures::select` macro.
71+
* Do not **iterate** through a `HashMap`.
72+
73+
To make sure your code is deterministic, run your test with the following environment variable:
74+
75+
```sh
76+
MADSIM_TEST_CHECK_DETERMINISTIC=1 cargo test
77+
```
78+
79+
Your test will be run at least twice with the same seed. If any non-determinism is detected, it will panic as soon as possible.
80+
6181
Happy coding and Good luck!
6282

6383
## License

0 commit comments

Comments
 (0)