//! Runs the tests of a `.synctest` file. Each run of a test gets its own sync server and its //! own client directories. A test with an `interleave` block runs once per schedule. use crate::driver::{Client, IoKind, Output, Poll, SyncStep, Task}; use crate::parser::{ Command, DEFAULT_CONNECTION, Expect, Item, Runner, Step, Target, Test, command_name, skip_reason, }; use crate::server::SyncServer; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; use turso_sdk_kit::rsapi::TursoConnection; #[derive(Debug, Clone)] pub struct RunOptions { pub tursodb: PathBuf, /// Longest time one step can take before the test fails. pub step_timeout: Duration, /// Keep the test directory (server log and databases) of a failed test. pub keep_failed: bool, /// Largest number of schedules to run for a test with an `interleave` block. pub max_schedules: usize, /// Seed of the PCT scheduler. pub seed: u64, /// Depth of the PCT scheduler: the number of forced task switches is one less. pub pct_depth: usize, /// Run only this schedule, as shuttle printed it for a failed run. pub replay: Option, pub io: IoKind, /// The program that runs the client steps. pub runner: Runner, /// The command of the driver process, for a runner other than `rust`. pub driver: Vec, } #[derive(Debug)] pub enum Outcome { /// The note tells how many schedules ran, for a test with an `interleave` block. Passed(Option), Skipped(String), Failed(String), } /// Runs the test. A test with `@skip` runs too: it must fail. When it passes, the outcome is a /// failure, so that nobody forgets to remove the `@skip` after a fix. pub fn run_test(test: &Test, options: &RunOptions) -> Outcome { let outcome = run_test_body(test, options); let Some(reason) = skip_reason(&test.skips, options.runner) else { return outcome; }; match outcome { Outcome::Failed(_) | Outcome::Skipped(_) => Outcome::Skipped(reason.to_string()), Outcome::Passed(_) => { Outcome::Failed(format!("the test passes now: remove `@skip \"{reason}\"`")) } } } fn run_test_body(test: &Test, options: &RunOptions) -> Outcome { let interleaves = test .items .iter() .any(|item| matches!(item, Item::Interleave { .. })); if options.runner != Runner::Rust { if test .items .iter() .any(|item| matches!(item, Item::Advance { .. })) { return Outcome::Skipped("step needs the rust runner".to_string()); } // The driver picks the order of the tasks: a second run is not a new schedule. return match run_in_new_dir(test, options) { Ok(()) => { Outcome::Passed(interleaves.then(|| "1 run, order of the driver".to_string())) } Err(message) => Outcome::Failed(message), }; } if !interleaves { return match run_in_new_dir(test, options) { Ok(()) => Outcome::Passed(None), Err(message) => Outcome::Failed(message), }; } // Shuttle runs the test many times and picks the order of the tasks of the // `interleave` block in each run. A failed run panics; shuttle adds the schedule to the // panic message. let (shared_test, shared_options) = (Arc::new(test.clone()), Arc::new(options.clone())); let body = move || { if let Err(message) = run_in_new_dir(&shared_test, &shared_options) { panic!("{message}"); } }; let mut config = shuttle::Config::new(); // Shuttle threads run the database code, which needs more than the default stack. The // `generator` crate under shuttle counts the size in words: 4 Mi words is 32 MiB. config.stack_size = 4 << 20; // A failing schedule can be long: write it to a file, and print the path. config.failure_persistence = shuttle::FailurePersistence::File(Some(std::env::temp_dir())); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match &options.replay { Some(schedule) => { let scheduler = if Path::new(schedule).exists() { shuttle::scheduler::ReplayScheduler::new_from_file(schedule) .expect("cannot read the schedule file") } else { shuttle::scheduler::ReplayScheduler::new_from_encoded(schedule) }; shuttle::Runner::new(scheduler, config).run(body) } None => { let scheduler = shuttle::scheduler::PctScheduler::new_from_seed( options.seed, options.pct_depth, options.max_schedules, ); shuttle::Runner::new(scheduler, config).run(body) } })); match result { Ok(runs) => Outcome::Passed(Some(format!("{runs} schedule(s)"))), Err(payload) => Outcome::Failed( payload .downcast_ref::() .cloned() .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string())) .unwrap_or_else(|| "the test panicked".to_string()), ), } } fn run_in_new_dir(test: &Test, options: &RunOptions) -> Result<(), String> { let dir = tempfile::Builder::new() .prefix("synctest-") .tempdir() .map_err(|error| format!("failed to create a directory: {error}"))?; let result = match options.runner { Runner::Rust => run_once(test, options, dir.path()), Runner::Js | Runner::Go => crate::external::run_once(test, options, dir.path()), }; match result { Err(message) if options.keep_failed => { let path = dir.keep(); Err(format!( "{message}\n databases and server.log kept in {}", path.display() )) } result => result, } } fn run_once(test: &Test, options: &RunOptions, dir: &Path) -> Result<(), String> { let server = SyncServer::start(&options.tursodb, &dir.join("server.db")) .map_err(|error| format!("{error:#}"))?; let mut env = Env { tasks: HashMap::new(), clients: HashMap::new(), port: server.port(), dir: dir.to_path_buf(), timeout: options.step_timeout, io: options.io, files: HashMap::new(), }; for item in &test.items { env.run_item(item)?; } if let Some((name, task)) = env.tasks.iter().min_by_key(|(_, task)| task.line) { return Err(format!( "line {}: task `{name}` has no `wait {name}`", task.line )); } Ok(()) } struct Env { tasks: HashMap, clients: HashMap, port: u16, dir: PathBuf, timeout: Duration, io: IoKind, /// The database IO of each client. It holds the files of the client across `reopen`. files: HashMap>, } struct ClientState { client: Client, connections: HashMap>, } struct TaskState { task: Task, result: Option, /// Line of the step that started the task. line: usize, /// Number of polls so far. polls: usize, /// The client and connection of the task. client: String, connection: Option, } /// Moves a value into a shuttle thread. Shuttle runs all its threads on the thread that /// runs the test, one at a time, so the value never moves to another OS thread. struct OneThread(T); // SAFETY: see the comment on `OneThread`. unsafe impl Send for OneThread {} impl TaskState { fn poll(&mut self) { if self.result.is_some() { return; } self.polls += 1; tracing::info!( "synctest: poll {} of the task from line {}", self.polls, self.line ); if let Poll::Ready(output) = self.task.poll() { tracing::info!( "synctest: the task from line {} ended: {output:?}", self.line ); self.result = Some(output); } } } impl Drop for Env { fn drop(&mut self) { // Tasks hold statements and connections: release them before the connections. self.tasks.clear(); for (_, state) in self.clients.drain() { close_connections(state); } } } fn close_connections(state: ClientState) { for (_, connection) in state.connections { let _ = connection.close(); } } impl Env { fn run_item(&mut self, item: &Item) -> Result<(), String> { match item { Item::Step(step) => match &step.task { None => { tracing::info!("synctest: line {}: {}", step.line, describe_step(step)); let output = self.run_step(step); check(Runner::Rust, &step.expect, output) .map_err(|message| step_error(step.line, &describe_step(step), message)) } Some(name) => { self.start_task(name, step)?; self.tasks.get_mut(name).unwrap().poll(); Ok(()) } }, Item::Advance { line, task, count } => { let state = self.task(task, *line)?; for _ in 0..*count { state.poll(); } Ok(()) } Item::Wait { line, task, expect } => { let timeout = self.timeout; let state = self.task(task, *line)?; let deadline = Instant::now() + timeout; while state.result.is_none() { if Instant::now() > deadline { return Err(format!( "line {line}: task `{task}` did not finish in {timeout:?}" )); } state.poll(); } let output = self.tasks.remove(task).unwrap().result.unwrap(); check(Runner::Rust, expect, output) .map_err(|message| step_error(*line, &format!("wait {task}"), message)) } Item::Interleave { line, steps } => { for step in steps { self.start_task(step.task.as_ref().unwrap(), step)?; } let deadline = Instant::now() + self.timeout; let threads: Vec<_> = steps .iter() .map(|step| { let name = step.task.clone().unwrap(); let state = OneThread(self.tasks.remove(&name).unwrap()); shuttle::thread::spawn(move || { let mut state = state; while state.0.result.is_none() && Instant::now() <= deadline { state.0.poll(); // `sleep` is a plain switch point. `yield_now` makes the PCT // scheduler lower the priority of the task, so it switches to // another task. Do that only at every 64th poll: then a task // that waits for a lock (busy wait) lets the lock holder run, // and the other polls keep the order that PCT picks. if state.0.polls % 64 == 0 { shuttle::thread::yield_now(); } else { shuttle::thread::sleep(Duration::ZERO); } } OneThread((name, state.0)) }) }) .collect(); for thread in threads { let (name, state) = thread.join().expect("a task thread panicked").0; self.tasks.insert(name, state); } if steps .iter() .any(|step| self.tasks[step.task.as_ref().unwrap()].result.is_none()) { return Err(format!( "line {line}: the tasks did not finish in {:?}", self.timeout )); } Ok(()) } } } fn task(&mut self, name: &str, line: usize) -> Result<&mut TaskState, String> { self.tasks .get_mut(name) .ok_or_else(|| format!("line {line}: no running task `{name}`")) } fn start_task(&mut self, name: &str, step: &Step) -> Result<(), String> { if let Some(task) = self.tasks.get(name) { return Err(format!( "line {}: task `{name}` from line {} is still running: add `wait {name}` first", step.line, task.line )); } let (task, client, connection) = self .make_task(step) .map_err(|message| step_error(step.line, &describe_step(step), message))?; self.tasks.insert( name.to_string(), TaskState { task, result: None, line: step.line, polls: 0, client, connection, }, ); Ok(()) } fn run_step(&mut self, step: &Step) -> Output { let Target::Client { client, connection } = &step.target else { let Command::Exec(sql) = &step.command else { unreachable!("the parser allows only `exec` on the server"); }; return crate::pipeline::execute(self.port, sql, self.timeout) .map_err(|e| format!("{e:#}")); }; match &step.command { Command::Init { ungated } => { if self.clients.contains_key(client) { return Err(format!("client `{client}` is already open")); } let path = self.dir.join(format!("{client}.db")); self.open_client(client, &path.to_string_lossy(), *ungated) } Command::Reopen => { let state = self.client(client)?; let (path, ungated) = (state.client.path.clone(), state.client.ungated); self.check_no_task(client, None)?; close_connections(self.clients.remove(client).unwrap()); self.open_client(client, &path, ungated) } Command::Close => { self.check_no_task(client, Some(connection))?; let connection = self .client(client)? .connections .remove(connection) .ok_or_else(|| format!("connection `{client}.{connection}` is not open"))?; connection.close().map_err(|e| e.to_string())?; Ok(Vec::new()) } _ => { let (mut task, _, _) = self.make_task(step)?; let deadline = Instant::now() + self.timeout; loop { if let Poll::Ready(output) = task.poll() { return output; } if Instant::now() > deadline { return Err(format!("step did not finish in {:?}", self.timeout)); } } } } } fn open_client(&mut self, name: &str, path: &str, ungated: bool) -> Output { let core_io = match self.files.get(name) { Some(io) => io.clone(), None => { let io = self.io.create().map_err(|e| format!("{e:#}"))?; self.files.insert(name.to_string(), io.clone()); io } }; let client = Client::open(path, name, self.port, self.timeout, core_io, ungated) .map_err(|e| format!("failed to open client `{name}`: {e:#}"))?; self.clients.insert( name.to_string(), ClientState { client, connections: HashMap::new(), }, ); Ok(Vec::new()) } /// Makes the task of a step that runs on a client. Returns the task, its client and its /// connection. fn make_task(&mut self, step: &Step) -> Result<(Task, String, Option), String> { let Target::Client { client, connection } = &step.target else { return Err("only client steps can run as tasks".to_string()); }; let plan: &[SyncStep] = match &step.command { Command::Exec(sql) => { self.check_no_task(client, Some(connection))?; let state = self.client(client)?; if !state.connections.contains_key(connection) { let opened = state.client.connect().map_err(|e| format!("{e:#}"))?; state.connections.insert(connection.clone(), opened); } let task = Task::statements(state.connections[connection].clone(), sql); return Ok((task, client.clone(), Some(connection.clone()))); } Command::Pull => &[SyncStep::Pull], Command::Push => &[SyncStep::Push], Command::Sync => &[SyncStep::Push, SyncStep::Pull], Command::Checkpoint => &[SyncStep::Checkpoint], Command::Init { .. } | Command::Reopen | Command::Close => { unreachable!("the parser does not allow these as tasks") } }; let task = self.client(client)?.client.operation(plan); Ok((task, client.clone(), None)) } fn client(&mut self, name: &str) -> Result<&mut ClientState, String> { self.clients .get_mut(name) .ok_or_else(|| format!("client `{name}` is not open: run `{name} init` first")) } /// Fails if a running task uses the connection (or, without a connection, the client). fn check_no_task(&self, client: &str, connection: Option<&str>) -> Result<(), String> { for (name, task) in &self.tasks { let same = task.client == client && (connection.is_none() || task.connection.as_deref() == connection); if same && task.result.is_none() { return Err(format!( "task `{name}` from line {} still runs on this {}", task.line, if connection.is_some() { "connection" } else { "client" } )); } } Ok(()) } } pub(crate) fn step_error(line: usize, description: &str, message: String) -> String { format!("line {line}: {description}\n{message}") } /// Checks the result of a step against the alternatives of `expect` that apply to the runner. pub(crate) fn check(runner: Runner, expect: &Option, output: Output) -> Result<(), String> { check_resolved(&expect.as_ref().and_then(|e| e.for_runner(runner)), output) } fn check_resolved(expect: &Option, output: Output) -> Result<(), String> { if let Some(Expect::AnyOf(all)) = expect { let mut failures = Vec::new(); for alternative in all { match check_resolved(&Some(alternative.clone()), output.clone()) { Ok(()) => return Ok(()), Err(message) => failures.push(message), } } return Err(format!( " no alternative matches:\n{}", failures.join("\n or\n") )); } match (expect, output) { (Some(Expect::AnyOf(_)), _) => unreachable!("handled above"), (Some(Expect::Only { .. }), _) => unreachable!("`for_runner` removes the runner tags"), (None, Ok(_)) => Ok(()), (None, Err(error)) => Err(format!(" unexpected error: {error}")), (Some(Expect::Error(_)), Ok(rows)) => Err(format!( " expected an error, got {} row(s){}", rows.len(), format_rows(&rows) )), (Some(Expect::Error(pattern)), Err(error)) => match pattern { None => Ok(()), Some(pattern) => { let regex = regex::Regex::new(&format!("(?i){pattern}")) .map_err(|e| format!(" invalid error pattern: {e}"))?; if regex.is_match(&error) { Ok(()) } else { Err(format!( " error does not match `{pattern}`\n actual error: {error}" )) } } }, (Some(Expect::Rows { .. }), Err(error)) => Err(format!(" unexpected error: {error}")), (Some(Expect::Rows { rows, unordered }), Ok(actual)) => { let (mut expected, mut actual) = (rows.clone(), actual); if *unordered { expected.sort(); actual.sort(); } if expected == actual { Ok(()) } else { let expected = expected.join("\n") + "\n"; let actual = actual.join("\n") + "\n"; let diff = similar::TextDiff::from_lines(&expected, &actual) .unified_diff() .header("expected", "actual") .to_string(); Err(format!(" rows differ:\n{diff}")) } } } } fn format_rows(rows: &[String]) -> String { rows.iter().map(|row| format!("\n {row}")).collect() } pub(crate) fn describe_step(step: &Step) -> String { let target = match &step.target { Target::Server => "server".to_string(), Target::Client { client, connection } if connection == DEFAULT_CONNECTION => client.clone(), Target::Client { client, connection } => format!("{client}.{connection}"), }; let command = match &step.command { Command::Exec(sql) => format!("exec {}", sql.replace('\n', " ")), other => command_name(other).to_string(), }; match &step.task { Some(task) => format!("{target} {command} &{task}"), None => format!("{target} {command}"), } } /// Formats a REAL the way the sqltest runner does: whole numbers keep `.0`. pub(crate) fn format_real(f: f64) -> String { if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e15 { format!("{f:.1}") } else { f.to_string() } }