| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The system under test: the engine over an object store, and the lander, a |
| 5 | //! serialized section that owns the branch head. |
| 6 | //! |
| 7 | //! The lander does what the command line will do inside |
| 8 | //! [`Store::transact`]: read the head, call [`land`], and move the branch with |
| 9 | //! a compare-and-swap from the head it read to the changeset the outcome |
| 10 | //! names. Nothing moves on a conflict or when the change has nothing left to |
| 11 | //! add. A crash falls between computing the outcome and the compare-and-swap. |
| 12 | |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | |
| 15 | use braid_engine::{LandOutcome, land}; |
| 16 | use braid_format::{MemoryObjects, ObjectId, Objects, Signature}; |
| 17 | use braid_store::{Options, RefUpdate, Store, TransactError}; |
| 18 | |
| 19 | /// The branch the agents land on. |
| 20 | pub const MAIN: &str = "main"; |
| 21 | |
| 22 | /// The agent label of the lander's operations. |
| 23 | const LANDER: &str = "lander"; |
| 24 | |
| 25 | /// One landing request, as the lander receives it. |
| 26 | #[derive(Clone, Debug)] |
| 27 | pub struct LandRequest { |
| 28 | /// The changeset to land. |
| 29 | pub change: ObjectId, |
| 30 | /// Who records the rebased changeset. |
| 31 | pub committer: Signature, |
| 32 | /// Whether the lander crashes after computing the outcome, before the |
| 33 | /// compare-and-swap. |
| 34 | pub crash: bool, |
| 35 | /// What the operation is, for the op log. |
| 36 | pub description: String, |
| 37 | } |
| 38 | |
| 39 | /// What the lander did with a request. |
| 40 | #[derive(Clone, Debug)] |
| 41 | pub struct Landed { |
| 42 | /// The head the lander read inside its serialized section. |
| 43 | pub head: Option<ObjectId>, |
| 44 | /// What [`land`] decided. |
| 45 | pub outcome: LandOutcome, |
| 46 | /// Where the compare-and-swap moved the branch, if it ran and moved it. |
| 47 | pub moved: Option<ObjectId>, |
| 48 | } |
| 49 | |
| 50 | /// One move of the branch, as the op log records it: the head before and |
| 51 | /// after. |
| 52 | pub type Move = (Option<ObjectId>, Option<ObjectId>); |
| 53 | |
| 54 | /// The changeset an outcome moves the branch to. |
| 55 | pub fn target(outcome: &LandOutcome) -> Option<ObjectId> { |
| 56 | match outcome { |
| 57 | LandOutcome::FastForward(id) => Some(*id), |
| 58 | LandOutcome::Rebased { changeset, .. } => Some(*changeset), |
| 59 | LandOutcome::AlreadyApplied | LandOutcome::Conflicts(_) => None, |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Where objects and the branch head live. |
| 64 | pub trait Backend { |
| 65 | /// The object store. |
| 66 | type Objects: Objects; |
| 67 | |
| 68 | /// A short name for reports. |
| 69 | fn name(&self) -> &'static str; |
| 70 | |
| 71 | /// Objects as the lander and the checks see them. |
| 72 | fn objects(&self) -> &Self::Objects; |
| 73 | |
| 74 | /// Objects as an agent sees them: its own handle on the shared store. |
| 75 | fn agent_objects(&self, agent: usize) -> &Self::Objects; |
| 76 | |
| 77 | /// Makes what an agent wrote durable, before it asks for a landing. |
| 78 | fn agent_sync(&self, agent: usize) -> Result<(), String>; |
| 79 | |
| 80 | /// The head of the branch, as the checks read it. |
| 81 | fn head(&self) -> Result<Option<ObjectId>, String>; |
| 82 | |
| 83 | /// The head of the branch, as an agent reads it. |
| 84 | fn agent_head(&self, agent: usize) -> Result<Option<ObjectId>, String>; |
| 85 | |
| 86 | /// Points the branch at its first changeset. |
| 87 | fn create_branch(&mut self, root: ObjectId) -> Result<(), String>; |
| 88 | |
| 89 | /// Runs the lander's serialized section for one request. |
| 90 | fn land(&mut self, request: &LandRequest) -> Result<Landed, String>; |
| 91 | |
| 92 | /// Every move of the branch the op log recorded, oldest first. |
| 93 | fn branch_moves(&self) -> Result<Vec<Move>, String>; |
| 94 | |
| 95 | /// Checks the store at the end of a run and opens it again, as a new |
| 96 | /// process would. Returns whether anything was opened again: objects in |
| 97 | /// memory stay as they are. |
| 98 | fn reopen(&mut self) -> Result<bool, String>; |
| 99 | } |
| 100 | |
| 101 | /// Objects in memory, and a simulated ref with its own op log. |
| 102 | #[derive(Debug, Default)] |
| 103 | pub struct MemoryBackend { |
| 104 | objects: MemoryObjects, |
| 105 | main: Option<ObjectId>, |
| 106 | moves: Vec<Move>, |
| 107 | } |
| 108 | |
| 109 | impl MemoryBackend { |
| 110 | /// An empty store and no branch. |
| 111 | pub fn new() -> Self { |
| 112 | Self::default() |
| 113 | } |
| 114 | |
| 115 | /// Moves the branch from `old` to `new`, if it is still at `old`. |
| 116 | fn compare_and_swap( |
| 117 | &mut self, |
| 118 | old: Option<ObjectId>, |
| 119 | new: Option<ObjectId>, |
| 120 | ) -> Result<(), String> { |
| 121 | if self.main != old { |
| 122 | return Err(format!( |
| 123 | "compare-and-swap of {MAIN} failed: expected {old:?}, found {:?}", |
| 124 | self.main |
| 125 | )); |
| 126 | } |
| 127 | self.main = new; |
| 128 | self.moves.push((old, new)); |
| 129 | Ok(()) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | impl Backend for MemoryBackend { |
| 134 | type Objects = MemoryObjects; |
| 135 | |
| 136 | fn name(&self) -> &'static str { |
| 137 | "memory" |
| 138 | } |
| 139 | |
| 140 | fn objects(&self) -> &MemoryObjects { |
| 141 | &self.objects |
| 142 | } |
| 143 | |
| 144 | fn agent_objects(&self, _agent: usize) -> &MemoryObjects { |
| 145 | &self.objects |
| 146 | } |
| 147 | |
| 148 | fn agent_sync(&self, _agent: usize) -> Result<(), String> { |
| 149 | Ok(()) |
| 150 | } |
| 151 | |
| 152 | fn head(&self) -> Result<Option<ObjectId>, String> { |
| 153 | Ok(self.main) |
| 154 | } |
| 155 | |
| 156 | fn agent_head(&self, _agent: usize) -> Result<Option<ObjectId>, String> { |
| 157 | Ok(self.main) |
| 158 | } |
| 159 | |
| 160 | fn create_branch(&mut self, root: ObjectId) -> Result<(), String> { |
| 161 | self.compare_and_swap(None, Some(root)) |
| 162 | } |
| 163 | |
| 164 | fn land(&mut self, request: &LandRequest) -> Result<Landed, String> { |
| 165 | // The serialized section: nothing else touches the branch until it |
| 166 | // returns. |
| 167 | let head = self.main; |
| 168 | let outcome = land( |
| 169 | &self.objects, |
| 170 | head, |
| 171 | request.change, |
| 172 | request.committer.clone(), |
| 173 | ) |
| 174 | .map_err(|error| format!("land: {error}"))?; |
| 175 | let mut moved = None; |
| 176 | if !request.crash |
| 177 | && let Some(new) = target(&outcome) |
| 178 | { |
| 179 | self.compare_and_swap(head, Some(new))?; |
| 180 | moved = Some(new); |
| 181 | } |
| 182 | Ok(Landed { |
| 183 | head, |
| 184 | outcome, |
| 185 | moved, |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | fn branch_moves(&self) -> Result<Vec<Move>, String> { |
| 190 | Ok(self.moves.clone()) |
| 191 | } |
| 192 | |
| 193 | fn reopen(&mut self) -> Result<bool, String> { |
| 194 | Ok(false) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Why the lander's transaction records nothing. |
| 199 | #[derive(Debug)] |
| 200 | enum Abort { |
| 201 | /// The outcome does not move the branch. |
| 202 | Unmoved, |
| 203 | /// The lander crashed before the compare-and-swap. |
| 204 | Crash, |
| 205 | /// The engine failed. |
| 206 | Engine(braid_engine::Error), |
| 207 | } |
| 208 | |
| 209 | /// The real local store in a directory: one handle for the lander and one for |
| 210 | /// each agent, as separate processes would have. |
| 211 | #[derive(Debug)] |
| 212 | pub struct StoreBackend { |
| 213 | dir: PathBuf, |
| 214 | options: Options, |
| 215 | lander: Store, |
| 216 | agents: Vec<Store>, |
| 217 | } |
| 218 | |
| 219 | impl StoreBackend { |
| 220 | /// Creates a store in `dir` with a handle for each of `agents` agents. |
| 221 | pub fn create(dir: &Path, agents: usize) -> Result<Self, String> { |
| 222 | let options = Options { |
| 223 | // Small, so that runs seal segments and write checkpoints. |
| 224 | segment_size: 256 << 10, |
| 225 | checkpoint_interval: 8, |
| 226 | ..Options::default() |
| 227 | }; |
| 228 | let lander = Store::init(dir, options.clone()).map_err(|error| error.to_string())?; |
| 229 | let mut backend = StoreBackend { |
| 230 | dir: dir.to_path_buf(), |
| 231 | options, |
| 232 | lander, |
| 233 | agents: Vec::new(), |
| 234 | }; |
| 235 | backend.open_agents(agents)?; |
| 236 | Ok(backend) |
| 237 | } |
| 238 | |
| 239 | fn open(&self) -> Result<Store, String> { |
| 240 | Store::open(&self.dir, self.options.clone()).map_err(|error| error.to_string()) |
| 241 | } |
| 242 | |
| 243 | fn open_agents(&mut self, count: usize) -> Result<(), String> { |
| 244 | self.agents.clear(); |
| 245 | for _ in 0..count { |
| 246 | let store = self.open()?; |
| 247 | self.agents.push(store); |
| 248 | } |
| 249 | Ok(()) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | impl Backend for StoreBackend { |
| 254 | type Objects = Store; |
| 255 | |
| 256 | fn name(&self) -> &'static str { |
| 257 | "store" |
| 258 | } |
| 259 | |
| 260 | fn objects(&self) -> &Store { |
| 261 | &self.lander |
| 262 | } |
| 263 | |
| 264 | fn agent_objects(&self, agent: usize) -> &Store { |
| 265 | &self.agents[agent] |
| 266 | } |
| 267 | |
| 268 | fn agent_sync(&self, agent: usize) -> Result<(), String> { |
| 269 | self.agents[agent].sync().map_err(|error| error.to_string()) |
| 270 | } |
| 271 | |
| 272 | fn head(&self) -> Result<Option<ObjectId>, String> { |
| 273 | let refs = self.lander.refs().map_err(|error| error.to_string())?; |
| 274 | Ok(refs.get(MAIN)) |
| 275 | } |
| 276 | |
| 277 | fn agent_head(&self, agent: usize) -> Result<Option<ObjectId>, String> { |
| 278 | let refs = self.agents[agent] |
| 279 | .refs() |
| 280 | .map_err(|error| error.to_string())?; |
| 281 | Ok(refs.get(MAIN)) |
| 282 | } |
| 283 | |
| 284 | fn create_branch(&mut self, root: ObjectId) -> Result<(), String> { |
| 285 | self.lander |
| 286 | .transact(LANDER, "create main", |refs| { |
| 287 | Ok::<_, String>(vec![RefUpdate::new(MAIN, refs.get(MAIN), Some(root))]) |
| 288 | }) |
| 289 | .map(|_| ()) |
| 290 | .map_err(|error| error.to_string()) |
| 291 | } |
| 292 | |
| 293 | fn land(&mut self, request: &LandRequest) -> Result<Landed, String> { |
| 294 | let mut seen = None; |
| 295 | let lander = &self.lander; |
| 296 | let result = lander.transact(LANDER, &request.description, |refs| { |
| 297 | let head = refs.get(MAIN); |
| 298 | let outcome = land(lander, head, request.change, request.committer.clone()) |
| 299 | .map_err(Abort::Engine)?; |
| 300 | let new = target(&outcome); |
| 301 | seen = Some((head, outcome)); |
| 302 | if request.crash { |
| 303 | return Err(Abort::Crash); |
| 304 | } |
| 305 | match new { |
| 306 | Some(new) => Ok(vec![RefUpdate::new(MAIN, head, Some(new))]), |
| 307 | None => Err(Abort::Unmoved), |
| 308 | } |
| 309 | }); |
| 310 | let landed = |seen: Option<(Option<ObjectId>, LandOutcome)>, moved| { |
| 311 | let (head, outcome) = seen.ok_or("the transaction did not run its closure")?; |
| 312 | Ok(Landed { |
| 313 | head, |
| 314 | outcome, |
| 315 | moved, |
| 316 | }) |
| 317 | }; |
| 318 | match result { |
| 319 | Ok(op) => { |
| 320 | let (head, outcome) = seen.ok_or("the transaction did not run its closure")?; |
| 321 | let moved = target(&outcome); |
| 322 | let expected = [RefUpdate::new(MAIN, head, moved)]; |
| 323 | if op.updates != expected { |
| 324 | return Err(format!( |
| 325 | "operation {} records {:?}, not {expected:?}", |
| 326 | op.seq, op.updates |
| 327 | )); |
| 328 | } |
| 329 | Ok(Landed { |
| 330 | head, |
| 331 | outcome, |
| 332 | moved, |
| 333 | }) |
| 334 | } |
| 335 | Err(TransactError::Aborted(Abort::Unmoved)) => landed(seen, None), |
| 336 | Err(TransactError::Aborted(Abort::Crash)) => { |
| 337 | // The process died: its handle goes, and a new one opens the |
| 338 | // store again. |
| 339 | self.lander = self.open()?; |
| 340 | landed(seen, None) |
| 341 | } |
| 342 | Err(TransactError::Aborted(Abort::Engine(error))) => Err(format!("land: {error}")), |
| 343 | Err(TransactError::Store(error)) => Err(format!("transaction: {error}")), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | fn branch_moves(&self) -> Result<Vec<Move>, String> { |
| 348 | let mut ops = self |
| 349 | .lander |
| 350 | .log(usize::MAX) |
| 351 | .map_err(|error| error.to_string())?; |
| 352 | ops.reverse(); |
| 353 | let mut moves = Vec::new(); |
| 354 | for op in ops { |
| 355 | for update in op.updates { |
| 356 | if update.name == MAIN { |
| 357 | moves.push((update.old, update.new)); |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | Ok(moves) |
| 362 | } |
| 363 | |
| 364 | fn reopen(&mut self) -> Result<bool, String> { |
| 365 | let report = self.lander.fsck().map_err(|error| error.to_string())?; |
| 366 | if !report.is_clean() { |
| 367 | return Err(format!("fsck found problems: {:?}", report.problems)); |
| 368 | } |
| 369 | let agents = self.agents.len(); |
| 370 | self.agents.clear(); |
| 371 | self.lander = self.open()?; |
| 372 | self.open_agents(agents)?; |
| 373 | Ok(true) |
| 374 | } |
| 375 | } |