Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 70.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The scheduler: agents snapshot the branch, edit, commit and ask the lander
5//! to land their changes, in an order the seed decides, with faults
6//! injected; every invariant is checked after every step.
7
8use std::collections::{BTreeMap, BTreeSet, VecDeque};
9use std::fmt;
10use std::rc::Rc;
11
12use braid_engine::{
13 Conflict, ConflictHunk, ConflictKind, LandOutcome, MergeResult, REBASED_FROM, admit, commit,
14 diff, is_ancestor, land, merge3, read_changes, read_changeset, read_tree,
15};
16use braid_format::{
17 Change, ChangeOp, Changes, Changeset, EntryKind, Kind, ObjectId, Objects, Signature,
18};
19
20use crate::backend::{Backend, LandRequest, MAIN};
21use crate::model::{
22 self, Edits, Files, Hunk, MergeCase, ModelConflict, Oracle, Rebase, TextMerge, Value, show,
23};
24use crate::ops::{self, FLAT_LIMIT, Generator, Op, WIDE};
25use crate::rng::Rng;
26use crate::trace::{Trace, short};
27
28/// How many times an agent redoes a change that keeps conflicting before it
29/// gives up on it.
30const MAX_ATTEMPTS: u32 = 6;
31
32/// How a run goes. Probabilities are per request or per change.
33#[derive(Clone, Debug)]
34pub struct Config {
35 /// Agents landing changes at the same time.
36 pub agents: usize,
37 /// Changes each agent sees through before it stops.
38 pub tasks: u32,
39 /// Probability that a run starts with a directory of about a thousand
40 /// files, on either side of the largest flat directory.
41 pub wide: f64,
42 /// Share of the steps the lander takes while requests wait.
43 pub lander_share: f64,
44 /// Probability that the lander's answer is lost on its way back.
45 pub lost_ack: f64,
46 /// Probability that a request reaches the lander twice.
47 pub duplicate: f64,
48 /// Probability that an agent sends a changeset again after it landed.
49 pub resubmit: f64,
50 /// Probability that the lander crashes after computing an outcome and
51 /// before the compare-and-swap.
52 pub crash: f64,
53 /// Probability that the lander takes a request out of order.
54 pub reorder: f64,
55 /// Probability that a new changeset is landed together with another one
56 /// built on the same base, in both orders, away from the branch.
57 pub commute: f64,
58 /// Probability that an agent copies a file from the newest head into its
59 /// change.
60 pub copy: f64,
61 /// Probability that an agent sends a change that changes nothing, rather
62 /// than dropping it.
63 pub empty: f64,
64 /// The shortest time an agent waits for an answer before it sends its
65 /// request again; the longest is six times as long.
66 pub timeout: u64,
67 /// Steps after which an unfinished run fails.
68 pub max_steps: u64,
69}
70
71impl Default for Config {
72 fn default() -> Self {
73 Config {
74 agents: 8,
75 tasks: 10,
76 wide: 0.2,
77 lander_share: 0.3,
78 lost_ack: 0.08,
79 duplicate: 0.06,
80 resubmit: 0.06,
81 crash: 0.05,
82 reorder: 0.1,
83 commute: 0.35,
84 copy: 0.08,
85 empty: 0.2,
86 timeout: 25,
87 max_steps: 200_000,
88 }
89 }
90}
91
92/// Counts of what happened, for one run or summed over many.
93#[derive(Clone, Debug, Default, PartialEq, Eq)]
94pub struct Report {
95 /// Runs.
96 pub seeds: u64,
97 /// Runs that started with the wide directory.
98 pub wide_seeds: u64,
99 /// Scheduler steps.
100 pub steps: u64,
101 /// Changesets agents committed.
102 pub commits: u64,
103 /// Requests the lander handled, retries and duplicates included.
104 pub requests: u64,
105 /// Landings that fast-forwarded the branch.
106 pub fast_forwards: u64,
107 /// Landings that rebased the change onto the head.
108 pub rebased: u64,
109 /// Paths both sides changed that a landing merged.
110 pub merged_paths: u64,
111 /// Landings whose change list was too long to be inline.
112 pub external_lists: u64,
113 /// Requests answered with "already applied".
114 pub already_applied: u64,
115 /// Requests answered with conflicts.
116 pub conflicts: u64,
117 /// Conflicts reported, by kind.
118 pub conflict_kinds: BTreeMap<String, u64>,
119 /// Answers lost on their way back.
120 pub lost_acks: u64,
121 /// Requests delivered twice.
122 pub duplicates: u64,
123 /// Changesets sent again after they landed.
124 pub resubmits: u64,
125 /// Lander crashes between the outcome and the compare-and-swap.
126 pub crashes: u64,
127 /// Requests sent again after waiting too long for an answer.
128 pub retries: u64,
129 /// Changes redone on a newer head after a conflict.
130 pub redos: u64,
131 /// Changes given up after conflicting too often.
132 pub abandoned: u64,
133 /// Pairs of changes landed in both orders.
134 pub commutations: u64,
135 /// Of those, pairs that conflicted in both orders.
136 pub commuted_conflicting: u64,
137 /// Landings that moved the wide directory across the flat limit.
138 pub wide_crossings: u64,
139}
140
141impl Report {
142 /// Landings that moved the branch.
143 pub fn landings(&self) -> u64 {
144 self.fast_forwards + self.rebased
145 }
146
147 /// Faults injected: lost answers, duplicates, resubmissions and crashes.
148 pub fn faults(&self) -> u64 {
149 self.lost_acks + self.duplicates + self.resubmits + self.crashes
150 }
151
152 /// Adds another report's counts to this one.
153 pub fn add(&mut self, other: &Report) {
154 self.seeds += other.seeds;
155 self.wide_seeds += other.wide_seeds;
156 self.steps += other.steps;
157 self.commits += other.commits;
158 self.requests += other.requests;
159 self.fast_forwards += other.fast_forwards;
160 self.rebased += other.rebased;
161 self.merged_paths += other.merged_paths;
162 self.external_lists += other.external_lists;
163 self.already_applied += other.already_applied;
164 self.conflicts += other.conflicts;
165 for (kind, count) in &other.conflict_kinds {
166 *self.conflict_kinds.entry(kind.clone()).or_default() += count;
167 }
168 self.lost_acks += other.lost_acks;
169 self.duplicates += other.duplicates;
170 self.resubmits += other.resubmits;
171 self.crashes += other.crashes;
172 self.retries += other.retries;
173 self.redos += other.redos;
174 self.abandoned += other.abandoned;
175 self.commutations += other.commutations;
176 self.commuted_conflicting += other.commuted_conflicting;
177 self.wide_crossings += other.wide_crossings;
178 }
179}
180
181impl fmt::Display for Report {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 let kinds: Vec<String> = self
184 .conflict_kinds
185 .iter()
186 .map(|(kind, count)| format!("{kind} {count}"))
187 .collect();
188 writeln!(
189 f,
190 "seeds {} ({} with the wide directory), steps {}, commits {}, requests {}",
191 self.seeds, self.wide_seeds, self.steps, self.commits, self.requests
192 )?;
193 writeln!(
194 f,
195 "landings {}: {} fast-forward, {} rebased ({} paths merged, {} external change lists)",
196 self.landings(),
197 self.fast_forwards,
198 self.rebased,
199 self.merged_paths,
200 self.external_lists
201 )?;
202 writeln!(
203 f,
204 "already applied {}, conflicts {} ({})",
205 self.already_applied,
206 self.conflicts,
207 kinds.join(", ")
208 )?;
209 writeln!(
210 f,
211 "faults {}: {} lost answers, {} duplicate requests, {} resubmissions after landing, \
212 {} lander crashes; {} retries after a timeout",
213 self.faults(),
214 self.lost_acks,
215 self.duplicates,
216 self.resubmits,
217 self.crashes,
218 self.retries
219 )?;
220 write!(
221 f,
222 "agents redid {} changes after a conflict and gave up {}; {} pairs landed in both \
223 orders ({} conflicting both ways); {} crossings of the flat directory limit",
224 self.redos,
225 self.abandoned,
226 self.commutations,
227 self.commuted_conflicting,
228 self.wide_crossings
229 )
230 }
231}
232
233/// A run that broke an invariant or disagreed with the model.
234#[derive(Clone, Debug)]
235pub struct Failure {
236 /// The seed that reproduces it.
237 pub seed: u64,
238 /// The backend it ran on.
239 pub backend: &'static str,
240 /// The step it failed at.
241 pub step: u64,
242 /// Which check failed: `I1` to `I7`, or another check of the run.
243 pub invariant: &'static str,
244 /// What went wrong.
245 pub message: String,
246 /// The events about the changesets involved.
247 pub trace: Vec<String>,
248 /// Every event of the run.
249 pub full_trace: Vec<String>,
250}
251
252impl fmt::Display for Failure {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 writeln!(
255 f,
256 "seed {} on the {} backend failed at step {}: {} ({})",
257 self.seed,
258 self.backend,
259 self.step,
260 self.invariant,
261 meaning(self.invariant)
262 )?;
263 writeln!(f, "{}", self.message)?;
264 writeln!(
265 f,
266 "replay: BRAID_SIM_SEED={} cargo test -p elffuss-braid-sim --test simulation -- --nocapture",
267 self.seed
268 )?;
269 writeln!(
270 f,
271 "events about the changesets involved ({} of {}):",
272 self.trace.len(),
273 self.full_trace.len()
274 )?;
275 for line in &self.trace {
276 writeln!(f, " {line}")?;
277 }
278 Ok(())
279 }
280}
281
282/// What a check name stands for.
283fn meaning(invariant: &str) -> &'static str {
284 match invariant {
285 "I1" => "the head only moves forward, each new head on the old one",
286 "I2" => "main's first-parent history is the sequence of landings",
287 "I3" => "no lost update: the head's tree is the model's state",
288 "I4" => "a changeset lands at most once",
289 "I5" => "a conflict leaves the head unchanged",
290 "I6" => "every changeset on main is admissible",
291 "I7" => "disjoint changes land the same in either order",
292 "model" => "the lander's answer differs from the reference model",
293 "merge" => "merge3 differs from the model's line merge",
294 "commit" => "a committed changeset differs from what the agent wrote",
295 "engine" => "the engine or the store failed",
296 "liveness" => "the run did not finish",
297 _ => "a check of the simulation",
298 }
299}
300
301/// A successful run.
302#[derive(Clone, Debug)]
303pub struct Outcome {
304 /// What happened.
305 pub report: Report,
306 /// Every event, as lines.
307 pub trace: Vec<String>,
308 /// Main's heads, oldest first: the first changeset, then one per landing.
309 pub heads: Vec<ObjectId>,
310}
311
312/// Runs one seed on `backend`.
313pub fn run<B: Backend>(seed: u64, config: &Config, backend: B) -> Result<Outcome, Failure> {
314 let mut sim = Sim::new(seed, config.clone(), backend);
315 match sim.run() {
316 Ok(()) => {
317 sim.report.seeds = 1;
318 sim.report.steps = sim.steps;
319 Ok(Outcome {
320 report: sim.report,
321 trace: sim.trace.lines(),
322 heads: sim.history.entries.iter().map(|entry| entry.head).collect(),
323 })
324 }
325 Err(fail) => Err(sim.failure(fail)),
326 }
327}
328
329/// A failed check: which, why, and the changesets it is about.
330#[derive(Debug)]
331struct Fail {
332 invariant: &'static str,
333 message: String,
334 ids: Vec<ObjectId>,
335}
336
337fn fail(invariant: &'static str, message: impl Into<String>) -> Fail {
338 Fail {
339 invariant,
340 message: message.into(),
341 ids: Vec::new(),
342 }
343}
344
345impl Fail {
346 fn about(mut self, ids: &[ObjectId]) -> Self {
347 self.ids.extend_from_slice(ids);
348 self
349 }
350}
351
352/// Turns an error of the engine or a store into a failed check.
353fn engine<E: fmt::Display>(what: &'static str) -> impl FnOnce(E) -> Fail {
354 move |error| fail("engine", format!("{what}: {error}"))
355}
356
357type Checked<T = ()> = Result<T, Fail>;
358
359/// One head of main as the model sees it.
360struct MainEntry {
361 head: ObjectId,
362 /// The request that landed it; `None` for the first changeset.
363 request: Option<ObjectId>,
364 state: Rc<Files>,
365 /// The oracle's root tree of `state`.
366 root: ObjectId,
367 /// Files in the wide directory.
368 wide: usize,
369}
370
371/// Main's history as the model sees it.
372#[derive(Default)]
373struct History {
374 entries: Vec<MainEntry>,
375 index: BTreeMap<ObjectId, usize>,
376 /// Entries up to this one were checked by walking first parents.
377 verified: usize,
378}
379
380impl History {
381 fn push(&mut self, entry: MainEntry) {
382 self.index.insert(entry.head, self.entries.len());
383 self.entries.push(entry);
384 }
385
386 fn last(&self) -> &MainEntry {
387 self.entries
388 .last()
389 .expect("main always has a first changeset")
390 }
391
392 fn state(&self, head: ObjectId) -> Checked<Rc<Files>> {
393 match self.index.get(&head) {
394 Some(at) => Ok(Rc::clone(&self.entries[*at].state)),
395 None => {
396 Err(fail("I2", format!("{} is not a head main had", short(head))).about(&[head]))
397 }
398 }
399 }
400
401 fn contains(&self, id: &ObjectId) -> bool {
402 self.index.contains_key(id)
403 }
404}
405
406/// What an agent is doing.
407enum Phase {
408 /// Between changes.
409 Idle,
410 /// Editing on a snapshot; committing and sending come next.
411 Editing(Edit),
412 /// Waiting for the lander's answer about a changeset.
413 Waiting { change: ObjectId, deadline: u64 },
414 /// Done.
415 Finished,
416}
417
418/// An edit in progress.
419struct Edit {
420 base: ObjectId,
421 base_state: Rc<Files>,
422 ops: Vec<Op>,
423 state: Files,
424 /// Conflicts this change has met so far.
425 attempt: u32,
426}
427
428/// The lander's answer.
429#[derive(Clone, Copy, Debug)]
430enum Answer {
431 Landed,
432 AlreadyApplied,
433 Conflicts,
434}
435
436struct Reply {
437 change: ObjectId,
438 answer: Answer,
439}
440
441struct Agent {
442 name: String,
443 phase: Phase,
444 wake_at: u64,
445 done: u32,
446 mailbox: VecDeque<Reply>,
447}
448
449/// How a request came to be sent.
450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
451enum Delivery {
452 First,
453 Retry,
454 Duplicate,
455 Resubmit,
456}
457
458impl Delivery {
459 fn name(self) -> &'static str {
460 match self {
461 Delivery::First => "first time",
462 Delivery::Retry => "retry after a timeout",
463 Delivery::Duplicate => "duplicate delivery",
464 Delivery::Resubmit => "again after it landed",
465 }
466 }
467}
468
469struct Message {
470 change: ObjectId,
471 agent: usize,
472 delivery: Delivery,
473}
474
475/// A changeset an agent committed and asked to land.
476struct Request {
477 agent: usize,
478 base: ObjectId,
479 base_state: Rc<Files>,
480 state: Rc<Files>,
481 ops: Vec<Op>,
482 edits: Edits,
483 attempt: u32,
484 /// The head of main it became, once it landed.
485 landed: Option<ObjectId>,
486}
487
488/// What the model says landing a request gives.
489enum Expect {
490 /// The request landed already, as this head.
491 Landed(ObjectId),
492 /// The base is the head: the branch moves to the change itself.
493 FastForward(Rc<Files>),
494 /// The head already has everything the change does.
495 Unchanged,
496 /// The change is rebased onto the head.
497 Rebased {
498 state: Files,
499 resolved: Edits,
500 merged: Vec<Vec<u8>>,
501 },
502 /// The change conflicts with the head.
503 Conflicts {
504 conflicts: Vec<ModelConflict>,
505 base: Rc<Files>,
506 ours: Rc<Files>,
507 theirs: Rc<Files>,
508 },
509}
510
511impl Expect {
512 fn describe(&self) -> String {
513 match self {
514 Expect::Landed(at) => format!("already applied (it landed as {})", short(*at)),
515 Expect::FastForward(_) => "a fast-forward".to_owned(),
516 Expect::Unchanged => "already applied (the head has everything it does)".to_owned(),
517 Expect::Rebased { merged, .. } if merged.is_empty() => "a rebase".to_owned(),
518 Expect::Rebased { merged, .. } => format!("a rebase merging {}", show_paths(merged)),
519 Expect::Conflicts { conflicts, .. } => format!(
520 "conflicts: {}",
521 conflicts
522 .iter()
523 .map(|c| format!("{} {}", c.code, show(&c.path)))
524 .collect::<Vec<_>>()
525 .join(", ")
526 ),
527 }
528 }
529}
530
531/// A conflict in a form both the engine's and the model's map to.
532#[derive(Debug, PartialEq, Eq)]
533struct ConflictView {
534 path: Vec<u8>,
535 code: &'static str,
536 detail: Vec<u8>,
537 base: Option<EntryKind>,
538 ours: Option<EntryKind>,
539 theirs: Option<EntryKind>,
540 hunks: Vec<Hunk>,
541}
542
543impl ConflictView {
544 fn of(conflict: &Conflict) -> Self {
545 let (detail, hunks) = match &conflict.kind {
546 ConflictKind::DirectoryRemoved { directory } => (directory.clone(), Vec::new()),
547 ConflictKind::Case { existing } => (existing.clone(), Vec::new()),
548 ConflictKind::Content { hunks } => (Vec::new(), hunks.iter().map(hunk).collect()),
549 _ => (Vec::new(), Vec::new()),
550 };
551 ConflictView {
552 path: conflict.path.clone(),
553 code: conflict.kind.code(),
554 detail,
555 base: conflict.base.clone(),
556 ours: conflict.ours.clone(),
557 theirs: conflict.theirs.clone(),
558 hunks,
559 }
560 }
561
562 fn line(&self) -> String {
563 let mut line = format!("{} {}", self.code, show(&self.path));
564 if !self.detail.is_empty() {
565 line.push_str(&format!(" ({})", show(&self.detail)));
566 }
567 line.push_str(&format!(
568 " base {}, ours {}, theirs {}",
569 show_entry(self.base.as_ref()),
570 show_entry(self.ours.as_ref()),
571 show_entry(self.theirs.as_ref())
572 ));
573 if !self.hunks.is_empty() {
574 line.push_str(&format!(", hunks {:?}", self.hunks));
575 }
576 line
577 }
578}
579
580fn hunk(hunk: &ConflictHunk) -> Hunk {
581 Hunk {
582 base: (hunk.base.lines.clone(), hunk.base.text.clone()),
583 ours: (hunk.ours.lines.clone(), hunk.ours.text.clone()),
584 theirs: (hunk.theirs.lines.clone(), hunk.theirs.text.clone()),
585 }
586}
587
588struct Sim<B: Backend> {
589 seed: u64,
590 config: Config,
591 rng: Rng,
592 generator: Generator,
593 backend: B,
594 oracle: Oracle,
595 history: History,
596 agents: Vec<Agent>,
597 inbox: VecDeque<Message>,
598 requests: BTreeMap<ObjectId, Request>,
599 /// Requests by base, for pairs to land in both orders.
600 by_base: BTreeMap<ObjectId, Vec<ObjectId>>,
601 /// The head of main after the landings so far.
602 head: ObjectId,
603 /// The head the last full check covered.
604 checked: Option<ObjectId>,
605 /// Simulated time.
606 now: u64,
607 steps: u64,
608 trace: Trace,
609 report: Report,
610}
611
612impl<B: Backend> Sim<B> {
613 fn new(seed: u64, config: Config, backend: B) -> Self {
614 let agents = (0..config.agents)
615 .map(|a| Agent {
616 name: format!("agent-{a}"),
617 phase: Phase::Idle,
618 wake_at: 0,
619 done: 0,
620 mailbox: VecDeque::new(),
621 })
622 .collect();
623 Sim {
624 seed,
625 config,
626 rng: Rng::new(seed),
627 generator: Generator::default(),
628 backend,
629 oracle: Oracle::default(),
630 history: History::default(),
631 agents,
632 inbox: VecDeque::new(),
633 requests: BTreeMap::new(),
634 by_base: BTreeMap::new(),
635 head: ObjectId::from_bytes([0; 32]),
636 checked: None,
637 now: 0,
638 steps: 0,
639 trace: Trace::default(),
640 report: Report::default(),
641 }
642 }
643
644 fn event(&mut self, actor: &str, text: String, ids: &[ObjectId]) {
645 self.trace.push(self.steps, self.now, actor, text, ids);
646 }
647
648 fn agent_event(&mut self, a: usize, text: String, ids: &[ObjectId]) {
649 let name = self.agents[a].name.clone();
650 self.event(&name, text, ids);
651 }
652
653 fn run(&mut self) -> Checked {
654 self.setup()?;
655 self.check_step()?;
656 while !self.finished() {
657 if self.steps >= self.config.max_steps {
658 return Err(fail(
659 "liveness",
660 format!("not finished after {} steps", self.steps),
661 ));
662 }
663 self.step()?;
664 self.check_step()?;
665 }
666 self.finish()
667 }
668
669 fn finished(&self) -> bool {
670 self.inbox.is_empty()
671 && self
672 .agents
673 .iter()
674 .all(|agent| matches!(agent.phase, Phase::Finished))
675 }
676
677 /// Commits the initial state and points main at it.
678 fn setup(&mut self) -> Checked {
679 let wide = self.rng.chance(self.config.wide);
680 if wide {
681 self.report.wide_seeds += 1;
682 }
683 let files = self.generator.initial(&mut self.rng, wide);
684 let edits = model::change_list(&Files::new(), &files);
685 let author = signature("setup", 0);
686 let objects = self.backend.objects();
687 for value in files.values() {
688 objects
689 .put(Kind::Blob, value.content())
690 .map_err(engine("store a blob"))?;
691 }
692 let root = commit(
693 objects,
694 Vec::new(),
695 model::to_changes(&edits),
696 author.clone(),
697 author,
698 b"the initial state\n".to_vec(),
699 Vec::new(),
700 )
701 .map_err(engine("commit the initial state"))?;
702 admit(objects, root, |_| false).map_err(|error| {
703 fail(
704 "I6",
705 format!("the first changeset is not admissible: {error}"),
706 )
707 })?;
708 let tree = read_changeset(objects, root)
709 .map_err(engine("read the first changeset"))?
710 .root;
711 let expected = self.oracle.root(&files);
712 if tree != expected {
713 let differences = describe_tree(objects, tree, &files);
714 return Err(fail(
715 "commit",
716 format!("the first tree differs from the initial state:\n{differences}"),
717 ));
718 }
719 self.backend
720 .create_branch(root)
721 .map_err(engine("create the branch"))?;
722 let count = files.len();
723 let wide = wide_count(&files);
724 self.history.push(MainEntry {
725 head: root,
726 request: None,
727 state: Rc::new(files),
728 root: expected,
729 wide,
730 });
731 self.head = root;
732 self.event(
733 "setup",
734 format!(
735 "{MAIN} starts at {} with {count} files, {wide} in the wide directory",
736 short(root)
737 ),
738 &[root],
739 );
740 for agent in &mut self.agents {
741 agent.wake_at = self.rng.below(8) as u64;
742 }
743 Ok(())
744 }
745
746 fn awake(&self) -> Vec<usize> {
747 (0..self.agents.len())
748 .filter(|&a| {
749 let agent = &self.agents[a];
750 !matches!(agent.phase, Phase::Finished) && agent.wake_at <= self.now
751 })
752 .collect()
753 }
754
755 /// One step: the lander handles a request, or one agent acts.
756 fn step(&mut self) -> Checked {
757 self.steps += 1;
758 self.now += 1;
759 let mut awake = self.awake();
760 if awake.is_empty() && self.inbox.is_empty() {
761 // Nobody can act yet: skip ahead to the next agent to wake.
762 let next = self
763 .agents
764 .iter()
765 .filter(|agent| !matches!(agent.phase, Phase::Finished))
766 .map(|agent| agent.wake_at)
767 .min()
768 .unwrap_or(self.now);
769 self.now = self.now.max(next);
770 awake = self.awake();
771 }
772 let lander = !self.inbox.is_empty()
773 && (awake.is_empty() || self.rng.chance(self.config.lander_share));
774 if lander {
775 self.lander_step()
776 } else {
777 let a = awake[self.rng.below(awake.len())];
778 self.agent_step(a)
779 }
780 }
781
782 fn agent_step(&mut self, a: usize) -> Checked {
783 match std::mem::replace(&mut self.agents[a].phase, Phase::Idle) {
784 Phase::Idle => self.start_change(a),
785 Phase::Editing(edit) => self.commit_change(a, edit),
786 Phase::Waiting { change, deadline } => self.wait(a, change, deadline),
787 Phase::Finished => {
788 self.agents[a].phase = Phase::Finished;
789 Ok(())
790 }
791 }
792 }
793
794 /// The head as an agent reads it, which must be main's.
795 fn agent_head(&self, a: usize) -> Checked<ObjectId> {
796 let head = self
797 .backend
798 .agent_head(a)
799 .map_err(engine("read the head"))?;
800 if head != Some(self.head) {
801 return Err(fail(
802 "I2",
803 format!(
804 "{} reads {MAIN} at {head:?}; the landings end at {}",
805 self.agents[a].name,
806 short(self.head)
807 ),
808 ));
809 }
810 Ok(self.head)
811 }
812
813 /// A pause: mostly short, sometimes long enough for bases to go stale.
814 fn think_time(&mut self) -> u64 {
815 let pause = match self.rng.below(20) {
816 0..=13 => self.rng.below(4),
817 14..=18 => self.rng.range(4, 60),
818 _ => self.rng.range(60, 400),
819 };
820 pause as u64
821 }
822
823 /// How long an agent waits for an answer before it sends again.
824 fn timeout(&mut self) -> u64 {
825 let shortest = self.config.timeout.max(1) as usize;
826 self.rng.range(shortest, shortest * 6) as u64
827 }
828
829 /// Takes a snapshot of main and plans a change on it.
830 fn start_change(&mut self, a: usize) -> Checked {
831 if self.agents[a].done >= self.config.tasks {
832 self.agents[a].phase = Phase::Finished;
833 self.agent_event(a, "finished".to_owned(), &[]);
834 return Ok(());
835 }
836 let head = self.agent_head(a)?;
837 let base_state = self.history.state(head)?;
838 let (ops, state) = self.generator.change(&mut self.rng, &base_state);
839 self.agent_event(
840 a,
841 format!(
842 "snapshot of {MAIN} at {}, plans {} edits",
843 short(head),
844 ops.len()
845 ),
846 &[head],
847 );
848 self.agents[a].phase = Phase::Editing(Edit {
849 base: head,
850 base_state,
851 ops,
852 state,
853 attempt: 0,
854 });
855 self.agents[a].wake_at = self.now + self.think_time();
856 Ok(())
857 }
858
859 /// Commits the change on its snapshot and asks the lander to land it.
860 fn commit_change(&mut self, a: usize, mut edit: Edit) -> Checked {
861 if self.rng.chance(self.config.copy) {
862 // Take a file as it is on the newest head.
863 let latest = Rc::clone(&self.history.last().state);
864 let files: Vec<(&Vec<u8>, &Value)> = latest
865 .iter()
866 .filter(|(path, _)| !model::inside(WIDE, path))
867 .collect();
868 if !files.is_empty() {
869 let (path, value) = files[self.rng.below(files.len())];
870 let op = Op::Write {
871 path: path.clone(),
872 value: value.clone(),
873 };
874 ops::apply(&mut edit.state, &op);
875 edit.ops.push(op);
876 }
877 }
878 let edits = model::change_list(&edit.base_state, &edit.state);
879 if edits.is_empty() && !self.rng.chance(self.config.empty) {
880 self.agents[a].done += 1;
881 self.agents[a].wake_at = self.now + self.think_time();
882 self.agent_event(a, "has nothing to change".to_owned(), &[]);
883 return Ok(());
884 }
885 let name = self.agents[a].name.clone();
886 let author = signature(&name, self.now);
887 let message = format!("{name}: change {}\n", self.agents[a].done + 1).into_bytes();
888 let objects = self.backend.agent_objects(a);
889 for (_, value) in &edits {
890 if let Some(value) = value {
891 objects
892 .put(Kind::Blob, value.content())
893 .map_err(engine("store a blob"))?;
894 }
895 }
896 let change = commit(
897 objects,
898 vec![edit.base],
899 model::to_changes(&edits),
900 author.clone(),
901 author,
902 message,
903 Vec::new(),
904 )
905 .map_err(engine("commit"))?;
906 self.backend
907 .agent_sync(a)
908 .map_err(engine("sync an agent's objects"))?;
909 if self.requests.contains_key(&change) {
910 return Err(fail(
911 "commit",
912 format!("{} was committed twice", short(change)),
913 ));
914 }
915 self.report.commits += 1;
916 let summary = show_edits(&edit.base_state, &edits);
917 self.agent_event(
918 a,
919 format!(
920 "commit {} on {}: {summary}",
921 short(change),
922 short(edit.base)
923 ),
924 &[change, edit.base],
925 );
926 // Changes to the wide directory make every check read and rebuild
927 // it; check a quarter of them.
928 if !touches_wide(&edits) || self.rng.chance(0.25) {
929 self.check_commit(change, edit.base, &edit.state, &edits)?;
930 }
931 self.requests.insert(
932 change,
933 Request {
934 agent: a,
935 base: edit.base,
936 base_state: edit.base_state,
937 state: Rc::new(edit.state),
938 ops: edit.ops,
939 edits,
940 attempt: edit.attempt,
941 landed: None,
942 },
943 );
944 self.by_base.entry(edit.base).or_default().push(change);
945 if self.rng.chance(self.config.commute) {
946 self.commute(change)?;
947 }
948 self.send(a, change, Delivery::First);
949 let deadline = self.now + self.timeout();
950 self.agents[a].phase = Phase::Waiting { change, deadline };
951 self.agents[a].wake_at = deadline;
952 Ok(())
953 }
954
955 /// What a store checks before it accepts a changeset, and that the
956 /// changeset is what the agent meant.
957 fn check_commit(
958 &mut self,
959 change: ObjectId,
960 base: ObjectId,
961 state: &Files,
962 edits: &Edits,
963 ) -> Checked {
964 let objects = self.backend.objects();
965 admit(objects, change, |id| self.history.contains(id)).map_err(|error| {
966 fail(
967 "I6",
968 format!(
969 "the committed changeset {} is not admissible: {error}",
970 short(change)
971 ),
972 )
973 .about(&[change])
974 })?;
975 let changeset = read_changeset(objects, change).map_err(engine("read a changeset"))?;
976 let expected = self.oracle.root(state);
977 if changeset.root != expected {
978 let differences = describe_tree(objects, changeset.root, state);
979 return Err(fail(
980 "commit",
981 format!(
982 "the tree of {} differs from the agent's files:\n{differences}",
983 short(change)
984 ),
985 )
986 .about(&[change]));
987 }
988 let base_root = read_changeset(objects, base)
989 .map_err(engine("read a changeset"))?
990 .root;
991 let listed = diff(objects, base_root, changeset.root).map_err(engine("diff"))?;
992 let expected = model::to_changes(edits);
993 if listed != expected {
994 return Err(fail(
995 "commit",
996 format!(
997 "diff of {} against its base differs from its change list:\n diff: {}\n list: {}",
998 short(change),
999 show_changes(&listed),
1000 show_changes(&expected)
1001 ),
1002 )
1003 .about(&[change]));
1004 }
1005 Ok(())
1006 }
1007
1008 /// Puts a request in the lander's inbox; the network may deliver it
1009 /// twice.
1010 fn send(&mut self, a: usize, change: ObjectId, delivery: Delivery) {
1011 self.inbox.push_back(Message {
1012 change,
1013 agent: a,
1014 delivery,
1015 });
1016 self.agent_event(
1017 a,
1018 format!("asks to land {} ({})", short(change), delivery.name()),
1019 &[change],
1020 );
1021 if matches!(delivery, Delivery::First | Delivery::Retry)
1022 && self.rng.chance(self.config.duplicate)
1023 {
1024 self.report.duplicates += 1;
1025 self.inbox.push_back(Message {
1026 change,
1027 agent: a,
1028 delivery: Delivery::Duplicate,
1029 });
1030 self.agent_event(
1031 a,
1032 format!("the request for {} is delivered twice", short(change)),
1033 &[change],
1034 );
1035 }
1036 }
1037
1038 /// Handles the answers about the changeset the agent waits for, or sends
1039 /// it again once the wait is over.
1040 fn wait(&mut self, a: usize, change: ObjectId, deadline: u64) -> Checked {
1041 while let Some(reply) = self.agents[a].mailbox.pop_front() {
1042 if reply.change != change {
1043 continue;
1044 }
1045 return match reply.answer {
1046 Answer::Landed | Answer::AlreadyApplied => {
1047 self.agents[a].done += 1;
1048 self.agents[a].wake_at = self.now + self.think_time();
1049 if self.rng.chance(self.config.resubmit) {
1050 self.report.resubmits += 1;
1051 self.send(a, change, Delivery::Resubmit);
1052 }
1053 Ok(())
1054 }
1055 Answer::Conflicts => self.redo(a, change),
1056 };
1057 }
1058 let deadline = if self.now >= deadline {
1059 self.report.retries += 1;
1060 self.send(a, change, Delivery::Retry);
1061 self.now + self.timeout()
1062 } else {
1063 deadline
1064 };
1065 self.agents[a].phase = Phase::Waiting { change, deadline };
1066 self.agents[a].wake_at = deadline;
1067 Ok(())
1068 }
1069
1070 /// After a conflict: updates to the new head and redoes the edit there,
1071 /// or puts the change's own files over the head's.
1072 fn redo(&mut self, a: usize, change: ObjectId) -> Checked {
1073 let request = &self.requests[&change];
1074 let attempt = request.attempt + 1;
1075 let (ops, edits) = (request.ops.clone(), request.edits.clone());
1076 if attempt > MAX_ATTEMPTS {
1077 self.report.abandoned += 1;
1078 self.agents[a].done += 1;
1079 self.agent_event(
1080 a,
1081 format!("gives up on {} after {attempt} conflicts", short(change)),
1082 &[change],
1083 );
1084 return Ok(());
1085 }
1086 let head = self.agent_head(a)?;
1087 let base_state = self.history.state(head)?;
1088 let (how, ops) = if self.rng.chance(0.4) {
1089 let ops = edits
1090 .into_iter()
1091 .map(|(path, value)| match value {
1092 Some(value) => Op::Write { path, value },
1093 None => Op::Delete { path },
1094 })
1095 .collect();
1096 ("puts its own files over", ops)
1097 } else {
1098 ("redoes its edits on", self.generator.refresh(&ops))
1099 };
1100 let mut state = (*base_state).clone();
1101 for op in &ops {
1102 ops::apply(&mut state, op);
1103 }
1104 self.report.redos += 1;
1105 self.agent_event(
1106 a,
1107 format!("{} conflicted; {how} {}", short(change), short(head)),
1108 &[change, head],
1109 );
1110 self.agents[a].phase = Phase::Editing(Edit {
1111 base: head,
1112 base_state,
1113 ops,
1114 state,
1115 attempt,
1116 });
1117 self.agents[a].wake_at = self.now + self.think_time();
1118 Ok(())
1119 }
1120
1121 /// The lander takes a request and runs its serialized section.
1122 fn lander_step(&mut self) -> Checked {
1123 let at = if self.inbox.len() > 1 && self.rng.chance(self.config.reorder) {
1124 self.rng.below(self.inbox.len())
1125 } else {
1126 0
1127 };
1128 let message = self
1129 .inbox
1130 .remove(at)
1131 .expect("the lander runs only when requests wait");
1132 let change = message.change;
1133 let crash = self.rng.chance(self.config.crash);
1134 let lost = !crash && self.rng.chance(self.config.lost_ack);
1135 let head = self.head;
1136 self.report.requests += 1;
1137
1138 let expect = self.expect(change, head)?;
1139 let request = LandRequest {
1140 change,
1141 committer: signature("lander", self.now),
1142 crash,
1143 description: format!("land {}", short(change)),
1144 };
1145 let landed = self.backend.land(&request).map_err(|error| {
1146 fail("engine", format!("landing {}: {error}", short(change))).about(&[change])
1147 })?;
1148 if landed.head != Some(head) {
1149 return Err(fail(
1150 "I1",
1151 format!(
1152 "the lander read the head {:?}; the landings end at {}",
1153 landed.head,
1154 short(head)
1155 ),
1156 ));
1157 }
1158 let summary = show_outcome(&landed.outcome);
1159 let requester = self.agents[message.agent].name.clone();
1160 let text = format!(
1161 "{} from {requester} ({}) on {}: {summary}",
1162 short(change),
1163 message.delivery.name(),
1164 short(head)
1165 );
1166 let verdict = match self.judge(head, change, expect, &landed.outcome) {
1167 Ok(verdict) => verdict,
1168 Err(failed) => {
1169 self.event("lander", text, &[change, head]);
1170 return Err(failed.about(&[change, head]));
1171 }
1172 };
1173 let moves_to = if crash {
1174 None
1175 } else {
1176 verdict.as_ref().map(|(id, _)| *id)
1177 };
1178 let mut ids = vec![change, head];
1179 ids.extend(verdict.as_ref().map(|(id, _)| *id));
1180 let note = if crash {
1181 "; crashed before the compare-and-swap"
1182 } else if lost {
1183 "; the answer is lost"
1184 } else {
1185 ""
1186 };
1187 self.event("lander", format!("{text}{note}"), &ids);
1188 if landed.moved != moves_to {
1189 let invariant = if matches!(landed.outcome, LandOutcome::Conflicts(_)) {
1190 "I5"
1191 } else {
1192 "I1"
1193 };
1194 return Err(fail(
1195 invariant,
1196 format!(
1197 "the lander moved {MAIN} to {:?} after deciding {summary}",
1198 landed.moved
1199 ),
1200 )
1201 .about(&[change, head]));
1202 }
1203 if crash {
1204 self.report.crashes += 1;
1205 return Ok(());
1206 }
1207 let answer = match &landed.outcome {
1208 LandOutcome::FastForward(_) => {
1209 self.report.fast_forwards += 1;
1210 Answer::Landed
1211 }
1212 LandOutcome::Rebased { merged_paths, .. } => {
1213 self.report.rebased += 1;
1214 self.report.merged_paths += merged_paths.len() as u64;
1215 Answer::Landed
1216 }
1217 LandOutcome::AlreadyApplied => {
1218 self.report.already_applied += 1;
1219 Answer::AlreadyApplied
1220 }
1221 LandOutcome::Conflicts(conflicts) => {
1222 self.report.conflicts += 1;
1223 for conflict in conflicts {
1224 *self
1225 .report
1226 .conflict_kinds
1227 .entry(conflict.kind.code().to_owned())
1228 .or_default() += 1;
1229 }
1230 Answer::Conflicts
1231 }
1232 };
1233 if let Some((new, state)) = verdict {
1234 self.record_landing(head, change, new, state)?;
1235 }
1236 if lost {
1237 self.report.lost_acks += 1;
1238 } else {
1239 let now = self.now;
1240 let agent = &mut self.agents[message.agent];
1241 agent.mailbox.push_back(Reply { change, answer });
1242 agent.wake_at = agent.wake_at.min(now + 1);
1243 }
1244 Ok(())
1245 }
1246
1247 /// What the model says landing `change` on `head` gives.
1248 fn expect(&mut self, change: ObjectId, head: ObjectId) -> Checked<Expect> {
1249 let request = &self.requests[&change];
1250 if let Some(at) = request.landed {
1251 return Ok(Expect::Landed(at));
1252 }
1253 if request.base == head {
1254 return Ok(Expect::FastForward(Rc::clone(&request.state)));
1255 }
1256 let base = Rc::clone(&request.base_state);
1257 let theirs = Rc::clone(&request.state);
1258 let ours = self.history.state(head)?;
1259 predict(&base, &ours, &theirs)
1260 }
1261
1262 /// Compares what the lander decided with what the model expects, and
1263 /// returns where the branch moves.
1264 fn judge(
1265 &mut self,
1266 head: ObjectId,
1267 change: ObjectId,
1268 expect: Expect,
1269 outcome: &LandOutcome,
1270 ) -> Checked<Option<(ObjectId, Rc<Files>)>> {
1271 match (expect, outcome) {
1272 (Expect::Landed(_) | Expect::Unchanged, LandOutcome::AlreadyApplied) => Ok(None),
1273 (Expect::Landed(at), other) => Err(fail(
1274 "I4",
1275 format!(
1276 "{} landed already, as {}, and landing it again gave {}",
1277 short(change),
1278 short(at),
1279 show_outcome(other)
1280 ),
1281 )
1282 .about(&[at])),
1283 (Expect::FastForward(state), LandOutcome::FastForward(id)) if *id == change => {
1284 Ok(Some((change, state)))
1285 }
1286 (
1287 Expect::Rebased {
1288 state,
1289 resolved,
1290 merged,
1291 },
1292 LandOutcome::Rebased {
1293 changeset,
1294 merged_paths,
1295 },
1296 ) => {
1297 self.check_rebased(head, change, *changeset, &state, &resolved)?;
1298 if *merged_paths != merged {
1299 return Err(fail(
1300 "model",
1301 format!(
1302 "the engine merged {}, the model {}",
1303 show_paths(merged_paths),
1304 show_paths(&merged)
1305 ),
1306 ));
1307 }
1308 Ok(Some((*changeset, Rc::new(state))))
1309 }
1310 (
1311 Expect::Conflicts {
1312 conflicts,
1313 base,
1314 ours,
1315 theirs,
1316 },
1317 LandOutcome::Conflicts(found),
1318 ) => {
1319 self.check_conflicts(&conflicts, &base, &ours, &theirs, found)?;
1320 Ok(None)
1321 }
1322 (expect, outcome) => Err(fail(
1323 "model",
1324 format!(
1325 "the model expects {}, the lander answered {}",
1326 expect.describe(),
1327 show_outcome(outcome)
1328 ),
1329 )),
1330 }
1331 }
1332
1333 /// A rebased changeset: on the head, naming the change it came from, with
1334 /// the model's change list and tree.
1335 fn check_rebased(
1336 &mut self,
1337 head: ObjectId,
1338 change: ObjectId,
1339 new: ObjectId,
1340 state: &Files,
1341 resolved: &Edits,
1342 ) -> Checked {
1343 let objects = self.backend.objects();
1344 let changeset = read_changeset(objects, new).map_err(engine("read a changeset"))?;
1345 if changeset.parents.first() != Some(&head) {
1346 return Err(fail(
1347 "I1",
1348 format!(
1349 "the rebased changeset {} has the parents {}, not the head {} first",
1350 short(new),
1351 show_ids(&changeset.parents),
1352 short(head)
1353 ),
1354 ));
1355 }
1356 if rebased_from(&changeset) != Some(change) {
1357 return Err(fail(
1358 "I4",
1359 format!(
1360 "the rebased changeset {} does not name {} as the one it was rebased from",
1361 short(new),
1362 short(change)
1363 ),
1364 ));
1365 }
1366 let list = read_changes(objects, new, &changeset).map_err(engine("read a change list"))?;
1367 let expected = model::to_changes(resolved);
1368 if list.as_ref() != expected.as_slice() {
1369 return Err(fail(
1370 "model",
1371 format!(
1372 "the rebased change list differs from the model's:\n engine: {}\n model: {}",
1373 show_changes(&list),
1374 show_changes(&expected)
1375 ),
1376 ));
1377 }
1378 let root = self.oracle.root(state);
1379 if changeset.root != root {
1380 let differences = describe_tree(objects, changeset.root, state);
1381 return Err(fail(
1382 "I3",
1383 format!(
1384 "the tree of the rebased changeset {} differs from the model's state:\n{differences}",
1385 short(new)
1386 ),
1387 ));
1388 }
1389 Ok(())
1390 }
1391
1392 /// The engine's conflicts, compared with the model's: paths, kinds, the
1393 /// entries on each side, and the hunks.
1394 fn check_conflicts(
1395 &mut self,
1396 expected: &[ModelConflict],
1397 base: &Files,
1398 ours: &Files,
1399 theirs: &Files,
1400 found: &[Conflict],
1401 ) -> Checked {
1402 let mut want: Vec<ConflictView> = expected
1403 .iter()
1404 .map(|conflict| ConflictView {
1405 path: conflict.path.clone(),
1406 code: conflict.code,
1407 detail: conflict.detail.clone(),
1408 base: self.oracle.entry_at(base, &conflict.path),
1409 ours: self.oracle.entry_at(ours, &conflict.path),
1410 theirs: self.oracle.entry_at(theirs, &conflict.path),
1411 hunks: conflict.hunks.clone(),
1412 })
1413 .collect();
1414 let mut got: Vec<ConflictView> = found.iter().map(ConflictView::of).collect();
1415 let key = |view: &ConflictView| (view.path.clone(), view.code, view.detail.clone());
1416 want.sort_by_key(key);
1417 got.sort_by_key(key);
1418 if want == got {
1419 return Ok(());
1420 }
1421 let lines = |views: &[ConflictView]| {
1422 views
1423 .iter()
1424 .map(|view| format!("\n {}", view.line()))
1425 .collect::<String>()
1426 };
1427 Err(fail(
1428 "model",
1429 format!(
1430 "the conflicts differ\n engine:{}\n model:{}",
1431 lines(&got),
1432 lines(&want)
1433 ),
1434 ))
1435 }
1436
1437 /// Main moved from `old` to `new` for `change`: check the move and record
1438 /// it.
1439 fn record_landing(
1440 &mut self,
1441 old: ObjectId,
1442 change: ObjectId,
1443 new: ObjectId,
1444 state: Rc<Files>,
1445 ) -> Checked {
1446 let objects = self.backend.objects();
1447 let changeset = read_changeset(objects, new).map_err(engine("read a changeset"))?;
1448 if changeset.parents.first() != Some(&old) {
1449 return Err(fail(
1450 "I1",
1451 format!(
1452 "the new head {} has the parents {}, not the old head {} first",
1453 short(new),
1454 show_ids(&changeset.parents),
1455 short(old)
1456 ),
1457 )
1458 .about(&[new]));
1459 }
1460 if !is_ancestor(objects, old, new).map_err(engine("ancestry"))? {
1461 return Err(fail(
1462 "I1",
1463 format!(
1464 "the old head {} is not an ancestor of the new one",
1465 short(old)
1466 ),
1467 )
1468 .about(&[new]));
1469 }
1470 if let Some(at) = self.requests[&change].landed {
1471 return Err(fail(
1472 "I4",
1473 format!(
1474 "{} landed a second time, as {}; it landed before as {}",
1475 short(change),
1476 short(new),
1477 short(at)
1478 ),
1479 )
1480 .about(&[new, at]));
1481 }
1482 let origin = if new == change {
1483 Some(change)
1484 } else {
1485 rebased_from(&changeset)
1486 };
1487 if origin != Some(change) {
1488 return Err(fail(
1489 "I4",
1490 format!(
1491 "the new head {} does not say it lands {}",
1492 short(new),
1493 short(change)
1494 ),
1495 )
1496 .about(&[new]));
1497 }
1498 admit(objects, new, |id| self.history.contains(id)).map_err(|error| {
1499 fail(
1500 "I6",
1501 format!("the new head {} is not admissible: {error}", short(new)),
1502 )
1503 .about(&[new])
1504 })?;
1505 if matches!(changeset.changes, Changes::External { .. }) {
1506 self.report.external_lists += 1;
1507 }
1508 let wide = wide_count(&state);
1509 if (self.history.last().wide > FLAT_LIMIT) != (wide > FLAT_LIMIT) {
1510 self.report.wide_crossings += 1;
1511 }
1512 let root = self.oracle.root(&state);
1513 self.history.push(MainEntry {
1514 head: new,
1515 request: Some(change),
1516 state,
1517 root,
1518 wide,
1519 });
1520 if let Some(request) = self.requests.get_mut(&change) {
1521 request.landed = Some(new);
1522 }
1523 self.head = new;
1524 Ok(())
1525 }
1526
1527 /// After every step: main is where the landings left it, its history is
1528 /// the landings, and its tree is the model's state.
1529 fn check_step(&mut self) -> Checked {
1530 let actual = self.backend.head().map_err(engine("read the head"))?;
1531 if actual != Some(self.head) {
1532 return Err(fail(
1533 "I2",
1534 format!(
1535 "{MAIN} is at {actual:?}, but the landings end at {}",
1536 short(self.head)
1537 ),
1538 )
1539 .about(&[self.head]));
1540 }
1541 if self.checked == Some(self.head) {
1542 return Ok(());
1543 }
1544 self.walk_new_landings()?;
1545 let objects = self.backend.objects();
1546 let root = read_changeset(objects, self.head)
1547 .map_err(engine("read the head"))?
1548 .root;
1549 let entry = self.history.last();
1550 if root != entry.root {
1551 let differences = describe_tree(objects, root, &entry.state);
1552 return Err(fail(
1553 "I3",
1554 format!("the head's tree differs from the model's state:\n{differences}"),
1555 )
1556 .about(&[self.head]));
1557 }
1558 self.checked = Some(self.head);
1559 Ok(())
1560 }
1561
1562 /// Walks first parents from the head down to the head checked last; the
1563 /// changesets met must be the landings since.
1564 fn walk_new_landings(&mut self) -> Checked {
1565 let objects = self.backend.objects();
1566 let entries = &self.history.entries;
1567 let verified = self.history.verified;
1568 let mut current = self.head;
1569 for at in (verified + 1..entries.len()).rev() {
1570 if current != entries[at].head {
1571 return Err(fail(
1572 "I2",
1573 format!(
1574 "first parents from the head reach {} where landing {at} put {}",
1575 short(current),
1576 short(entries[at].head)
1577 ),
1578 )
1579 .about(&[current, entries[at].head]));
1580 }
1581 let changeset = read_changeset(objects, current).map_err(engine("read a changeset"))?;
1582 current = match changeset.parents.first() {
1583 Some(parent) => *parent,
1584 None => {
1585 return Err(fail(
1586 "I2",
1587 format!("{} has no parent, yet it is landing {at}", short(current)),
1588 ));
1589 }
1590 };
1591 }
1592 if current != entries[verified].head {
1593 return Err(fail(
1594 "I2",
1595 format!(
1596 "first parents from the head reach {} where main had {}",
1597 short(current),
1598 short(entries[verified].head)
1599 ),
1600 ));
1601 }
1602 self.history.verified = entries.len() - 1;
1603 Ok(())
1604 }
1605
1606 /// Lands a new changeset and another one built on the same base, by
1607 /// another agent and on unrelated paths, in both orders, away from the
1608 /// branch: both orders must agree.
1609 fn commute(&mut self, x: ObjectId) -> Checked {
1610 let request = &self.requests[&x];
1611 let base = request.base;
1612 let peer = self.by_base[&base].iter().rev().copied().find(|y| {
1613 let other = &self.requests[y];
1614 *y != x && other.agent != request.agent && unrelated(&request.edits, &other.edits)
1615 });
1616 let Some(y) = peer else {
1617 return Ok(());
1618 };
1619 // Pairs that touch the wide directory read and rebuild it several
1620 // times each; replay a quarter of them.
1621 if (touches_wide(&request.edits) || touches_wide(&self.requests[&y].edits))
1622 && !self.rng.chance(0.25)
1623 {
1624 return Ok(());
1625 }
1626 let base_state = Rc::clone(&request.base_state);
1627 let x_state = Rc::clone(&request.state);
1628 let y_state = Rc::clone(&self.requests[&y].state);
1629 let x_then_y = self.replay(base, (x, &x_state), (y, &y_state), &base_state)?;
1630 let y_then_x = self.replay(base, (y, &y_state), (x, &x_state), &base_state)?;
1631 self.report.commutations += 1;
1632 let both = [x, y, base];
1633 let text = match (x_then_y, y_then_x) {
1634 (Some(a), Some(b)) if a != b => {
1635 return Err(fail(
1636 "I7",
1637 format!(
1638 "{} and {} land in both orders but give the trees {} and {}",
1639 short(x),
1640 short(y),
1641 short(a),
1642 short(b)
1643 ),
1644 )
1645 .about(&both));
1646 }
1647 (Some(_), None) | (None, Some(_)) => {
1648 return Err(fail(
1649 "I7",
1650 format!(
1651 "{} and {} land in one order and conflict in the other ({} first: {}, {} first: {})",
1652 short(x),
1653 short(y),
1654 short(x),
1655 landed_or_not(x_then_y),
1656 short(y),
1657 landed_or_not(y_then_x)
1658 ),
1659 )
1660 .about(&both));
1661 }
1662 (Some(_), Some(_)) => "give the same tree in either order",
1663 (None, None) => {
1664 self.report.commuted_conflicting += 1;
1665 "conflict in either order"
1666 }
1667 };
1668 self.event(
1669 "check",
1670 format!("{} and {} on {} {text}", short(x), short(y), short(base)),
1671 &both,
1672 );
1673 Ok(())
1674 }
1675
1676 /// Lands `first` on `base`, then `second` on it, and returns the tree,
1677 /// or `None` if the second conflicts.
1678 fn replay(
1679 &mut self,
1680 base: ObjectId,
1681 first: (ObjectId, &Rc<Files>),
1682 second: (ObjectId, &Rc<Files>),
1683 base_state: &Rc<Files>,
1684 ) -> Checked<Option<ObjectId>> {
1685 let committer = signature("replay", self.now);
1686 let objects = self.backend.objects();
1687 match land(objects, Some(base), first.0, committer.clone()) {
1688 Ok(LandOutcome::FastForward(id)) if id == first.0 => {}
1689 Ok(other) => {
1690 return Err(fail(
1691 "model",
1692 format!(
1693 "{} built on {} lands on it as {}, not as a fast-forward",
1694 short(first.0),
1695 short(base),
1696 show_outcome(&other)
1697 ),
1698 ));
1699 }
1700 Err(error) => return Err(engine("land")(error)),
1701 }
1702 let outcome = land(objects, Some(first.0), second.0, committer).map_err(engine("land"))?;
1703 let expect = predict(base_state, first.1, second.1)?;
1704 self.judge(first.0, second.0, expect, &outcome)
1705 .map_err(|failed| failed.about(&[first.0, second.0]))?;
1706 let objects = self.backend.objects();
1707 let root_of = |id: ObjectId| -> Checked<ObjectId> {
1708 Ok(read_changeset(objects, id)
1709 .map_err(engine("read a changeset"))?
1710 .root)
1711 };
1712 match &outcome {
1713 LandOutcome::Rebased { changeset, .. } => Ok(Some(root_of(*changeset)?)),
1714 LandOutcome::AlreadyApplied => Ok(Some(root_of(first.0)?)),
1715 _ => Ok(None),
1716 }
1717 }
1718
1719 /// Checks at the end of a run, after the store is opened again: the op
1720 /// log moved main through exactly the landings, main's whole history is
1721 /// those landings, each request at most once, every changeset admissible,
1722 /// and the last tree is the model's.
1723 fn finish(&mut self) -> Checked {
1724 let heads: Vec<ObjectId> = self.history.entries.iter().map(|e| e.head).collect();
1725 let mut expected = vec![(None, Some(heads[0]))];
1726 expected.extend(heads.windows(2).map(|pair| (Some(pair[0]), Some(pair[1]))));
1727 let moves = self
1728 .backend
1729 .branch_moves()
1730 .map_err(engine("read the op log"))?;
1731 if moves != expected {
1732 return Err(fail(
1733 "I2",
1734 format!(
1735 "the op log moved {MAIN} {} times; there were {} landings",
1736 moves.len().saturating_sub(1),
1737 expected.len() - 1
1738 ),
1739 ));
1740 }
1741 let reopened = self
1742 .backend
1743 .reopen()
1744 .map_err(engine("check and reopen the store"))?;
1745 let head = self.backend.head().map_err(engine("read the head"))?;
1746 if head != Some(self.head) {
1747 return Err(fail(
1748 "I2",
1749 format!(
1750 "after reopening, {MAIN} is at {head:?}, not {}",
1751 short(self.head)
1752 ),
1753 ));
1754 }
1755
1756 let objects = self.backend.objects();
1757 let mut chain = Vec::new();
1758 let mut current = Some(self.head);
1759 while let Some(id) = current {
1760 chain.push(id);
1761 if chain.len() > heads.len() {
1762 break;
1763 }
1764 current = read_changeset(objects, id)
1765 .map_err(engine("read a changeset"))?
1766 .parents
1767 .first()
1768 .copied();
1769 }
1770 chain.reverse();
1771 if chain != heads {
1772 return Err(fail(
1773 "I2",
1774 format!(
1775 "main's first-parent history has {} changesets; there were {} landings and the first changeset",
1776 chain.len(),
1777 heads.len() - 1
1778 ),
1779 ));
1780 }
1781 let mut origins = BTreeSet::new();
1782 for entry in &self.history.entries {
1783 // Each was admitted when it landed; a store opened again must
1784 // still hold everything that took.
1785 if reopened {
1786 admit(objects, entry.head, |id| self.history.contains(id)).map_err(|error| {
1787 fail(
1788 "I6",
1789 format!("{} on main is not admissible: {error}", short(entry.head)),
1790 )
1791 })?;
1792 }
1793 let Some(request) = entry.request else {
1794 continue;
1795 };
1796 let changeset =
1797 read_changeset(objects, entry.head).map_err(engine("read a changeset"))?;
1798 let origin = if self.requests.contains_key(&entry.head) {
1799 Some(entry.head)
1800 } else {
1801 rebased_from(&changeset)
1802 };
1803 if origin != Some(request) || !origins.insert(request) {
1804 return Err(fail(
1805 "I4",
1806 format!(
1807 "{} on main lands {:?}; the model has it landing {} once",
1808 short(entry.head),
1809 origin.map(short),
1810 short(request)
1811 ),
1812 )
1813 .about(&[entry.head, request]));
1814 }
1815 }
1816 let root = read_changeset(objects, self.head)
1817 .map_err(engine("read the head"))?
1818 .root;
1819 let last = self.history.last();
1820 if root != last.root {
1821 let differences = describe_tree(objects, root, &last.state);
1822 return Err(fail(
1823 "I3",
1824 format!("after reopening, the head's tree differs from the model:\n{differences}"),
1825 ));
1826 }
1827 self.event(
1828 "check",
1829 format!(
1830 "done: {} landings, history, op log and store check out",
1831 heads.len() - 1
1832 ),
1833 &[],
1834 );
1835 Ok(())
1836 }
1837
1838 /// The report for a failed check, with the events that matter.
1839 fn failure(&self, fail: Fail) -> Failure {
1840 let mut ids: BTreeSet<ObjectId> = fail.ids.iter().copied().collect();
1841 // The requests involved and their bases, and the landings since the
1842 // oldest of those bases that touched paths related to theirs.
1843 let mut paths: Vec<&Vec<u8>> = Vec::new();
1844 let mut oldest: Option<usize> = None;
1845 let mut consider = |at: Option<&usize>| {
1846 if let Some(&at) = at {
1847 oldest = Some(oldest.map_or(at, |oldest: usize| oldest.min(at)));
1848 }
1849 };
1850 for id in &fail.ids {
1851 if let Some(request) = self.requests.get(id) {
1852 ids.insert(request.base);
1853 paths.extend(request.edits.iter().map(|(path, _)| path));
1854 consider(self.history.index.get(&request.base));
1855 }
1856 consider(self.history.index.get(id));
1857 }
1858 if let Some(from) = oldest {
1859 let entries = &self.history.entries;
1860 for at in from + 1..entries.len() {
1861 let touched = model::change_list(&entries[at - 1].state, &entries[at].state);
1862 let related = paths.is_empty()
1863 || touched
1864 .iter()
1865 .any(|(path, _)| paths.iter().any(|other| model::related(other, path)));
1866 if related || at + 1 == entries.len() {
1867 ids.insert(entries[at].head);
1868 ids.extend(entries[at].request);
1869 }
1870 }
1871 }
1872 Failure {
1873 seed: self.seed,
1874 backend: self.backend.name(),
1875 step: self.steps,
1876 invariant: fail.invariant,
1877 message: fail.message,
1878 trace: self.trace.about(&ids, 12),
1879 full_trace: self.trace.lines(),
1880 }
1881 }
1882}
1883
1884/// What the model says landing the change from `base` to `theirs` on the
1885/// head `ours` gives, with every text merge it made checked against the
1886/// engine's `merge3`.
1887fn predict(base: &Rc<Files>, ours: &Rc<Files>, theirs: &Rc<Files>) -> Checked<Expect> {
1888 let mut merges = Vec::new();
1889 let rebase =
1890 model::rebase(base, ours, theirs, &mut merges).map_err(|why| fail("model", why))?;
1891 for case in &merges {
1892 check_merge3(case)?;
1893 }
1894 Ok(match rebase {
1895 Rebase::Clean { resolved, .. } if resolved.is_empty() => Expect::Unchanged,
1896 Rebase::Clean {
1897 state,
1898 resolved,
1899 merged,
1900 } => Expect::Rebased {
1901 state,
1902 resolved,
1903 merged,
1904 },
1905 Rebase::Conflicts(conflicts) => Expect::Conflicts {
1906 conflicts,
1907 base: Rc::clone(base),
1908 ours: Rc::clone(ours),
1909 theirs: Rc::clone(theirs),
1910 },
1911 })
1912}
1913
1914/// The engine's `merge3` on the inputs of a model merge must give the same
1915/// text, or the same conflicting regions.
1916fn check_merge3(case: &MergeCase) -> Checked {
1917 let engine = merge3(&case.base, &case.ours, &case.theirs);
1918 let same = match (&engine, &case.result) {
1919 (MergeResult::Clean(a), TextMerge::Clean(b)) => a == b,
1920 (MergeResult::Conflict { hunks }, TextMerge::Conflict(expected)) => {
1921 hunks.iter().map(hunk).collect::<Vec<_>>() == *expected
1922 }
1923 _ => false,
1924 };
1925 if same {
1926 return Ok(());
1927 }
1928 let text = |bytes: &[u8]| format!("{:?}", String::from_utf8_lossy(bytes));
1929 Err(fail(
1930 "merge",
1931 format!(
1932 "merging {}:\n base {}\n ours {}\n theirs {}\n merge3: {engine:?}\n model: {:?}",
1933 show(&case.path),
1934 text(&case.base),
1935 text(&case.ours),
1936 text(&case.theirs),
1937 case.result
1938 ),
1939 ))
1940}
1941
1942/// The changeset a rebased changeset names as its origin: its one
1943/// `rebased-from` field.
1944fn rebased_from(changeset: &Changeset) -> Option<ObjectId> {
1945 let mut fields = changeset
1946 .extras
1947 .iter()
1948 .filter(|(key, _)| key.as_slice() == REBASED_FROM);
1949 let (_, value) = fields.next()?;
1950 if fields.next().is_some() {
1951 return None;
1952 }
1953 std::str::from_utf8(value).ok()?.parse().ok()
1954}
1955
1956/// Whether no path of one change list is, or is inside, a path of the other.
1957fn unrelated(a: &Edits, b: &Edits) -> bool {
1958 a.iter()
1959 .all(|(p, _)| b.iter().all(|(q, _)| !model::related(p, q)))
1960}
1961
1962/// Whether a change list touches the wide directory.
1963fn touches_wide(edits: &Edits) -> bool {
1964 edits.iter().any(|(path, _)| model::inside(WIDE, path))
1965}
1966
1967fn wide_count(files: &Files) -> usize {
1968 model::files_below(files, WIDE).count()
1969}
1970
1971fn signature(name: &str, time: u64) -> Signature {
1972 Signature {
1973 name: name.as_bytes().to_vec(),
1974 email: format!("{name}@example.org").into_bytes(),
1975 seconds: 1_700_000_000 + time as i64,
1976 offset_minutes: 0,
1977 }
1978}
1979
1980fn landed_or_not(tree: Option<ObjectId>) -> &'static str {
1981 if tree.is_some() { "lands" } else { "conflicts" }
1982}
1983
1984fn show_ids(ids: &[ObjectId]) -> String {
1985 let shown: Vec<String> = ids.iter().map(|id| short(*id)).collect();
1986 format!("[{}]", shown.join(", "))
1987}
1988
1989fn show_paths(paths: &[Vec<u8>]) -> String {
1990 let shown: Vec<String> = paths.iter().map(|path| show(path)).collect();
1991 format!("[{}]", shown.join(", "))
1992}
1993
1994fn show_outcome(outcome: &LandOutcome) -> String {
1995 match outcome {
1996 LandOutcome::FastForward(id) => format!("fast-forward to {}", short(*id)),
1997 LandOutcome::Rebased {
1998 changeset,
1999 merged_paths,
2000 } if merged_paths.is_empty() => format!("rebased as {}", short(*changeset)),
2001 LandOutcome::Rebased {
2002 changeset,
2003 merged_paths,
2004 } => format!(
2005 "rebased as {}, merging {}",
2006 short(*changeset),
2007 show_paths(merged_paths)
2008 ),
2009 LandOutcome::AlreadyApplied => "already applied".to_owned(),
2010 LandOutcome::Conflicts(conflicts) => {
2011 let shown: Vec<String> = conflicts
2012 .iter()
2013 .map(|c| format!("{} {}", c.kind.code(), show(&c.path)))
2014 .collect();
2015 format!("conflicts: {}", shown.join(", "))
2016 }
2017 }
2018}
2019
2020/// A change list for traces: `+` for a new file, `~` for a changed one, `-`
2021/// for a deleted one; long lists are cut short.
2022fn show_edits(base: &Files, edits: &Edits) -> String {
2023 const SHOWN: usize = 6;
2024 let mut parts: Vec<String> = edits
2025 .iter()
2026 .take(SHOWN)
2027 .map(|(path, value)| {
2028 let sign = match (base.contains_key(path), value) {
2029 (_, None) => '-',
2030 (true, Some(_)) => '~',
2031 (false, Some(_)) => '+',
2032 };
2033 format!("{sign}{}", show(path))
2034 })
2035 .collect();
2036 if edits.len() > SHOWN {
2037 parts.push(format!("and {} more", edits.len() - SHOWN));
2038 }
2039 if parts.is_empty() {
2040 return "no changes".to_owned();
2041 }
2042 parts.join(" ")
2043}
2044
2045fn show_changes(changes: &[Change]) -> String {
2046 let shown: Vec<String> = changes
2047 .iter()
2048 .map(|change| match &change.op {
2049 ChangeOp::Delete => format!("-{}", show(&change.path)),
2050 op => format!(
2051 "{}={}",
2052 show(&change.path),
2053 show_entry(op.to_entry().as_ref())
2054 ),
2055 })
2056 .collect();
2057 format!("[{}]", shown.join(", "))
2058}
2059
2060fn show_entry(entry: Option<&EntryKind>) -> String {
2061 match entry {
2062 None => "nothing".to_owned(),
2063 Some(EntryKind::File { blob, size }) => format!("file {} ({size} bytes)", short(*blob)),
2064 Some(EntryKind::Executable { blob, size }) => {
2065 format!("executable {} ({size} bytes)", short(*blob))
2066 }
2067 Some(EntryKind::Symlink { blob, .. }) => format!("symlink {}", short(*blob)),
2068 Some(EntryKind::Tree { tree }) => format!("directory {}", short(*tree)),
2069 Some(EntryKind::Gitlink { .. }) => "gitlink".to_owned(),
2070 }
2071}
2072
2073/// Every file of a tree, by path.
2074fn tree_files<O: Objects>(
2075 objects: &O,
2076 root: ObjectId,
2077) -> Result<BTreeMap<Vec<u8>, EntryKind>, braid_engine::Error> {
2078 let mut files = BTreeMap::new();
2079 let mut pending = vec![(Vec::new(), root)];
2080 while let Some((dir, tree)) = pending.pop() {
2081 for entry in read_tree(objects, tree)? {
2082 let path = model::join(&dir, &entry.name);
2083 match entry.kind {
2084 EntryKind::Tree { tree } => pending.push((path, tree)),
2085 kind => {
2086 files.insert(path, kind);
2087 }
2088 }
2089 }
2090 }
2091 Ok(files)
2092}
2093
2094/// The files where a tree and a state differ, for failure messages.
2095fn describe_tree<O: Objects>(objects: &O, root: ObjectId, expected: &Files) -> String {
2096 const SHOWN: usize = 12;
2097 let actual = match tree_files(objects, root) {
2098 Ok(files) => files,
2099 Err(error) => return format!(" cannot read the tree {}: {error}", short(root)),
2100 };
2101 let paths: BTreeSet<&Vec<u8>> = actual.keys().chain(expected.keys()).collect();
2102 let mut lines = Vec::new();
2103 for path in paths {
2104 let want = expected.get(path);
2105 let got = actual.get(path);
2106 if want.map(Value::entry).as_ref() == got {
2107 continue;
2108 }
2109 if lines.len() == SHOWN {
2110 lines.push(" ...".to_owned());
2111 break;
2112 }
2113 let want = want.map_or_else(|| "nothing".to_owned(), |value| format!("{value:?}"));
2114 lines.push(format!(
2115 " {}: the model has {want}, the tree has {}",
2116 show(path),
2117 show_entry(got)
2118 ));
2119 }
2120 if lines.is_empty() {
2121 return " (the same files: the trees differ in structure only)".to_owned();
2122 }
2123 lines.join("\n")
2124}