Add HW 9
This commit is contained in:
1 parent
0085512a98
commit
a499e38e6e
15 files changed
+5529
No files matched your search
@@ -0,0 +1,5 @@
|
||||
target
|
||||
**/target
|
||||
**/__pycache__
|
||||
**/.pytest_cache
|
||||
*.pyc
|
||||
+1027
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "distsys-kv-replication-2"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
resolver = "3"
|
||||
|
||||
[dependencies]
|
||||
anysystem = "=0.3.0"
|
||||
indexmap = "2.12"
|
||||
assertables = "3.2.2"
|
||||
byteorder = "1.4.3"
|
||||
clap = { version = "3.2.17", features = ["cargo", "derive"] }
|
||||
decorum = "0.3.1"
|
||||
env_logger = "0.9.0"
|
||||
log = "0.4.17"
|
||||
md5 = "0.7.0"
|
||||
pyo3 = { version = "=0.29.2", features = ["auto-initialize"] }
|
||||
rand = "0.8.5"
|
||||
rand_pcg = "0.3.1"
|
||||
serde = { version = "1.0.142", features = ["derive"] }
|
||||
serde_json = "1.0.83"
|
||||
@@ -0,0 +1,19 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM rust:1.97.1-bookworm@sha256:0e2bcaef56d041a486784e54104a81aebe0da44bd03019bd70bc0401e42e4a97 AS builder
|
||||
|
||||
RUN apt-get update && apt-get install -y build-essential python3-dev
|
||||
|
||||
WORKDIR /tests
|
||||
COPY . .
|
||||
RUN --mount=type=cache,id=distsys-course-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \
|
||||
--mount=type=cache,id=distsys-course-cargo-target-rust-1-97-1,target=/tests/target,sharing=locked \
|
||||
cargo install --locked --path . --root /opt/course
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update && apt-get install -y python3-dev && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=builder /opt/course/bin/distsys-kv-replication-2 /usr/local/bin/distsys-kv-replication-2
|
||||
|
||||
WORKDIR /solution
|
||||
ENTRYPOINT ["timeout", "--verbose", "-k", "10", "600", "distsys-kv-replication-2", "-i", "node.py"]
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Retain exceptions from StorageNode calls for the Rust test runner."""
|
||||
from functools import wraps
|
||||
from inspect import getattr_static
|
||||
|
||||
|
||||
def watch(cls):
|
||||
if not isinstance(cls, type):
|
||||
raise TypeError("StorageNode must be a class")
|
||||
missing = sorted(getattr(cls, "__abstractmethods__", ()))
|
||||
if missing:
|
||||
raise TypeError(f"{cls.__name__} must implement {', '.join(missing)}")
|
||||
errors = []
|
||||
|
||||
def checked(name, method):
|
||||
@wraps(method)
|
||||
def call(*args, **kwargs):
|
||||
try:
|
||||
result = method(*args, **kwargs)
|
||||
except BaseException as exc:
|
||||
errors[:] = [f"{name}: {type(exc).__name__}: {exc}"]
|
||||
raise
|
||||
if errors:
|
||||
errors.clear() # A nested exception was handled by the solution.
|
||||
return result
|
||||
|
||||
return call
|
||||
|
||||
for name in ("__new__", "__init__", "on_start", "on_local_message", "on_message", "on_timer",
|
||||
"get_state", "set_state", "__deepcopy__"):
|
||||
# Preserve static and class methods and inherited implementations.
|
||||
method = getattr_static(cls, name, None)
|
||||
if name == "__new__" and method is object.__new__:
|
||||
continue # Keep the default allocation and constructor argument handling.
|
||||
if isinstance(method, (staticmethod, classmethod)):
|
||||
setattr(cls, name, type(method)(checked(name, method.__func__)))
|
||||
elif callable(method):
|
||||
setattr(cls, name, checked(name, method))
|
||||
return errors
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,169 @@
|
||||
use byteorder::{ByteOrder, LittleEndian};
|
||||
use rand::distributions::WeightedIndex;
|
||||
use rand::prelude::*;
|
||||
use rand_pcg::Pcg64;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use anysystem::python::PyProcessFactory;
|
||||
use anysystem::{Message, System};
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct GetReqMessage<'a> {
|
||||
pub key: &'a str,
|
||||
pub quorum: u8,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct PutReqMessage<'a> {
|
||||
pub key: &'a str,
|
||||
pub value: &'a str,
|
||||
pub context: Option<String>,
|
||||
pub quorum: u8,
|
||||
}
|
||||
|
||||
pub type GetRespMessage = Response<Option<String>>;
|
||||
pub type PutRespMessage = Response<String>;
|
||||
|
||||
pub struct Response<C> {
|
||||
pub key: String,
|
||||
pub values: Vec<String>,
|
||||
pub context: C,
|
||||
}
|
||||
|
||||
impl<C: DeserializeOwned> Response<C> {
|
||||
pub fn parse(msg: &Message, proc: &str) -> Result<Self, String> {
|
||||
Self::from_json(&msg.data)
|
||||
.map_err(|error| format!("Invalid {} from {proc}: {error}", msg.tip))
|
||||
}
|
||||
|
||||
fn from_json(json: &str) -> Result<Self, String> {
|
||||
#[derive(Deserialize)]
|
||||
struct Fields {
|
||||
key: Value,
|
||||
values: Value,
|
||||
context: Value,
|
||||
}
|
||||
|
||||
// Serde also accepts positional arrays for structs; the protocol requires an object.
|
||||
if !json.trim_start().starts_with('{') {
|
||||
return Err("expected a JSON object".to_owned());
|
||||
}
|
||||
let fields: Fields = serde_json::from_str(json).map_err(|e| e.to_string())?;
|
||||
let key: String = response_field("key", fields.key)?;
|
||||
let values: Vec<String> = response_field("values", fields.values)?;
|
||||
let context = response_field("context", fields.context)?;
|
||||
if (key.starts_with("CART") || key.starts_with("XCART")) && values.len() > 1 {
|
||||
return Err(format!(
|
||||
"field `values`: expected at most one basket for {key}, got {}",
|
||||
values.len()
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
key,
|
||||
values,
|
||||
context,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn response_field<T: DeserializeOwned>(name: &str, value: Value) -> Result<T, String> {
|
||||
serde_json::from_value(value).map_err(|error| format!("field `{name}`: {error}"))
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct TestConfig<'a> {
|
||||
pub proc_factory: &'a PyProcessFactory,
|
||||
pub proc_count: u32,
|
||||
pub seed: u64,
|
||||
}
|
||||
|
||||
pub fn build_system(config: &TestConfig) -> System {
|
||||
let mut sys = System::new(config.seed);
|
||||
sys.network().set_delays(0.01, 0.1);
|
||||
let mut proc_names = Vec::new();
|
||||
for n in 0..config.proc_count {
|
||||
proc_names.push(format!("{n}"));
|
||||
}
|
||||
for proc_name in proc_names.iter() {
|
||||
let proc = config
|
||||
.proc_factory
|
||||
.build((proc_name, proc_names.clone()), config.seed);
|
||||
// process and node on which it runs have the same name
|
||||
let node_name = proc_name.clone();
|
||||
sys.add_node(&node_name);
|
||||
sys.add_process(proc_name, Box::new(proc), &node_name);
|
||||
let clock_skew = sys.gen_range(0.0..10.0);
|
||||
sys.set_node_clock_skew(&node_name, clock_skew);
|
||||
}
|
||||
sys
|
||||
}
|
||||
|
||||
pub fn key_replicas(key: &str, sys: &System) -> Vec<String> {
|
||||
let proc_count = sys.process_names().len();
|
||||
let mut replicas = Vec::new();
|
||||
let hash = md5::compute(key);
|
||||
let hash128 = LittleEndian::read_u128(&hash.0);
|
||||
let mut replica = (hash128 % proc_count as u128) as usize;
|
||||
for _ in 0..3 {
|
||||
replicas.push(replica.to_string());
|
||||
replica += 1;
|
||||
if replica == proc_count {
|
||||
replica = 0;
|
||||
}
|
||||
}
|
||||
replicas
|
||||
}
|
||||
|
||||
pub fn key_non_replicas(key: &str, sys: &System) -> Vec<String> {
|
||||
let replicas = key_replicas(key, sys);
|
||||
let mut non_replicas_pre = Vec::new();
|
||||
let mut non_replicas = Vec::new();
|
||||
let mut pre = true;
|
||||
let mut process_names = sys.process_names();
|
||||
process_names.sort();
|
||||
for proc in process_names {
|
||||
if replicas.contains(&proc) {
|
||||
pre = false;
|
||||
continue;
|
||||
}
|
||||
if pre {
|
||||
non_replicas_pre.push(proc);
|
||||
} else {
|
||||
non_replicas.push(proc);
|
||||
}
|
||||
}
|
||||
non_replicas.append(&mut non_replicas_pre);
|
||||
non_replicas
|
||||
}
|
||||
|
||||
const SYMBOLS: [char; 36] = [
|
||||
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
|
||||
't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
||||
];
|
||||
const WEIGHTS: [usize; 36] = [
|
||||
13, 16, 3, 8, 8, 5, 6, 23, 4, 8, 24, 12, 2, 1, 1, 10, 5, 8, 10, 1, 24, 3, 1, 8, 12, 22, 5, 20,
|
||||
18, 5, 5, 2, 1, 3, 16, 22,
|
||||
];
|
||||
|
||||
pub fn random_string(length: usize, rand: &mut Pcg64) -> String {
|
||||
let dist = WeightedIndex::new(WEIGHTS).unwrap();
|
||||
rand.sample_iter(&dist)
|
||||
.take(length)
|
||||
.map(|x| SYMBOLS[x])
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn random_key(rand: &mut Pcg64) -> String {
|
||||
ordinary_key(random_string(8, rand))
|
||||
}
|
||||
|
||||
fn ordinary_key(mut key: String) -> String {
|
||||
key.make_ascii_uppercase();
|
||||
// Keep the RNG sequence for subsequent values even when a reserved prefix occurs.
|
||||
if key.starts_with("CART") || key.starts_with("XCART") {
|
||||
key.replace_range(..1, "K");
|
||||
}
|
||||
key
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
mod common;
|
||||
mod python_errors;
|
||||
mod python_seed;
|
||||
mod shared_state;
|
||||
mod tests;
|
||||
mod tests_mc;
|
||||
|
||||
use indexmap::IndexMap;
|
||||
use std::collections::HashSet;
|
||||
use std::io::Write;
|
||||
|
||||
use clap::Parser;
|
||||
use env_logger::Builder;
|
||||
use log::LevelFilter;
|
||||
|
||||
use anysystem::test::{TestResult, TestSuite};
|
||||
|
||||
use crate::python_errors::{run_case, Case, CaseConfig, Solution};
|
||||
use crate::tests::*;
|
||||
use crate::tests_mc::*;
|
||||
|
||||
/// Replicated KV Store Homework Tests
|
||||
#[derive(Parser, Debug)]
|
||||
#[clap(about, long_about = None)]
|
||||
struct Args {
|
||||
/// Path to Python file with solution
|
||||
#[clap(long = "impl", short = 'i', default_value = "solution/node.py")]
|
||||
solution_path: String,
|
||||
|
||||
/// Test to run (optional)
|
||||
#[clap(long = "test", short)]
|
||||
test: Option<String>,
|
||||
|
||||
/// Print execution trace
|
||||
#[clap(long, short)]
|
||||
debug: bool,
|
||||
|
||||
/// Number of nodes used in tests
|
||||
#[clap(long, short, default_value = "6")]
|
||||
node_count: u32,
|
||||
|
||||
/// Random seed used in tests
|
||||
#[clap(long, short, default_value = "123")]
|
||||
seed: u64,
|
||||
|
||||
/// Skip model checking tests and report only the test results
|
||||
#[clap(long)]
|
||||
disable_mc_tests: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
python_seed::configure(args.seed);
|
||||
python_errors::install_panic_hook();
|
||||
let validation = shared_state::validate_or_report(&args.solution_path, &["StorageNode"]);
|
||||
if matches!(validation, Ok(false)) {
|
||||
if args.disable_mc_tests {
|
||||
println!("No tests ran.");
|
||||
} else {
|
||||
println!("\nSCORE: 0\n");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if args.debug {
|
||||
Builder::new()
|
||||
.filter(Some("anysystem"), LevelFilter::Debug)
|
||||
.format(|buf, record| writeln!(buf, "{}", record.args()))
|
||||
.init();
|
||||
}
|
||||
let solution = validation.and_then(|_| Solution::load(&args.solution_path));
|
||||
let config = CaseConfig {
|
||||
solution: &solution,
|
||||
proc_count: args.node_count,
|
||||
seed: args.seed,
|
||||
};
|
||||
|
||||
let mut tests = TestSuite::new();
|
||||
for &(name, case) in CASES {
|
||||
if !args.disable_mc_tests || !name.starts_with("MC ") {
|
||||
tests.add(name, run_case, (&config, case));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(test) = &args.test {
|
||||
tests.run_test(test);
|
||||
} else {
|
||||
let (_, results) = tests.run();
|
||||
if args.disable_mc_tests {
|
||||
println!("Run the full suite without --disable-mc-tests to see your score.");
|
||||
} else {
|
||||
let score = score(results);
|
||||
println!("\nSCORE: {score}\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const CASES: &[(&str, Case)] = &[
|
||||
("BASIC", test_basic),
|
||||
("MC EMPTY SYSTEM", test_mc_empty_system),
|
||||
("MC BASIC", test_mc_basic),
|
||||
("PUT FORWARDING", test_put_forwarding),
|
||||
("STALE REPLICA", test_stale_replica),
|
||||
("SLOPPY QUORUM", test_sloppy_quorum),
|
||||
(
|
||||
"MC SLOPPY QUORUM HINTED HANDOFF",
|
||||
test_mc_sloppy_quorum_hinted_handoff,
|
||||
),
|
||||
("CONCURRENT WRITES 1", test_concurrent_writes_1),
|
||||
("CONCURRENT WRITES 2", test_concurrent_writes_2),
|
||||
("CONCURRENT WRITES 3", test_concurrent_writes_3),
|
||||
("CONCURRENT WRITES 4", test_concurrent_writes_4),
|
||||
(
|
||||
"RANDOMIZED CONCURRENT WRITES",
|
||||
test_randomized_concurrent_writes,
|
||||
),
|
||||
("MC CONCURRENT WRITES", test_mc_concurrent_writes),
|
||||
("DIVERGED REPLICAS", test_diverged_replicas),
|
||||
(
|
||||
"DIVERGED REPLICAS WITH CLIENT CONTEXT",
|
||||
test_diverged_replicas_with_client_context,
|
||||
),
|
||||
("PARTITIONED CLIENTS", test_partitioned_clients),
|
||||
("SHOPPING CART 1", test_shopping_cart_1),
|
||||
("SHOPPING CART 2", test_shopping_cart_2),
|
||||
("MC CONCURRENT CART", test_mc_concurrent_cart),
|
||||
("SHOPPING XCART 1", test_shopping_xcart_1),
|
||||
("SHOPPING XCART 2", test_shopping_xcart_2),
|
||||
("MC CONCURRENT XCART", test_mc_concurrent_xcart),
|
||||
("SEQUENTIAL CONTEXT GROWTH", test_sequential_context_growth),
|
||||
];
|
||||
|
||||
macro_rules! string_set {
|
||||
($($x:expr),+ $(,)?) => (
|
||||
HashSet::from([$($x.to_string()),+])
|
||||
);
|
||||
}
|
||||
|
||||
fn score(results: IndexMap<String, TestResult>) -> f32 {
|
||||
let basic_group = string_set! {
|
||||
"BASIC", "MC EMPTY SYSTEM", "MC BASIC", "STALE REPLICA", "SLOPPY QUORUM", "MC SLOPPY QUORUM HINTED HANDOFF"
|
||||
};
|
||||
let forwarding_group = string_set! {"PUT FORWARDING"};
|
||||
let concurrent_writes_group = string_set! {
|
||||
"CONCURRENT WRITES 1", "CONCURRENT WRITES 2", "CONCURRENT WRITES 3", "CONCURRENT WRITES 4", "RANDOMIZED CONCURRENT WRITES", "MC CONCURRENT WRITES"
|
||||
};
|
||||
let diverged_replicas_group =
|
||||
string_set! {"DIVERGED REPLICAS", "DIVERGED REPLICAS WITH CLIENT CONTEXT"};
|
||||
let partitioned_clients_group = string_set! {"PARTITIONED CLIENTS"};
|
||||
let shopping_cart_group = string_set! {
|
||||
"SHOPPING CART 1", "SHOPPING CART 2", "MC CONCURRENT CART"
|
||||
};
|
||||
let shopping_xcart_group = string_set! {
|
||||
"SHOPPING XCART 1", "SHOPPING XCART 2", "MC CONCURRENT XCART"
|
||||
};
|
||||
let efficiency_group = string_set! {"SEQUENTIAL CONTEXT GROWTH"};
|
||||
let groups = [
|
||||
("BASIC tests", &basic_group, 2.),
|
||||
("PUT FORWARDING test", &forwarding_group, 1.),
|
||||
("CONCURRENT WRITES tests", &concurrent_writes_group, 1.),
|
||||
("DIVERGED REPLICAS tests", &diverged_replicas_group, 1.),
|
||||
("PARTITIONED CLIENTS test", &partitioned_clients_group, 1.),
|
||||
("SHOPPING CART tests", &shopping_cart_group, 1.),
|
||||
("SHOPPING XCART tests", &shopping_xcart_group, 2.),
|
||||
("EFFICIENCY tests", &efficiency_group, 1.),
|
||||
];
|
||||
let all_groups: HashSet<_> = groups
|
||||
.iter()
|
||||
.flat_map(|(_, group, _)| group.iter().cloned())
|
||||
.collect();
|
||||
|
||||
assert_eq!(all_groups, results.keys().cloned().collect());
|
||||
|
||||
let mut passed = HashSet::new();
|
||||
for (test, result) in results {
|
||||
if result.is_ok() {
|
||||
passed.insert(test);
|
||||
}
|
||||
}
|
||||
|
||||
let mut score = 0.;
|
||||
for (label, group, points) in groups {
|
||||
print!("{label}: ");
|
||||
if group.is_subset(&passed) {
|
||||
score += points;
|
||||
println!("passed");
|
||||
} else {
|
||||
println!("not passed {:?}", group.difference(&passed));
|
||||
}
|
||||
}
|
||||
if basic_group.is_subset(&passed) {
|
||||
score
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use std::ffi::CString;
|
||||
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
|
||||
use std::path::Path;
|
||||
|
||||
use anysystem::python::PyProcessFactory;
|
||||
use anysystem::test::TestResult;
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::{PyList, PyModule};
|
||||
|
||||
use crate::common::TestConfig;
|
||||
|
||||
// AnySystem 0.3 prints the Python traceback and then unwraps the same error.
|
||||
// Suppress this duplicate diagnostic only at those bridge sites.
|
||||
pub fn install_panic_hook() {
|
||||
let default = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let site = info
|
||||
.location()
|
||||
.map(|l| l.file().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let message = info.payload_as_str().unwrap_or("");
|
||||
let python = site.ends_with("/anysystem-0.3.0/src/python/mod.rs")
|
||||
&& (message.contains("PyErr {")
|
||||
|| message.contains("Error when creating Python process"));
|
||||
let callback = (site.ends_with("/anysystem-0.3.0/src/node.rs")
|
||||
|| site.ends_with("/anysystem-0.3.0/src/mc/node.rs"))
|
||||
&& message.contains("Error when calling process");
|
||||
if !python && !callback {
|
||||
default(info);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
pub struct Solution {
|
||||
factory: PyProcessFactory,
|
||||
errors: Py<PyList>,
|
||||
}
|
||||
|
||||
impl Solution {
|
||||
pub fn load(path: &str) -> Result<Self, String> {
|
||||
let path = Path::new(path).canonicalize().map_err(|e| e.to_string())?;
|
||||
let path = path.to_str().ok_or("Solution path is not UTF-8")?;
|
||||
// AnySystem unwraps Python errors during import. Preserve unrelated loader panics.
|
||||
let factory = catch_unwind(|| PyProcessFactory::new(path, "StorageNode"))
|
||||
.map_err(|panic| format!("Cannot load StorageNode: {}", python_panic(panic)))?;
|
||||
let errors = Python::attach(|py| -> PyResult<_> {
|
||||
// AnySystem 0.3 registers the solution under its canonical filename without ".py".
|
||||
let modules = PyModule::import(py, "sys")?.getattr("modules")?;
|
||||
let class = modules
|
||||
.get_item(path.replace(".py", ""))?
|
||||
.getattr("StorageNode")?;
|
||||
let code = CString::new(include_str!("../python_errors.py")).unwrap();
|
||||
let adapter =
|
||||
PyModule::from_code(py, &code, c"python_errors.py", c"hw9_python_errors")?;
|
||||
Ok(adapter
|
||||
.getattr("watch")?
|
||||
.call1((class,))?
|
||||
.extract::<Py<PyList>>()?)
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(Self { factory, errors })
|
||||
}
|
||||
}
|
||||
|
||||
fn python_panic(panic: Box<dyn std::any::Any + Send>) -> String {
|
||||
if let Some(message) = panic.downcast_ref::<String>() {
|
||||
if let Some(start) = message.find("PyErr {") {
|
||||
return message[start..].to_string();
|
||||
}
|
||||
}
|
||||
resume_unwind(panic)
|
||||
}
|
||||
|
||||
pub type Case = fn(&TestConfig) -> TestResult;
|
||||
|
||||
pub struct CaseConfig<'a> {
|
||||
pub solution: &'a Result<Solution, String>,
|
||||
pub proc_count: u32,
|
||||
pub seed: u64,
|
||||
}
|
||||
|
||||
pub fn run_case((config, test): &(&CaseConfig, Case)) -> TestResult {
|
||||
let solution = config.solution.as_ref().map_err(Clone::clone)?;
|
||||
let config = TestConfig {
|
||||
proc_factory: &solution.factory,
|
||||
proc_count: config.proc_count,
|
||||
seed: config.seed,
|
||||
};
|
||||
// Each case owns its simulator. Unwinding drops all nodes from the failed case.
|
||||
match catch_unwind(AssertUnwindSafe(|| test(&config))) {
|
||||
Ok(result) => result,
|
||||
Err(panic) => {
|
||||
let error = Python::attach(|py| {
|
||||
solution
|
||||
.errors
|
||||
.bind(py)
|
||||
.call_method0("pop")
|
||||
.and_then(|item| item.extract::<String>())
|
||||
.ok()
|
||||
});
|
||||
match error {
|
||||
Some(error) => Err(format!("Python exception in {error}")),
|
||||
// PyO3 can also report Python errors outside a callback, for example in deepcopy.
|
||||
None => Err(format!("Python exception: {}", python_panic(panic))),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Set Python's hash seed before the interpreter (including the validator) starts.
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
|
||||
pub fn configure(seed: u64) {
|
||||
// Python accepts only 32-bit hash seeds; the simulator keeps the full u64 seed.
|
||||
let hash_seed = (seed as u32).to_string();
|
||||
if env::var("PYTHONHASHSEED").as_deref() == Ok(hash_seed.as_str()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Restart with an inherited environment instead of changing it at runtime:
|
||||
// on Windows, Rust and CPython can use different copies of the environment.
|
||||
let mut command = Command::new(env::current_exe().expect("cannot locate test executable"));
|
||||
command
|
||||
.args(env::args_os().skip(1))
|
||||
.env("PYTHONHASHSEED", hash_seed);
|
||||
|
||||
// Preserve the PID so timeout/signals still reach the test process directly.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
let error = command.exec();
|
||||
panic!("cannot restart tests with PYTHONHASHSEED: {error}");
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let status = command
|
||||
.status()
|
||||
.expect("cannot restart tests with PYTHONHASHSEED");
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use std::ffi::CString;
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::{PyList, PyModule};
|
||||
|
||||
const VALIDATOR_CODE: &str = include_str!("../shared_state_validator.py");
|
||||
|
||||
fn validator_module<'py>(py: Python<'py>) -> PyResult<Bound<'py, PyModule>> {
|
||||
let code = CString::new(VALIDATOR_CODE).expect("validator source contains a null byte");
|
||||
PyModule::from_code(
|
||||
py,
|
||||
&code,
|
||||
c"shared_state_validator.py",
|
||||
c"shared_state_validator",
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_solution(path: &str, class_names: &[&str]) -> Result<Vec<String>, String> {
|
||||
Python::attach(|py| {
|
||||
let module = validator_module(py).map_err(|error| error.to_string())?;
|
||||
let class_names = PyList::new(py, class_names).map_err(|error| error.to_string())?;
|
||||
module
|
||||
.getattr("validate_solution")
|
||||
.and_then(|function| function.call1((path, class_names)))
|
||||
.and_then(|result| result.extract::<Vec<String>>())
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate_or_report(path: &str, class_names: &[&str]) -> Result<bool, String> {
|
||||
let violations = validate_solution(path, class_names)?;
|
||||
if violations.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
println!("ERROR: shared state between AnySystem processes is forbidden");
|
||||
for violation in violations {
|
||||
println!("{violation}");
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
@@ -0,0 +1,990 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use assertables::{assume, assume_eq};
|
||||
use rand::prelude::*;
|
||||
use rand_pcg::Pcg64;
|
||||
|
||||
use anysystem::logger::LogEntry;
|
||||
use anysystem::test::TestResult;
|
||||
use anysystem::{Message, System};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
pub fn test_basic(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let procs = sys.process_names();
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
println!("Key {key} replicas: {replicas:?}");
|
||||
|
||||
// get key from the first node
|
||||
check_get(&mut sys, &procs[0], &key, 2, Some(vec![]), 100)?;
|
||||
|
||||
// put key from the first replica (clock skew is 1)
|
||||
sys.set_node_clock_skew(&replicas[0], 1.);
|
||||
let value = random_string(8, &mut rand);
|
||||
let (values, _) = check_put(&mut sys, &replicas[0], &key, &value, None, 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
assume_eq!(values[0], value)?;
|
||||
|
||||
// get key from the last replica
|
||||
check_get(&mut sys, &replicas[2], &key, 2, Some(vec![&value]), 100)?;
|
||||
|
||||
// get key from the first non-replica
|
||||
check_get(&mut sys, &non_replicas[0], &key, 2, Some(vec![&value]), 100)?;
|
||||
|
||||
// update key from the last non-replica
|
||||
// (node clocks are adjusted to break LWW-based implementations)
|
||||
let (_, ctx) = check_get(&mut sys, &non_replicas[2], &key, 2, Some(vec![&value]), 100)?;
|
||||
let value2 = random_string(8, &mut rand);
|
||||
let skew = -sys.time() + 0.5;
|
||||
sys.set_node_clock_skew(&non_replicas[2], skew);
|
||||
sys.set_node_clock_skew(&replicas[0], skew);
|
||||
sys.set_node_clock_skew(&replicas[1], skew);
|
||||
sys.set_node_clock_skew(&replicas[2], skew);
|
||||
let (values, _) = check_put(&mut sys, &non_replicas[2], &key, &value2, ctx, 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
assume_eq!(values[0], value2)?;
|
||||
|
||||
// get key from the first node
|
||||
check_get(&mut sys, &procs[0], &key, 2, Some(vec![&value2]), 100)?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_sequential_context_growth(config: &TestConfig) -> TestResult {
|
||||
let (short_put, short_get) = sequential_context_sizes(config, 16)?;
|
||||
let (long_put, long_get) = sequential_context_sizes(config, 128)?;
|
||||
// Allow counter and encoding overhead while looking for an accumulating history.
|
||||
for (response, short, long) in [
|
||||
("PUT_RESP", short_put, long_put),
|
||||
("GET_RESP", short_get, long_get),
|
||||
] {
|
||||
if long > short + 64 {
|
||||
return Err(format!(
|
||||
"{response} context grew from {short} to {long} bytes; allowed growth is 64 bytes"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn sequential_context_sizes(config: &TestConfig, writes: u32) -> Result<(usize, usize), String> {
|
||||
const EARLY_GROWTH_LIMIT: usize = 4 * 1024;
|
||||
|
||||
let mut sys = build_system(config);
|
||||
let key = format!("KEY-{}", config.seed);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let mut context = None;
|
||||
let mut first_put_bytes = None;
|
||||
for step in 1..=writes {
|
||||
let value = format!("v{step:03}");
|
||||
let (values, next) = check_put(&mut sys, &replicas[0], &key, &value, context, 3, 100)?;
|
||||
assume_eq!(values, [value.as_str()])?;
|
||||
assume!(!next.is_empty(), "Missing PUT_RESP context")?;
|
||||
|
||||
// Check before feeding a rapidly growing context back into the simulator.
|
||||
let bytes = next.len();
|
||||
let first = *first_put_bytes.get_or_insert(bytes);
|
||||
if bytes > first + EARLY_GROWTH_LIMIT {
|
||||
return Err(format!(
|
||||
"PUT_RESP context grew from {first} bytes at write 1 to {bytes} bytes at write {step}; early growth limit is {EARLY_GROWTH_LIMIT} bytes"
|
||||
));
|
||||
}
|
||||
context = Some(next);
|
||||
}
|
||||
let put_bytes = context.ok_or("No PUT_RESP context")?.len();
|
||||
let (values, context) = check_get(&mut sys, &replicas[1], &key, 3, None, 100)?;
|
||||
assume_eq!(values, [format!("v{writes:03}")])?;
|
||||
let get_bytes = context
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or("Missing GET_RESP context")?
|
||||
.len();
|
||||
println!(
|
||||
"{writes} writes: PUT_RESP context {put_bytes} bytes, GET_RESP context {get_bytes} bytes"
|
||||
);
|
||||
Ok((put_bytes, get_bytes))
|
||||
}
|
||||
|
||||
pub fn test_put_forwarding(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
// Deliver messages immediately so a healthy coordinator can reply before a retry.
|
||||
sys.network().set_delay(0.);
|
||||
let key = format!("KEY-{}", config.seed);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let ingress = non_replicas
|
||||
.first()
|
||||
.ok_or("PUT forwarding needs a non-replica")?;
|
||||
println!("PUT({key}) via {ingress}, replicas: {replicas:?}");
|
||||
|
||||
let (values, _) = check_put(&mut sys, ingress, &key, "value", None, 2, 100)?;
|
||||
assume_eq!(values, ["value"])?;
|
||||
|
||||
let mut coordinator = None;
|
||||
let mut delivered = false;
|
||||
for event in sys.logger().trace() {
|
||||
match event {
|
||||
LogEntry::MessageSent {
|
||||
src_proc, dst_proc, ..
|
||||
} if src_proc == ingress && dst_proc != ingress => {
|
||||
if !replicas.contains(dst_proc) {
|
||||
return Err(format!(
|
||||
"Node {ingress} forwarded PUT to non-replica {dst_proc}"
|
||||
));
|
||||
}
|
||||
if let Some(first) = coordinator {
|
||||
if first != dst_proc {
|
||||
return Err(format!(
|
||||
"Node {ingress} forwarded PUT to both {first} and {dst_proc}"
|
||||
));
|
||||
}
|
||||
}
|
||||
coordinator = Some(dst_proc);
|
||||
}
|
||||
LogEntry::MessageReceived {
|
||||
src_proc, dst_proc, ..
|
||||
} if src_proc == ingress && Some(dst_proc) == coordinator => {
|
||||
delivered = true;
|
||||
}
|
||||
LogEntry::LocalMessageSent { proc, .. } if proc == ingress => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assume!(
|
||||
delivered,
|
||||
"No replica received the forwarded PUT before PUT_RESP"
|
||||
)?;
|
||||
check_get(&mut sys, &replicas[0], &key, 2, Some(vec!["value"]), 100)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_stale_replica(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
|
||||
// put key from the first non-replica with quorum 3
|
||||
let value = random_string(8, &mut rand);
|
||||
set_writer_clocks(&mut sys, &non_replicas[0], &replicas, 100.0);
|
||||
check_put(&mut sys, &non_replicas[0], &key, &value, None, 3, 100)?;
|
||||
|
||||
// disconnect the first replica
|
||||
sys.network().disconnect_node(&replicas[0]);
|
||||
|
||||
// update key from the last replica with quorum 2
|
||||
let (_, ctx) = check_get(&mut sys, &replicas[2], &key, 2, Some(vec![&value]), 100)?;
|
||||
let value2 = format!("{value}-updated");
|
||||
// The causally newer write gets an earlier timestamp, even after a coordinator retry.
|
||||
set_writer_clocks(&mut sys, &replicas[2], &replicas, 0.5);
|
||||
check_put(&mut sys, &replicas[2], &key, &value2, ctx, 2, 100)?;
|
||||
|
||||
// disconnect the last replica
|
||||
sys.network().disconnect_node(&replicas[2]);
|
||||
// connect the first replica
|
||||
sys.network().connect_node(&replicas[0]);
|
||||
|
||||
// read key from the second replica with quorum 2
|
||||
check_get(&mut sys, &replicas[1], &key, 2, Some(vec![&value2]), 100)?;
|
||||
|
||||
// step for a while and check whether the first replica got the recent value
|
||||
sys.steps(100);
|
||||
sys.network().disconnect_node(&replicas[0]);
|
||||
check_get(&mut sys, &replicas[0], &key, 1, Some(vec![&value2]), 100)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[allow(clippy::get_first)]
|
||||
pub fn test_concurrent_writes_1(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let proc_1 = &non_replicas.get(0).unwrap();
|
||||
let proc_2 = &non_replicas.get(1).unwrap();
|
||||
let proc_3 = &non_replicas.get(2).unwrap();
|
||||
|
||||
// put key from proc_1 (quorum=2)
|
||||
let value1 = random_string(8, &mut rand);
|
||||
let (values, _) = check_put(&mut sys, proc_1, &key, &value1, None, 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
assume_eq!(values[0], value1)?;
|
||||
|
||||
// concurrently (using same context) put key from proc_2 (quorum=2)
|
||||
let value2 = random_string(8, &mut rand);
|
||||
let (values, _) = check_put(&mut sys, proc_2, &key, &value2, None, 2, 100)?;
|
||||
assume_eq!(values.len(), 2, "Expected two values")?;
|
||||
|
||||
// read key from proc_3 (quorum=2)
|
||||
// should return both values for reconciliation by the client
|
||||
check_get(&mut sys, proc_3, &key, 2, Some(vec![&value1, &value2]), 100)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[allow(clippy::get_first)]
|
||||
pub fn test_concurrent_writes_2(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let proc_1 = &non_replicas.get(0).unwrap();
|
||||
let proc_2 = &non_replicas.get(1).unwrap();
|
||||
let proc_3 = &non_replicas.get(2).unwrap();
|
||||
|
||||
// put key from proc_1 (quorum=2)
|
||||
let value1 = random_string(8, &mut rand);
|
||||
send_put(&mut sys, proc_1, &key, &value1, 2, None);
|
||||
|
||||
// concurrently (using same context) put key from proc_2 (quorum=2)
|
||||
let value2 = random_string(8, &mut rand);
|
||||
send_put(&mut sys, proc_2, &key, &value2, 2, None);
|
||||
|
||||
// wait until both puts are processed
|
||||
check_put_result(&mut sys, proc_1, &key, 100)?;
|
||||
check_put_result(&mut sys, proc_2, &key, 100)?;
|
||||
|
||||
// read key from proc_3 (quorum=2)
|
||||
// should return both values for reconciliation by the client
|
||||
let (_, ctx) = check_get(&mut sys, proc_3, &key, 2, Some(vec![&value1, &value2]), 100)?;
|
||||
// put new reconciled value using the obtained context
|
||||
let value3 = [value1, value2].join("+");
|
||||
check_put(&mut sys, proc_3, &key, &value3, ctx, 2, 100)?;
|
||||
|
||||
// read key from proc_1 (quorum=2)
|
||||
check_get(&mut sys, proc_1, &key, 2, Some(vec![&value3]), 100)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_concurrent_writes_3(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
|
||||
// put key from the first replica (quorum=1)
|
||||
let value1 = random_string(8, &mut rand);
|
||||
check_put(&mut sys, &replicas[0], &key, &value1, None, 1, 100)?;
|
||||
|
||||
// concurrently put key from the second replica (quorum=1)
|
||||
let value2 = random_string(8, &mut rand);
|
||||
check_put(&mut sys, &replicas[1], &key, &value2, None, 1, 100)?;
|
||||
|
||||
// read key from the first non-replica (quorum=3)
|
||||
check_get(
|
||||
&mut sys,
|
||||
&non_replicas[0],
|
||||
&key,
|
||||
3,
|
||||
Some(vec![&value1, &value2]),
|
||||
100,
|
||||
)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_concurrent_writes_4(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let key = format!("KEY-{}", config.seed);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let node = &replicas[0];
|
||||
check_put(&mut sys, node, &key, "base", None, 3, 100)?;
|
||||
|
||||
// Both clients read the same version before either writes through this replica.
|
||||
let (_, first_ctx) = check_get(&mut sys, node, &key, 2, Some(vec!["base"]), 100)?;
|
||||
let (_, second_ctx) = check_get(&mut sys, node, &key, 2, Some(vec!["base"]), 100)?;
|
||||
assume!(
|
||||
first_ctx.as_deref().is_some_and(|ctx| !ctx.is_empty())
|
||||
&& second_ctx.as_deref().is_some_and(|ctx| !ctx.is_empty()),
|
||||
"Both GET responses must include a non-empty context"
|
||||
)?;
|
||||
|
||||
// Replay one opaque context so the second PUT uses exactly the same token.
|
||||
let (values, ctx_a) = check_put(&mut sys, node, &key, "A", first_ctx.clone(), 2, 100)?;
|
||||
assume_eq!(values, ["A"])?;
|
||||
let (mut values, _) = check_put(&mut sys, node, &key, "B", first_ctx, 2, 100)?;
|
||||
values.sort_unstable();
|
||||
assume_eq!(
|
||||
values,
|
||||
["A", "B"],
|
||||
"Expected both values in the second PUT_RESP"
|
||||
)?;
|
||||
// A2 replaces only A: the first client has never seen B.
|
||||
let (mut values, _) = check_put(&mut sys, node, &key, "A2", Some(ctx_a), 2, 100)?;
|
||||
values.sort_unstable();
|
||||
assume_eq!(values, ["A2", "B"]).map_err(|err| format!("A2 PUT_RESP: {err}"))?;
|
||||
let (mut values, _) = check_get(&mut sys, &replicas[1], &key, 3, None, 100)?;
|
||||
values.sort_unstable();
|
||||
assume_eq!(values, ["A2", "B"]).map_err(|err| format!("GET after A2: {err}"))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_randomized_concurrent_writes(config: &TestConfig) -> TestResult {
|
||||
struct KeyHistory {
|
||||
key: String,
|
||||
live: Vec<String>,
|
||||
// Each GET token is paired with the versions visible at that read.
|
||||
reads: Vec<(String, Vec<String>)>,
|
||||
}
|
||||
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
let mut nodes = sys.process_names();
|
||||
nodes.sort();
|
||||
let mut keys = vec![random_key(&mut rand)];
|
||||
let replicas = key_replicas(&keys[0], &sys);
|
||||
// Shared replicas make accidental overwrites between keys observable.
|
||||
while keys.len() < 3 {
|
||||
let key = random_key(&mut rand);
|
||||
if !keys.contains(&key) && key_replicas(&key, &sys) == replicas {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
let mut histories: Vec<_> = keys
|
||||
.into_iter()
|
||||
.map(|key| KeyHistory {
|
||||
key,
|
||||
live: Vec::new(),
|
||||
reads: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
println!("Random seed: {}", config.seed);
|
||||
for round in 0..7 {
|
||||
histories.shuffle(&mut rand);
|
||||
for history in &mut histories {
|
||||
// Fork twice from the first read, sample historical contexts, then reconcile.
|
||||
let read = match round {
|
||||
0 => None,
|
||||
1 | 2 => Some(0),
|
||||
6 => Some(history.reads.len() - 1),
|
||||
_ => Some(rand.gen_range(0..history.reads.len())),
|
||||
};
|
||||
let context = read.map(|i| {
|
||||
let (token, seen) = &history.reads[i];
|
||||
history.live.retain(|version| !seen.contains(version));
|
||||
token.clone()
|
||||
});
|
||||
let value = format!("{}-{round}", history.key);
|
||||
history.live.push(value.clone());
|
||||
history.live.sort_unstable();
|
||||
|
||||
let node = nodes.choose(&mut rand).unwrap();
|
||||
let step = format!(
|
||||
"round {round}, PUT {} via {node}, context from round {read:?}",
|
||||
history.key
|
||||
);
|
||||
let (mut values, _) = check_put(&mut sys, node, &history.key, &value, context, 3, 100)
|
||||
.map_err(|err| format!("{step}: {err}"))?;
|
||||
values.sort_unstable();
|
||||
assume_eq!(values, history.live).map_err(|err| format!("{step}: {err}"))?;
|
||||
}
|
||||
|
||||
// All three keys have been written before any is read back. A full quorum
|
||||
// in a healthy network sees every acknowledged write, regardless of ingress.
|
||||
for history in &mut histories {
|
||||
let node = nodes.choose(&mut rand).unwrap();
|
||||
let step = format!("round {round}, GET {} via {node}", history.key);
|
||||
let (mut values, context) = check_get(&mut sys, node, &history.key, 3, None, 100)
|
||||
.map_err(|err| format!("{step}: {err}"))?;
|
||||
values.sort_unstable();
|
||||
assume_eq!(values, history.live).map_err(|err| format!("{step}: {err}"))?;
|
||||
let token = context
|
||||
.filter(|ctx| !ctx.is_empty())
|
||||
.ok_or_else(|| format!("{step}: missing context"))?;
|
||||
history.reads.push((token, history.live.clone()));
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_diverged_replicas(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
|
||||
// put key from the first replica with quorum 3
|
||||
let value = random_string(8, &mut rand);
|
||||
check_put(&mut sys, &replicas[0], &key, &value, None, 3, 100)?;
|
||||
|
||||
// disconnect each replica and put value from it
|
||||
let mut new_values = Vec::new();
|
||||
for replica in replicas.iter() {
|
||||
sys.network().disconnect_node(replica);
|
||||
}
|
||||
for replica in replicas.iter() {
|
||||
let (_, ctx) = check_get(&mut sys, replica, &key, 1, Some(vec![&value]), 100)?;
|
||||
let value2 = random_string(8, &mut rand);
|
||||
check_put(&mut sys, replica, &key, &value2, ctx, 1, 100)?;
|
||||
new_values.push(value2);
|
||||
// read some key to advance the time
|
||||
// (make sure that the isolated replicas are not among this key's replicas)
|
||||
loop {
|
||||
let some_key = random_key(&mut rand);
|
||||
let some_key_replicas = key_replicas(&some_key, &sys);
|
||||
if replicas
|
||||
.iter()
|
||||
.all(|proc| !some_key_replicas.contains(proc))
|
||||
{
|
||||
check_get(&mut sys, &non_replicas[0], &some_key, 3, Some(vec![]), 100)?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reconnect the replicas
|
||||
for replica in replicas.iter() {
|
||||
sys.network().connect_node(replica);
|
||||
}
|
||||
|
||||
// read key from the first replica with quorum 3
|
||||
// should return all three conflicting values
|
||||
let expected = new_values.iter().map(String::as_str).collect();
|
||||
check_get(&mut sys, &replicas[0], &key, 3, Some(expected), 100)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_diverged_replicas_with_client_context(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let key = format!("KEY-{}", config.seed);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let first = &replicas[0];
|
||||
let isolated = &replicas[1];
|
||||
sys.network().disconnect_node(isolated);
|
||||
|
||||
check_put(&mut sys, first, &key, "A", None, 2, 100)?;
|
||||
let (_, context) = check_get(&mut sys, first, &key, 2, Some(vec!["A"]), 100)?;
|
||||
let context = context
|
||||
.filter(|ctx| !ctx.is_empty())
|
||||
.ok_or("GET of A must return a non-empty context")?;
|
||||
|
||||
// Only the client's context can tell the isolated replica that B replaces A.
|
||||
check_get(&mut sys, isolated, &key, 1, Some(vec![]), 100)?;
|
||||
check_put(&mut sys, isolated, &key, "B", Some(context), 1, 100)?;
|
||||
|
||||
sys.network().connect_node(isolated);
|
||||
let (values, _) = check_get(&mut sys, first, &key, 3, None, 100)?;
|
||||
assume_eq!(values, ["B"]).map_err(|err| format!("GET after reconnecting replicas: {err}"))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_sloppy_quorum(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
|
||||
// put key from the first non-replica with quorum 3
|
||||
let value = random_string(8, &mut rand);
|
||||
set_writer_clocks(&mut sys, &non_replicas[0], &replicas, 100.0);
|
||||
check_put(&mut sys, &non_replicas[0], &key, &value, None, 3, 100)?;
|
||||
|
||||
// temporarily disconnect the first replica
|
||||
sys.network().disconnect_node(&replicas[0]);
|
||||
|
||||
// update key from the second non-replica with quorum 3 (should use sloppy quorum)
|
||||
let (_, ctx) = check_get(&mut sys, &non_replicas[1], &key, 1, Some(vec![&value]), 100)?;
|
||||
let value2 = format!("{value}-updated");
|
||||
// The causally newer write gets an earlier timestamp, even after a coordinator retry.
|
||||
set_writer_clocks(&mut sys, &non_replicas[1], &replicas, 0.5);
|
||||
check_put(&mut sys, &non_replicas[1], &key, &value2, ctx, 3, 100)?;
|
||||
|
||||
// read key from the last non-replica with quorum 3 (should use sloppy quorum)
|
||||
check_get(
|
||||
&mut sys,
|
||||
&non_replicas[2],
|
||||
&key,
|
||||
3,
|
||||
Some(vec![&value2]),
|
||||
100,
|
||||
)?;
|
||||
|
||||
// reconnect the first replica and let it receive the update
|
||||
sys.network().connect_node(&replicas[0]);
|
||||
sys.steps(100);
|
||||
|
||||
// check if the first replica got update
|
||||
sys.network().disconnect_node(&replicas[0]);
|
||||
check_get(&mut sys, &replicas[0], &key, 1, Some(vec![&value2]), 100)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_partitioned_clients(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let procs = sys.process_names();
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let replica1 = &replicas[0];
|
||||
let replica2 = &replicas[1];
|
||||
let replica3 = &replicas[2];
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let non_replica1 = &non_replicas[0];
|
||||
let non_replica2 = &non_replicas[1];
|
||||
let non_replica3 = &non_replicas[2];
|
||||
|
||||
// put key from the first node with quorum 3
|
||||
let value = random_string(8, &mut rand);
|
||||
check_put(&mut sys, &procs[0], &key, &value, None, 3, 100)?;
|
||||
|
||||
// partition network into two parts
|
||||
let part1: Vec<&str> = vec![non_replica1, non_replica2, replica1];
|
||||
let part2: Vec<&str> = vec![non_replica3, replica2, replica3];
|
||||
sys.network().make_partition(&part1, &part2);
|
||||
|
||||
// partition 1
|
||||
let (values, ctx) = check_get(&mut sys, non_replica1, &key, 2, Some(vec![&value]), 100)?;
|
||||
let mut value2 = format!("{}-1", values[0]);
|
||||
check_put(&mut sys, non_replica1, &key, &value2, ctx, 2, 100)?;
|
||||
let (values, ctx) = check_get(&mut sys, non_replica2, &key, 2, Some(vec![&value2]), 100)?;
|
||||
value2 = format!("{}-2", values[0]);
|
||||
check_put(&mut sys, non_replica2, &key, &value2, ctx, 2, 100)?;
|
||||
check_get(&mut sys, non_replica2, &key, 2, Some(vec![&value2]), 100)?;
|
||||
|
||||
// partition 2
|
||||
let (values, ctx) = check_get(&mut sys, non_replica3, &key, 2, Some(vec![&value]), 100)?;
|
||||
let value3 = format!("{}-3", values[0]);
|
||||
check_put(&mut sys, non_replica3, &key, &value3, ctx, 2, 100)?;
|
||||
check_get(&mut sys, non_replica3, &key, 2, Some(vec![&value3]), 100)?;
|
||||
|
||||
// heal partition
|
||||
sys.network().reset();
|
||||
sys.steps(100);
|
||||
|
||||
// read key from all non-replicas
|
||||
// (should return value2 and value3)
|
||||
let expected: Option<Vec<&str>> = Some(vec![&value2, &value3]);
|
||||
check_get(&mut sys, non_replica1, &key, 2, expected.clone(), 100)?;
|
||||
check_get(&mut sys, non_replica2, &key, 2, expected.clone(), 100)?;
|
||||
check_get(&mut sys, non_replica3, &key, 2, expected.clone(), 100)?;
|
||||
|
||||
// check all replicas
|
||||
for replica in replicas.iter() {
|
||||
sys.network().disconnect_node(replica);
|
||||
check_get(&mut sys, replica, &key, 1, expected.clone(), 100)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_shopping_cart_1(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = format!("cart-{}", random_string(8, &mut rand)).to_uppercase();
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let proc_1 = &non_replicas[0];
|
||||
let proc_2 = &non_replicas[1];
|
||||
|
||||
// proc_1: put [milk]
|
||||
let mut cart1 = vec!["milk"];
|
||||
let (values, ctx1) = check_put(&mut sys, proc_1, &key, &cart1.join(","), None, 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
cart1 = values[0].split(',').collect();
|
||||
|
||||
// proc_1: put [flour]
|
||||
cart1.push("flour");
|
||||
let (values, ctx1) = check_put(&mut sys, proc_1, &key, &cart1.join(","), Some(ctx1), 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
cart1 = values[0].split(',').collect();
|
||||
|
||||
// Client 2 has seen neither write from client 1. Its eggs must survive the merge.
|
||||
let mut cart2 = vec!["eggs"];
|
||||
let (values, ctx2) = check_put(&mut sys, proc_2, &key, &cart2.join(","), None, 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
cart2 = values[0].split(',').collect();
|
||||
|
||||
// proc_2: put [ham]
|
||||
cart2.push("ham");
|
||||
let (values, _) = check_put(&mut sys, proc_2, &key, &cart2.join(","), Some(ctx2), 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
|
||||
// proc_1: put [bacon]
|
||||
cart1.push("bacon");
|
||||
let (values, _) = check_put(&mut sys, proc_1, &key, &cart1.join(","), Some(ctx1), 2, 100)?;
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
|
||||
// read cart from all non-replicas
|
||||
let expected: HashSet<_> = vec!["milk", "eggs", "flour", "ham", "bacon"]
|
||||
.into_iter()
|
||||
.collect();
|
||||
for proc in non_replicas.iter() {
|
||||
let (values, _) = check_get(&mut sys, proc, &key, 2, None, 100)?;
|
||||
check_cart_values(&values, &expected)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_shopping_cart_2(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = format!("cart-{}", random_string(8, &mut rand)).to_uppercase();
|
||||
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let replica1 = &replicas[0];
|
||||
let replica2 = &replicas[1];
|
||||
let replica3 = &replicas[2];
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let proc_1 = &non_replicas[0];
|
||||
let proc_2 = &non_replicas[1];
|
||||
let proc_3 = &non_replicas[2];
|
||||
|
||||
// proc_1: put [beer, snacks]
|
||||
let cart0 = vec!["beer", "snacks"];
|
||||
let (_, ctx) = check_put(&mut sys, proc_1, &key, &cart0.join(","), None, 3, 100)?;
|
||||
|
||||
// partition network into two parts
|
||||
let part1: Vec<&str> = vec![proc_1, proc_2, replica1];
|
||||
let part2: Vec<&str> = vec![proc_3, replica2, replica3];
|
||||
sys.network().make_partition(&part1, &part2);
|
||||
|
||||
// partition 1 -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// proc_1: put [milk]
|
||||
let mut cart1 = cart0.clone();
|
||||
cart1.push("milk");
|
||||
check_put(&mut sys, proc_1, &key, &cart1.join(","), Some(ctx), 2, 100)?;
|
||||
// proc_2: read, put [eggs]
|
||||
let (values, ctx) = check_get(&mut sys, proc_2, &key, 2, Some(vec![&cart1.join(",")]), 100)?;
|
||||
let mut cart2: Vec<_> = values[0].split(',').collect();
|
||||
cart2.push("eggs");
|
||||
check_put(&mut sys, proc_2, &key, &cart2.join(","), ctx, 2, 100)?;
|
||||
// control read
|
||||
check_get(&mut sys, proc_1, &key, 2, Some(vec![&cart2.join(",")]), 100)?;
|
||||
|
||||
// partition 2 -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// proc_3: read, remove [snacks, beer], put [cheese, wine]
|
||||
let (values, ctx) = check_get(&mut sys, proc_3, &key, 2, Some(vec![&cart0.join(",")]), 100)?;
|
||||
let mut cart3: Vec<_> = values[0].split(',').collect();
|
||||
cart3.clear();
|
||||
cart3.push("cheese");
|
||||
cart3.push("wine");
|
||||
check_put(&mut sys, proc_3, &key, &cart3.join(","), ctx, 2, 100)?;
|
||||
// control read
|
||||
check_get(
|
||||
&mut sys,
|
||||
replica2,
|
||||
&key,
|
||||
2,
|
||||
Some(vec![&cart3.join(",")]),
|
||||
100,
|
||||
)?;
|
||||
|
||||
// heal partition --------------------------------------------------------------------------------------------------
|
||||
sys.network().reset();
|
||||
sys.steps(100);
|
||||
|
||||
// read key from all non-replica nodes
|
||||
let expected: HashSet<_> = vec!["cheese", "wine", "milk", "eggs", "beer", "snacks"]
|
||||
.into_iter()
|
||||
.collect();
|
||||
for proc in non_replicas.iter() {
|
||||
let (values, _) = check_get(&mut sys, proc, &key, 2, None, 100)?;
|
||||
check_cart_values(&values, &expected)?;
|
||||
}
|
||||
|
||||
// check all replicas
|
||||
for replica in replicas.iter() {
|
||||
sys.network().disconnect_node(replica);
|
||||
let (values, _) = check_get(&mut sys, replica, &key, 1, None, 100)?;
|
||||
check_cart_values(&values, &expected)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_shopping_xcart_1(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = format!("xcart-{}", random_string(8, &mut rand)).to_uppercase();
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let replica1 = &replicas[0];
|
||||
let replica2 = &replicas[1];
|
||||
let replica3 = &replicas[2];
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let proc_1 = &non_replicas[0];
|
||||
let proc_2 = &non_replicas[1];
|
||||
let proc_3 = &non_replicas[2];
|
||||
|
||||
// proc_1: [beer, snacks]
|
||||
let cart0 = vec!["beer", "snacks"];
|
||||
let (_, ctx) = check_put(&mut sys, proc_1, &key, &cart0.join(","), None, 3, 100)?;
|
||||
|
||||
// partition network into two parts
|
||||
let part1: Vec<&str> = vec![proc_1, proc_2, replica1];
|
||||
let part2: Vec<&str> = vec![proc_3, replica2, replica3];
|
||||
sys.network().make_partition(&part1, &part2);
|
||||
|
||||
// partition 1 -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// proc_1: put [milk]
|
||||
let mut cart1 = cart0.clone();
|
||||
cart1.push("milk");
|
||||
check_put(&mut sys, proc_1, &key, &cart1.join(","), Some(ctx), 2, 100)?;
|
||||
// proc_2: read, put [eggs]
|
||||
let (values, ctx) = check_get(&mut sys, proc_2, &key, 2, Some(vec![&cart1.join(",")]), 100)?;
|
||||
let mut cart2: Vec<_> = values[0].split(',').collect();
|
||||
cart2.push("eggs");
|
||||
check_put(&mut sys, proc_2, &key, &cart2.join(","), ctx, 2, 100)?;
|
||||
// control read
|
||||
check_get(&mut sys, proc_1, &key, 2, Some(vec![&cart2.join(",")]), 100)?;
|
||||
|
||||
// partition 2 -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// proc_3: read, remove [snacks, beer], put [cheese, wine]
|
||||
let (values, ctx) = check_get(&mut sys, proc_3, &key, 2, Some(vec![&cart0.join(",")]), 100)?;
|
||||
let mut cart3: Vec<_> = values[0].split(',').collect();
|
||||
cart3.clear();
|
||||
cart3.push("cheese");
|
||||
cart3.push("wine");
|
||||
check_put(&mut sys, proc_3, &key, &cart3.join(","), ctx, 2, 100)?;
|
||||
// control read
|
||||
check_get(
|
||||
&mut sys,
|
||||
replica2,
|
||||
&key,
|
||||
2,
|
||||
Some(vec![&cart3.join(",")]),
|
||||
100,
|
||||
)?;
|
||||
|
||||
// heal partition --------------------------------------------------------------------------------------------------
|
||||
sys.network().reset();
|
||||
sys.steps(100);
|
||||
|
||||
// read key from all non-replica nodes
|
||||
let expected: HashSet<_> = vec!["cheese", "wine", "milk", "eggs"].into_iter().collect();
|
||||
for proc in non_replicas.iter() {
|
||||
let (values, _) = check_get(&mut sys, proc, &key, 2, None, 100)?;
|
||||
check_cart_values(&values, &expected)?;
|
||||
}
|
||||
|
||||
// check all replicas
|
||||
for replica in replicas.iter() {
|
||||
sys.network().disconnect_node(replica);
|
||||
let (values, _) = check_get(&mut sys, replica, &key, 1, None, 100)?;
|
||||
check_cart_values(&values, &expected)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_shopping_xcart_2(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = format!("xcart-{}", random_string(8, &mut rand)).to_uppercase();
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let replica1 = &replicas[0];
|
||||
let replica2 = &replicas[1];
|
||||
let replica3 = &replicas[2];
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
let proc_1 = &non_replicas[0];
|
||||
let proc_2 = &non_replicas[1];
|
||||
let proc_3 = &non_replicas[2];
|
||||
|
||||
// proc_1: put [lemonade, snacks, beer]
|
||||
let cart0 = vec!["lemonade", "snacks", "beer"];
|
||||
let (_, ctx) = check_put(&mut sys, proc_1, &key, &cart0.join(","), None, 3, 100)?;
|
||||
|
||||
// partition network into two parts
|
||||
let part1: Vec<&str> = vec![proc_1, proc_2, replica1];
|
||||
let part2: Vec<&str> = vec![proc_3, replica2, replica3];
|
||||
sys.network().make_partition(&part1, &part2);
|
||||
|
||||
// partition 1 -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// proc_1: remove [lemonade], put [milk]
|
||||
let mut cart1 = cart0.clone();
|
||||
cart1.remove(0);
|
||||
cart1.push("milk");
|
||||
check_put(&mut sys, proc_1, &key, &cart1.join(","), Some(ctx), 2, 100)?;
|
||||
// proc_2: read, put [eggs]
|
||||
let (values, ctx) = check_get(&mut sys, proc_2, &key, 2, Some(vec![&cart1.join(",")]), 100)?;
|
||||
let mut cart2: Vec<_> = values[0].split(',').collect();
|
||||
cart2.push("eggs");
|
||||
check_put(&mut sys, proc_2, &key, &cart2.join(","), ctx, 2, 100)?;
|
||||
// control read
|
||||
check_get(&mut sys, proc_1, &key, 2, Some(vec![&cart2.join(",")]), 100)?;
|
||||
|
||||
// partition 2 -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// proc_3: read, remove [snacks, beer], put [cheese, wine], put [snacks] (back)
|
||||
let (values, ctx) = check_get(&mut sys, proc_3, &key, 2, Some(vec![&cart0.join(",")]), 100)?;
|
||||
let mut cart3: Vec<_> = values[0].split(',').collect();
|
||||
cart3.clear();
|
||||
cart3.push("lemonade");
|
||||
cart3.push("cheese");
|
||||
cart3.push("wine");
|
||||
let (_, ctx) = check_put(&mut sys, proc_3, &key, &cart3.join(","), ctx, 2, 100)?;
|
||||
cart3.push("snacks");
|
||||
check_put(&mut sys, proc_3, &key, &cart3.join(","), Some(ctx), 2, 100)?;
|
||||
// control read
|
||||
check_get(
|
||||
&mut sys,
|
||||
replica2,
|
||||
&key,
|
||||
2,
|
||||
Some(vec![&cart3.join(",")]),
|
||||
100,
|
||||
)?;
|
||||
|
||||
// heal partition --------------------------------------------------------------------------------------------------
|
||||
sys.network().reset();
|
||||
sys.steps(100);
|
||||
|
||||
// read key from all non-replica nodes
|
||||
let expected: HashSet<_> = vec!["milk", "eggs", "wine", "snacks", "cheese"]
|
||||
.into_iter()
|
||||
.collect();
|
||||
for proc in non_replicas.iter() {
|
||||
let (values, _) = check_get(&mut sys, proc, &key, 2, None, 100)?;
|
||||
check_cart_values(&values, &expected)?;
|
||||
}
|
||||
|
||||
// check all replicas
|
||||
for replica in replicas.iter() {
|
||||
sys.network().disconnect_node(replica);
|
||||
let (values, _) = check_get(&mut sys, replica, &key, 1, None, 100)?;
|
||||
check_cart_values(&values, &expected)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// UTILS ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
// Either the entry node or a replica may timestamp a PUT in an LWW implementation.
|
||||
// Set their local clocks relative to the simulation time immediately before the PUT.
|
||||
fn set_writer_clocks(sys: &mut System, entry_node: &str, replicas: &[String], local_time: f64) {
|
||||
let skew = local_time - sys.time();
|
||||
sys.set_node_clock_skew(entry_node, skew);
|
||||
for replica in replicas {
|
||||
sys.set_node_clock_skew(replica, skew);
|
||||
}
|
||||
}
|
||||
|
||||
fn check_get(
|
||||
sys: &mut System,
|
||||
proc: &str,
|
||||
key: &str,
|
||||
quorum: u8,
|
||||
expected: Option<Vec<&str>>,
|
||||
max_steps: u32,
|
||||
) -> Result<(Vec<String>, Option<String>), String> {
|
||||
sys.send_local_message(proc, Message::json("GET", &GetReqMessage { key, quorum }));
|
||||
let msg = wait_for_response(sys, proc, "GET_RESP", max_steps)?;
|
||||
let data = GetRespMessage::parse(&msg, proc)?;
|
||||
assume_eq!(data.key, key)?;
|
||||
if let Some(expected) = expected {
|
||||
let mut values_set: HashSet<_> = data.values.iter().map(String::as_str).collect();
|
||||
let mut expected_set: HashSet<_> = expected.into_iter().collect();
|
||||
|
||||
if key.starts_with("CART") || key.starts_with("XCART") {
|
||||
assert!(
|
||||
expected_set.len() <= 1,
|
||||
"Expected cant contain more than 1 value"
|
||||
);
|
||||
values_set = values_set
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|s| s.split(',').collect())
|
||||
.unwrap_or_default();
|
||||
expected_set = expected_set
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|s| s.split(',').collect())
|
||||
.unwrap_or_default();
|
||||
}
|
||||
|
||||
assume_eq!(values_set, expected_set)?;
|
||||
}
|
||||
Ok((data.values, data.context))
|
||||
}
|
||||
|
||||
fn send_put(
|
||||
sys: &mut System,
|
||||
proc: &str,
|
||||
key: &str,
|
||||
value: &str,
|
||||
quorum: u8,
|
||||
context: Option<String>,
|
||||
) {
|
||||
sys.send_local_message(
|
||||
proc,
|
||||
Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key,
|
||||
value,
|
||||
quorum,
|
||||
context,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_for_response(
|
||||
sys: &mut System,
|
||||
proc: &str,
|
||||
tip: &str,
|
||||
max_steps: u32,
|
||||
) -> Result<Message, String> {
|
||||
let missing = || format!("{tip} is not returned by {proc}");
|
||||
let messages = sys
|
||||
.step_until_local_message_max_steps(proc, max_steps)
|
||||
.map_err(|_| missing())?;
|
||||
let msg = messages.into_iter().next().ok_or_else(missing)?;
|
||||
assume_eq!(msg.tip, tip)?;
|
||||
Ok(msg)
|
||||
}
|
||||
|
||||
fn check_put_result(
|
||||
sys: &mut System,
|
||||
proc: &str,
|
||||
key: &str,
|
||||
max_steps: u32,
|
||||
) -> Result<(Vec<String>, String), String> {
|
||||
let msg = wait_for_response(sys, proc, "PUT_RESP", max_steps)?;
|
||||
let data = PutRespMessage::parse(&msg, proc)?;
|
||||
assume_eq!(data.key, key)?;
|
||||
Ok((data.values, data.context))
|
||||
}
|
||||
|
||||
fn check_put(
|
||||
sys: &mut System,
|
||||
proc: &str,
|
||||
key: &str,
|
||||
value: &str,
|
||||
context: Option<String>,
|
||||
quorum: u8,
|
||||
max_steps: u32,
|
||||
) -> Result<(Vec<String>, String), String> {
|
||||
send_put(sys, proc, key, value, quorum, context);
|
||||
check_put_result(sys, proc, key, max_steps)
|
||||
}
|
||||
|
||||
fn check_cart_values(values: &[String], expected: &HashSet<&str>) -> TestResult {
|
||||
assume_eq!(values.len(), 1, "Expected single value")?;
|
||||
let items: Vec<&str> = values[0].split(',').collect();
|
||||
assume_eq!(
|
||||
items.len(),
|
||||
expected.len(),
|
||||
format!("Expected {} items in the cart", expected.len())
|
||||
)?;
|
||||
let items_set: HashSet<&str> = HashSet::from_iter(items);
|
||||
assume_eq!(items_set, *expected)
|
||||
}
|
||||
@@ -0,0 +1,748 @@
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use rand::prelude::*;
|
||||
use rand_pcg::Pcg64;
|
||||
|
||||
use anysystem::logger::LogEntry;
|
||||
use anysystem::mc::{
|
||||
predicates::{collects, goals, invariants, prunes},
|
||||
strategies::bfs::Bfs,
|
||||
EventOrderingMode, InvariantFn, McState, McStats, McSystem, ModelChecker, StrategyConfig,
|
||||
};
|
||||
use anysystem::test::TestResult;
|
||||
use anysystem::{Message, System};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
const MC_SEARCH_LIMIT: Duration = Duration::from_secs(180);
|
||||
|
||||
pub fn test_mc_empty_system(config: &TestConfig) -> TestResult {
|
||||
let sys = build_system(config);
|
||||
let procs = sys.process_names();
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let mut mc = ModelChecker::new(&sys);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
println!("Key {key} replicas: {replicas:?}");
|
||||
println!("Key {key} non-replicas: {non_replicas:?}");
|
||||
|
||||
// stage 1: get key from the first node
|
||||
let stage1_strategy = mc_query_strategy(&procs[0], McQuery::Get(key.clone(), vec![]));
|
||||
let stage1_msg = Message::json(
|
||||
"GET",
|
||||
&GetReqMessage {
|
||||
key: &key,
|
||||
quorum: 2,
|
||||
},
|
||||
);
|
||||
let stage1_states = run_mc(
|
||||
&mut mc,
|
||||
stage1_strategy,
|
||||
&procs[0],
|
||||
stage1_msg,
|
||||
McNetworkChange::None,
|
||||
None,
|
||||
)?
|
||||
.collected_states;
|
||||
println!("stage 1: {}", stage1_states.len());
|
||||
if stage1_states.is_empty() {
|
||||
return Err("stage 1 - GET response is not received".to_owned());
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_mc_basic(config: &TestConfig) -> TestResult {
|
||||
let sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let mut mc = ModelChecker::new(&sys);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
println!("Key {key} replicas: {replicas:?}");
|
||||
println!("Key {key} non-replicas: {non_replicas:?}");
|
||||
|
||||
// stage 1: put key to the first replica
|
||||
let value = random_string(8, &mut rand);
|
||||
let stage1_strategy =
|
||||
mc_query_strategy(&replicas[0], McQuery::Put(key.clone(), vec![value.clone()]));
|
||||
let stage1_strategy = stage1_strategy.prune(prunes::any_prune(vec![
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_timer_fired, 2),
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_message_received, 24),
|
||||
prunes::proc_permutations(&replicas),
|
||||
]));
|
||||
let stage1_msg = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value,
|
||||
quorum: 2,
|
||||
context: None,
|
||||
},
|
||||
);
|
||||
let stage1_states = run_mc(
|
||||
&mut mc,
|
||||
stage1_strategy,
|
||||
&replicas[0],
|
||||
stage1_msg,
|
||||
McNetworkChange::None,
|
||||
None,
|
||||
)?
|
||||
.collected_states;
|
||||
println!("stage 1: {}", stage1_states.len());
|
||||
if stage1_states.is_empty() {
|
||||
return Err("stage 1 - PUT response is not received".to_owned());
|
||||
}
|
||||
|
||||
// stage 2: get key from the last replica
|
||||
let stage2_strategy = mc_query_strategy(&replicas[2], McQuery::Get(key.clone(), vec![value]));
|
||||
let stage2_strategy = stage2_strategy.prune(prunes::any_prune(vec![
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_timer_fired, 4),
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_message_received, 24),
|
||||
// symmetry-breaking constraint: log starts with replica 2 (because it received the query)
|
||||
// and then the replica 0 should be earlier in the log than replica 1.
|
||||
prunes::proc_permutations(&[
|
||||
replicas[2].clone(),
|
||||
replicas[0].clone(),
|
||||
replicas[1].clone(),
|
||||
]),
|
||||
]));
|
||||
let stage2_msg = Message::json(
|
||||
"GET",
|
||||
&GetReqMessage {
|
||||
key: &key,
|
||||
quorum: 2,
|
||||
},
|
||||
);
|
||||
let stage2_states = run_mc(
|
||||
&mut mc,
|
||||
stage2_strategy,
|
||||
&replicas[2],
|
||||
stage2_msg,
|
||||
McNetworkChange::None,
|
||||
Some(stage1_states),
|
||||
)?
|
||||
.collected_states;
|
||||
println!("stage 2: {}", stage2_states.len());
|
||||
if stage2_states.is_empty() {
|
||||
return Err("stage 2 - GET response is not received".to_owned());
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_mc_concurrent_writes(config: &TestConfig) -> TestResult {
|
||||
let sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
println!("Key {key} replicas: {replicas:?}");
|
||||
println!("Key {key} non-replicas: {non_replicas:?}");
|
||||
|
||||
let mut mc = ModelChecker::new(&sys);
|
||||
|
||||
// put (key, value) to the first replica
|
||||
// and then put (key, value2) to the second replica
|
||||
let value = random_string(8, &mut rand);
|
||||
let value2 = random_string(8, &mut rand);
|
||||
|
||||
let strategy_config =
|
||||
mc_query_strategy(&replicas[0], McQuery::Put(key.clone(), vec![value.clone()]));
|
||||
let msg1 = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value,
|
||||
quorum: 1,
|
||||
context: None,
|
||||
},
|
||||
);
|
||||
let states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[0],
|
||||
msg1,
|
||||
McNetworkChange::Isolation,
|
||||
None,
|
||||
)?
|
||||
.collected_states;
|
||||
if states.is_empty() {
|
||||
return Err(format!("put({key}, {value}) response is not received"));
|
||||
}
|
||||
println!("put({key}, {value}): {} states collected", states.len());
|
||||
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[1],
|
||||
McQuery::Put(key.clone(), vec![value2.clone()]),
|
||||
);
|
||||
let msg2 = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value2,
|
||||
quorum: 1,
|
||||
context: None,
|
||||
},
|
||||
);
|
||||
let states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[1],
|
||||
msg2,
|
||||
McNetworkChange::None,
|
||||
Some(states),
|
||||
)?
|
||||
.collected_states;
|
||||
if states.is_empty() {
|
||||
return Err(format!("put({key}, {value2}) response is not received"));
|
||||
}
|
||||
println!("put({key}, {value2}): {} states collected", states.len());
|
||||
|
||||
// now reset the network state and ask the third replica about the key's value
|
||||
// we expect both values in the response
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[2],
|
||||
McQuery::Get(key.to_string(), vec![value.to_string(), value2.to_string()]),
|
||||
);
|
||||
let msg = Message::json(
|
||||
"GET",
|
||||
&GetReqMessage {
|
||||
key: &key,
|
||||
quorum: 3,
|
||||
},
|
||||
);
|
||||
let states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[2],
|
||||
msg,
|
||||
McNetworkChange::Reset,
|
||||
Some(states),
|
||||
)?
|
||||
.collected_states;
|
||||
if states.is_empty() {
|
||||
return Err(format!("get({key}) response is not received"));
|
||||
}
|
||||
println!("get({key}): {} states collected", states.len());
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_mc_sloppy_quorum_hinted_handoff(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let mut mc = ModelChecker::new(&sys);
|
||||
|
||||
let key = random_key(&mut rand);
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
println!("Key {key} replicas: {replicas:?}");
|
||||
println!("Key {key} non-replicas: {non_replicas:?}");
|
||||
|
||||
// stage 1: put key from the first replica (network partition still exists)
|
||||
let value = random_string(8, &mut rand);
|
||||
let stage1_strategy =
|
||||
mc_query_strategy(&replicas[0], McQuery::Put(key.clone(), vec![value.clone()]));
|
||||
let stage1_msg = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value,
|
||||
quorum: 2,
|
||||
context: None,
|
||||
},
|
||||
);
|
||||
let stage1_states = run_mc(
|
||||
&mut mc,
|
||||
stage1_strategy,
|
||||
&replicas[0],
|
||||
stage1_msg,
|
||||
McNetworkChange::Partition([
|
||||
vec![
|
||||
replicas[0].clone(),
|
||||
non_replicas[0].clone(),
|
||||
non_replicas[1].clone(),
|
||||
non_replicas[2].clone(),
|
||||
],
|
||||
vec![replicas[1].clone(), replicas[2].clone()],
|
||||
]),
|
||||
None,
|
||||
)?
|
||||
.collected_states;
|
||||
println!("stage 1: {}", stage1_states.len());
|
||||
if stage1_states.is_empty() {
|
||||
return Err("stage 1 - PUT response is not received".to_owned());
|
||||
}
|
||||
|
||||
// stage 2: recover network and let data propagate to all replicas
|
||||
let stage2_states = mc_stabilize(&mut sys, stage1_states, MC_SEARCH_LIMIT)?.collected_states;
|
||||
println!("stage 2: {}", stage2_states.len());
|
||||
if stage2_states.is_empty() {
|
||||
return Err(
|
||||
"stage 2 - no states found during the exploration phase with recovered network"
|
||||
.to_owned(),
|
||||
);
|
||||
}
|
||||
|
||||
// stage 3: get key from the last replica (again during the network partition)
|
||||
let stage3_strategy = mc_query_strategy(&replicas[2], McQuery::Get(key.clone(), vec![value]));
|
||||
let stage3_msg = Message::json(
|
||||
"GET",
|
||||
&GetReqMessage {
|
||||
key: &key,
|
||||
quorum: 2,
|
||||
},
|
||||
);
|
||||
let stage3_states = run_mc(
|
||||
&mut mc,
|
||||
stage3_strategy,
|
||||
&replicas[2],
|
||||
stage3_msg,
|
||||
McNetworkChange::Partition([
|
||||
vec![
|
||||
replicas[0].clone(),
|
||||
non_replicas[0].clone(),
|
||||
non_replicas[1].clone(),
|
||||
non_replicas[2].clone(),
|
||||
],
|
||||
vec![replicas[1].clone(), replicas[2].clone()],
|
||||
]),
|
||||
Some(stage2_states),
|
||||
)?
|
||||
.collected_states;
|
||||
println!("stage 3: {}", stage3_states.len());
|
||||
if stage3_states.is_empty() {
|
||||
return Err("stage 3 - GET response is not received".to_owned());
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_mc_concurrent_cart(config: &TestConfig) -> TestResult {
|
||||
let sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = format!("CART_{}", random_string(8, &mut rand).to_uppercase());
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let non_replicas = key_non_replicas(&key, &sys);
|
||||
println!("Key {key} replicas: {replicas:?}");
|
||||
println!("Key {key} non-replicas: {non_replicas:?}");
|
||||
|
||||
// put key to the first replica
|
||||
let value = "a,b,c".to_string();
|
||||
let value2 = "b,c,d".to_string();
|
||||
|
||||
let mut mc = ModelChecker::new(&sys);
|
||||
|
||||
let strategy_config =
|
||||
mc_query_strategy(&replicas[0], McQuery::Put(key.clone(), vec![value.clone()]));
|
||||
let msg1 = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value,
|
||||
quorum: 1,
|
||||
context: None,
|
||||
},
|
||||
);
|
||||
let states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[0],
|
||||
msg1,
|
||||
McNetworkChange::Isolation,
|
||||
None,
|
||||
)?
|
||||
.collected_states;
|
||||
if states.is_empty() {
|
||||
return Err(format!("put({key}, \"{value}\") response is not received"));
|
||||
}
|
||||
println!("put({key}, \"{value}\"): {} states collected", states.len());
|
||||
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[1],
|
||||
McQuery::Put(key.clone(), vec![value2.clone()]),
|
||||
);
|
||||
let msg2 = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value2,
|
||||
quorum: 1,
|
||||
context: None,
|
||||
},
|
||||
);
|
||||
let states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[1],
|
||||
msg2,
|
||||
McNetworkChange::None,
|
||||
Some(states),
|
||||
)?
|
||||
.collected_states;
|
||||
if states.is_empty() {
|
||||
return Err(format!("put({key}, \"{value2}\") response is not received"));
|
||||
}
|
||||
println!(
|
||||
"put({key}, \"{value2}\"): {} states collected",
|
||||
states.len()
|
||||
);
|
||||
|
||||
// Now reset the network state and ask all replicas to agree about value for key
|
||||
// We expect the combination of "a,b,c" and "b,c,d"
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[2],
|
||||
McQuery::Get(key.to_string(), vec!["a,b,c,d".to_string()]),
|
||||
);
|
||||
let msg3 = Message::json(
|
||||
"GET",
|
||||
&GetReqMessage {
|
||||
key: &key,
|
||||
quorum: 3,
|
||||
},
|
||||
);
|
||||
let states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[2],
|
||||
msg3,
|
||||
McNetworkChange::Reset,
|
||||
Some(states),
|
||||
)?
|
||||
.collected_states;
|
||||
if states.is_empty() {
|
||||
return Err(format!("get({key}) has no positive outcomes"));
|
||||
}
|
||||
println!("get({key}): {} states collected", states.len());
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn test_mc_concurrent_xcart(config: &TestConfig) -> TestResult {
|
||||
let mut sys = build_system(config);
|
||||
let mut rand = Pcg64::seed_from_u64(config.seed);
|
||||
|
||||
let key = format!("xcart-{}", random_string(8, &mut rand)).to_uppercase();
|
||||
let replicas = key_replicas(&key, &sys);
|
||||
let mut mc = ModelChecker::new(&sys);
|
||||
|
||||
let value1 = "a,b".to_string();
|
||||
let value2 = "a,b,c".to_string();
|
||||
let value3 = "d".to_string();
|
||||
let value4 = "c,d".to_string();
|
||||
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[2],
|
||||
McQuery::Put(key.clone(), vec![value1.clone()]),
|
||||
);
|
||||
let msg1 = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value1,
|
||||
quorum: 3,
|
||||
context: None,
|
||||
},
|
||||
);
|
||||
let states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[2],
|
||||
msg1,
|
||||
McNetworkChange::None,
|
||||
None,
|
||||
)?
|
||||
.collected_states;
|
||||
if states.is_empty() {
|
||||
return Err(format!("put({key}, \"{value1}\") response is not received"));
|
||||
}
|
||||
println!("get({key}): {} states collected", states.len());
|
||||
|
||||
let states = mc_stabilize(&mut sys, states, MC_SEARCH_LIMIT)?.collected_states;
|
||||
println!("after stabilization: {} states collected", states.len());
|
||||
|
||||
for state in &states {
|
||||
let msg = state.node_states[&replicas[2]].proc_states[&replicas[2]]
|
||||
.local_outbox
|
||||
.first()
|
||||
.ok_or_else(|| format!("PUT_RESP is not returned by {}", replicas[2]))?;
|
||||
let ctx = PutRespMessage::parse(msg, &replicas[2])?.context;
|
||||
|
||||
let msg1 = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value2,
|
||||
quorum: 1,
|
||||
context: Some(ctx.clone()),
|
||||
},
|
||||
);
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[0],
|
||||
McQuery::Put(key.clone(), vec![value2.clone()]),
|
||||
);
|
||||
mc = ModelChecker::new(&sys);
|
||||
let cur_states: HashSet<McState> = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[0],
|
||||
msg1,
|
||||
McNetworkChange::Isolation,
|
||||
Some(HashSet::from_iter(vec![state.clone()])),
|
||||
)?
|
||||
.collected_states;
|
||||
println!(
|
||||
"put({key}, \"{value2}\"): {} states collected",
|
||||
cur_states.len()
|
||||
);
|
||||
if cur_states.is_empty() {
|
||||
return Err(format!("put({key}, \"{value2}\") response is not received"));
|
||||
}
|
||||
|
||||
let msg2 = Message::json(
|
||||
"PUT",
|
||||
&PutReqMessage {
|
||||
key: &key,
|
||||
value: &value3,
|
||||
quorum: 1,
|
||||
context: Some(ctx),
|
||||
},
|
||||
);
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[1],
|
||||
McQuery::Put(key.clone(), vec![value3.clone()]),
|
||||
);
|
||||
let cur_states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[1],
|
||||
msg2,
|
||||
McNetworkChange::Isolation,
|
||||
Some(cur_states),
|
||||
)?
|
||||
.collected_states;
|
||||
println!(
|
||||
"put({key}, \"{value3}\"): {} states collected",
|
||||
cur_states.len()
|
||||
);
|
||||
if cur_states.is_empty() {
|
||||
return Err(format!("put({key}, \"{value3}\") response is not received"));
|
||||
}
|
||||
|
||||
let msg3 = Message::json(
|
||||
"GET",
|
||||
&GetReqMessage {
|
||||
key: &key,
|
||||
quorum: 3,
|
||||
},
|
||||
);
|
||||
let strategy_config = mc_query_strategy(
|
||||
&replicas[2],
|
||||
McQuery::Get(key.clone(), vec![value4.clone()]),
|
||||
);
|
||||
let final_states = run_mc(
|
||||
&mut mc,
|
||||
strategy_config,
|
||||
&replicas[2],
|
||||
msg3,
|
||||
McNetworkChange::Reset,
|
||||
Some(cur_states),
|
||||
)?
|
||||
.collected_states;
|
||||
println!("get({key}): {} states collected", final_states.len());
|
||||
if final_states.is_empty() {
|
||||
return Err(format!("get({key}) response is not received"));
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// UTILS ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
enum McQuery {
|
||||
Get(String, Vec<String>),
|
||||
Put(String, Vec<String>),
|
||||
}
|
||||
|
||||
fn mc_query_strategy(proc: &str, query_data: McQuery) -> StrategyConfig {
|
||||
let proc_name = proc.to_string();
|
||||
|
||||
let invariant = match query_data {
|
||||
McQuery::Get(key, expected) => mc_get_invariant(proc, key, expected),
|
||||
McQuery::Put(key, value) => mc_put_invariant(proc, key, value),
|
||||
};
|
||||
|
||||
StrategyConfig::default()
|
||||
.prune(prunes::any_prune(vec![
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_timer_fired, 5_usize),
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_message_received, 10_usize),
|
||||
]))
|
||||
.goal(goals::event_happened_n_times_current_run(
|
||||
LogEntry::is_mc_local_message_sent,
|
||||
1,
|
||||
))
|
||||
.invariant(invariants::all_invariants(vec![
|
||||
invariant,
|
||||
invariants::time_limit(MC_SEARCH_LIMIT),
|
||||
]))
|
||||
.collect(collects::event_happened_n_times_current_run(
|
||||
move |log_entry| match log_entry {
|
||||
LogEntry::McLocalMessageSent { proc, .. } => proc == &proc_name,
|
||||
_ => false,
|
||||
},
|
||||
1,
|
||||
))
|
||||
}
|
||||
|
||||
fn mc_get_invariant<S>(proc: S, key: String, expected: Vec<String>) -> InvariantFn
|
||||
where
|
||||
S: Into<String>,
|
||||
{
|
||||
let proc_name = proc.into();
|
||||
Box::new(move |state: &McState| -> Result<(), String> {
|
||||
for entry in state.current_run_trace().iter() {
|
||||
if let LogEntry::McLocalMessageSent { msg, proc } = entry {
|
||||
if &proc_name != proc {
|
||||
return Err("local message received on wrong process".to_string());
|
||||
}
|
||||
if msg.tip != "GET_RESP" {
|
||||
return Err(format!("wrong type {}", msg.tip));
|
||||
}
|
||||
let data = GetRespMessage::parse(msg, proc)?;
|
||||
if data.key != key {
|
||||
return Err(format!("wrong key {}", data.key));
|
||||
}
|
||||
if sorted_cart(&data.values) != sorted_cart(&expected) {
|
||||
return Err(format!("wrong values {:?}", sorted_cart(&data.values)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn mc_put_invariant<S>(proc: S, key: String, values: Vec<String>) -> InvariantFn
|
||||
where
|
||||
S: Into<String>,
|
||||
{
|
||||
let proc_name = proc.into();
|
||||
Box::new(move |state: &McState| -> Result<(), String> {
|
||||
for entry in state.current_run_trace().iter() {
|
||||
if let LogEntry::McLocalMessageSent { msg, proc } = entry {
|
||||
if &proc_name != proc {
|
||||
return Err("local message received on wrong process".to_string());
|
||||
}
|
||||
if msg.tip != "PUT_RESP" {
|
||||
return Err(format!("wrong type {}", msg.tip));
|
||||
}
|
||||
let data = PutRespMessage::parse(msg, proc)?;
|
||||
if data.key != key {
|
||||
return Err(format!("wrong key {}", data.key));
|
||||
}
|
||||
if sorted_cart(&data.values) != sorted_cart(&values) {
|
||||
return Err(format!("wrong values {:?}", sorted_cart(&data.values)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn sorted_cart(cart: &[String]) -> Vec<String> {
|
||||
let mut res = vec![];
|
||||
for items in cart {
|
||||
let mut items = items
|
||||
.split(',')
|
||||
.map(|s| s.to_owned())
|
||||
.collect::<Vec<String>>();
|
||||
items.sort();
|
||||
res.push(items.join(","));
|
||||
}
|
||||
res.sort();
|
||||
res
|
||||
}
|
||||
|
||||
enum McNetworkChange {
|
||||
None,
|
||||
Reset,
|
||||
Partition([Vec<String>; 2]),
|
||||
Isolation,
|
||||
}
|
||||
|
||||
fn run_mc<S>(
|
||||
mc: &mut ModelChecker,
|
||||
strategy_config: StrategyConfig,
|
||||
proc: S,
|
||||
msg: Message,
|
||||
network_change: McNetworkChange,
|
||||
states: Option<HashSet<McState>>,
|
||||
) -> Result<McStats, String>
|
||||
where
|
||||
S: Into<String>,
|
||||
{
|
||||
let proc = proc.into();
|
||||
|
||||
let callback = |sys: &mut McSystem| {
|
||||
match &network_change {
|
||||
McNetworkChange::Partition([part1, part2]) => sys.network().partition(part1, part2),
|
||||
McNetworkChange::Reset => sys.network().reset(),
|
||||
McNetworkChange::Isolation => {
|
||||
for node in sys.nodes() {
|
||||
sys.network().disconnect_node(&node)
|
||||
}
|
||||
}
|
||||
McNetworkChange::None => {}
|
||||
}
|
||||
sys.set_event_ordering_mode(EventOrderingMode::MessagesFirst);
|
||||
sys.send_local_message(proc.clone(), proc.clone(), msg.clone());
|
||||
};
|
||||
|
||||
let res = if let Some(states) = states {
|
||||
mc.run_from_states_with_change::<Bfs>(strategy_config, states, callback)
|
||||
} else {
|
||||
mc.run_with_change::<Bfs>(strategy_config, callback)
|
||||
};
|
||||
match res {
|
||||
Err(e) => {
|
||||
e.print_trace();
|
||||
Err(e.message())
|
||||
}
|
||||
Ok(stats) => Ok(stats),
|
||||
}
|
||||
}
|
||||
|
||||
fn mc_stabilize(
|
||||
sys: &mut System,
|
||||
states: HashSet<McState>,
|
||||
time_limit: Duration,
|
||||
) -> Result<McStats, String> {
|
||||
let strategy_config = StrategyConfig::default()
|
||||
.invariant(invariants::time_limit(time_limit))
|
||||
.prune(prunes::any_prune(vec![
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_timer_fired, 6),
|
||||
prunes::event_happened_n_times_current_run(LogEntry::is_mc_message_received, 24),
|
||||
]))
|
||||
.goal(goals::any_goal(vec![
|
||||
goals::depth_reached(30),
|
||||
goals::no_events(),
|
||||
]))
|
||||
.collect(collects::any_collect(vec![
|
||||
collects::no_events(),
|
||||
collects::event_happened_n_times_current_run(LogEntry::is_mc_timer_fired, 6),
|
||||
collects::event_happened_n_times_current_run(LogEntry::is_mc_message_received, 24),
|
||||
]));
|
||||
let mut mc = ModelChecker::new(sys);
|
||||
let res = mc.run_from_states_with_change::<Bfs>(strategy_config, states, |sys| {
|
||||
sys.network().reset();
|
||||
sys.set_event_ordering_mode(EventOrderingMode::MessagesFirst);
|
||||
});
|
||||
res.map_err(|e| {
|
||||
e.print_trace();
|
||||
format!("stabilization: {}", e.message())
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user