Skip to main content

vitrify_cli/run/
mainline.rs

1//! A lane's handle on mainline: which repository, which SDD, which branch,
2//! and how a commit gets there — and the lane's integration checkout, which
3//! is reset to a pristine state before every use.
4//!
5//! The SDD is pinned by its path relative to the repository root, resolved
6//! once in preflight. Every later read — in the primary checkout, a unit
7//! worktree, the integration checkout or a transaction — resolves that same
8//! path and never searches, so a repository with several SDDs is as
9//! unambiguous after preflight as it was during it.
10
11use std::path::{Path, PathBuf};
12
13use vitrify_core::claims::Op;
14use vitrify_core::model::{self, Instance, UtcTime};
15use vitrify_core::{CoreError, audit, journal, ledger, questions, yamlish};
16
17use crate::cli::ClaimArgs;
18use crate::cmd::{self, claim};
19use crate::gate::ShRunner;
20use crate::git::{Git, GitError};
21use crate::layout::Layout;
22use crate::signals;
23
24#[derive(Debug, Clone)]
25pub struct Mainline {
26    /// The primary checkout.
27    pub primary: Git,
28    pub layout: Layout,
29    /// The SDD's root relative to the repository root.
30    pub sdd_rel: PathBuf,
31    /// The SDD's name in branch, worktree and checkout names.
32    pub slug: String,
33    /// The mainline branch.
34    pub branch: String,
35    /// Publish by `git push` (origin arbitrates) rather than a local CAS.
36    pub push: bool,
37}
38
39/// A held lock on a lane's integration checkout: one user of it at a time,
40/// across processes. Unlocked when dropped.
41pub struct LaneLock(std::fs::File);
42
43impl Drop for LaneLock {
44    /// Unlock before the file closes, as a temp slot does (`gate::TmpSlot`):
45    /// left to the close, the lock can outlive its holder while a child
46    /// forked meanwhile (a worker, say) has yet to exec — and the next user
47    /// wait on it, told that another process has the checkout.
48    fn drop(&mut self) {
49        let _ = self.0.unlock();
50    }
51}
52
53/// A commit that reached mainline.
54#[derive(Debug, Clone)]
55pub struct Landed {
56    pub commit: String,
57    /// What the local branch pointed at before it was moved to the commit;
58    /// `None` when it was not moved (it has diverged from origin's).
59    pub local_was: Option<String>,
60}
61
62/// What [`Mainline::heal`] put right.
63#[derive(Debug, Default, Clone)]
64pub struct Healed {
65    /// Units whose lapsed lease was released.
66    pub leases: Vec<String>,
67    /// Units marked Stale, each with the cause.
68    pub stale: Vec<(String, String)>,
69    /// Findings the audit cannot fix itself.
70    pub other: Vec<audit::Finding>,
71    /// The published commit, when anything changed.
72    pub commit: Option<String>,
73}
74
75impl Mainline {
76    /// The mainline head (fetched first when origin arbitrates).
77    pub fn head(&self) -> Result<String, CoreError> {
78        let name = if self.push {
79            let _ = self.primary.fetch_origin(&self.branch);
80            format!("refs/remotes/origin/{}", self.branch)
81        } else {
82            format!("refs/heads/{}", self.branch)
83        };
84        self.primary.rev_parse(&name).map_err(CoreError::from)
85    }
86
87    /// The pinned SDD as `checkout` holds it.
88    pub fn sdd_in(&self, checkout: &Path) -> Result<Instance, CoreError> {
89        Instance::load(cmd::resolve_sdd_in(checkout, &self.sdd_rel)?)
90    }
91
92    /// One claim transaction on this run's SDD — published the way this run
93    /// publishes, on the SDD this run pinned, wherever the process's
94    /// working directory happens to be.
95    pub fn claim(
96        &self,
97        op: Op,
98        unit: &str,
99        holder: &str,
100        lease_minutes: i64,
101    ) -> Result<claim::ClaimOutcome, CoreError> {
102        let args = ClaimArgs {
103            unit: unit.to_string(),
104            holder: holder.to_string(),
105            lease_minutes,
106            sdd: None,
107            mainline: Some(self.branch.clone()),
108        };
109        claim::execute_pinned(
110            op,
111            &args,
112            &claim::Pinned {
113                push: self.push,
114                sdd_rel: &self.sdd_rel,
115            },
116        )
117    }
118
119    /// This lane's integration checkout.
120    pub fn checkout(&self) -> PathBuf {
121        self.layout.mainline(&self.slug)
122    }
123
124    /// Take this lane's integration checkout, waiting while another process
125    /// has it; `waiting` is called once if it must wait. `None` = the run
126    /// was interrupted while waiting.
127    pub fn lock_checkout(&self, waiting: &dyn Fn()) -> Result<Option<LaneLock>, CoreError> {
128        let path = self.layout.mainline_lock(&self.slug);
129        let io = |source| CoreError::Io {
130            path: path.clone(),
131            source,
132        };
133        if let Some(parent) = path.parent() {
134            std::fs::create_dir_all(parent).map_err(io)?;
135        }
136        let file = std::fs::OpenOptions::new()
137            .create(true)
138            .truncate(false)
139            .write(true)
140            .open(&path)
141            .map_err(io)?;
142        let mut told = false;
143        loop {
144            match file.try_lock() {
145                Ok(()) => return Ok(Some(LaneLock(file))),
146                Err(std::fs::TryLockError::WouldBlock) => {
147                    if signals::interrupted() {
148                        return Ok(None);
149                    }
150                    if !told {
151                        waiting();
152                        told = true;
153                    }
154                    std::thread::sleep(std::time::Duration::from_millis(250));
155                }
156                Err(std::fs::TryLockError::Error(e)) => return Err(io(e)),
157            }
158        }
159    }
160
161    /// Remove this lane's checkouts — integration, base and culprit probe
162    /// — giving their room back (`run.lane_cap`). Taken under the lane's
163    /// lock, so a checkout another run is using is not pulled out from
164    /// under it. A checkout that is not there is fine.
165    pub fn remove_checkouts(&self) {
166        let Ok(Some(_held)) = self.lock_checkout(&|| {}) else {
167            return;
168        };
169        let _turn = claim::tx_lock();
170        for path in [
171            self.checkout(),
172            self.layout.base_checkout(&self.slug),
173            self.layout.wt_root.join(format!("probe-{}", self.slug)),
174        ] {
175            if path.exists() {
176                let _ = self.primary.worktree_remove(&path);
177            }
178            if path.exists() {
179                let _ = std::fs::remove_dir_all(&path);
180                let _ = self.primary.worktree_remove(&path);
181            }
182        }
183    }
184
185    /// Remove this lane's integration checkout and create it again at
186    /// `rev`: whatever an earlier run left there — build outputs, a lock
187    /// file a crash left behind, a half-finished merge — is gone. Call it
188    /// holding [`Mainline::lock_checkout`], so a checkout another live run
189    /// is using is never pulled out from under it.
190    pub fn recreate_checkout(&self, rev: &str) -> Result<PathBuf, CoreError> {
191        let path = self.checkout();
192        // the checkout is one more worktree: its turn like any other
193        let _turn = claim::tx_lock();
194        if path.exists() {
195            // `worktree remove` takes git's own record of the checkout with
196            // it, a stale index lock included
197            let _ = self.primary.worktree_remove(&path);
198        }
199        if path.exists() {
200            // not a worktree git knows (or it would not let go): the
201            // directory goes, and git forgets whatever it pointed at
202            std::fs::remove_dir_all(&path).map_err(|source| CoreError::Io {
203                path: path.clone(),
204                source,
205            })?;
206            let _ = self.primary.worktree_remove(&path);
207        }
208        self.pristine(&path, rev)?;
209        Ok(path)
210    }
211
212    /// Bring the detached worktree at `path` to the mainline head, pristine
213    /// ([`Mainline::pristine`]). Returns the head.
214    pub fn sync_checkout(&self, path: &Path) -> Result<String, CoreError> {
215        let head = self.head()?;
216        self.pristine(path, &head)?;
217        Ok(head)
218    }
219
220    /// Bring the detached worktree at `path` to `rev` with nothing else in
221    /// it, creating it on first use: an unfinished merge is abandoned,
222    /// tracked files are reset, and every other file — ignored ones too:
223    /// environments, build outputs, caches — is removed. Every gate, head
224    /// check and preflight starts from here, so no result depends on what
225    /// an earlier one left behind.
226    pub fn pristine(&self, path: &Path, rev: &str) -> Result<(), CoreError> {
227        if path.join(".git").exists() {
228            let wt = self.primary.at(path);
229            // an interrupted merge would refuse the reset
230            let _ = wt.merge_abort();
231            wt.reset_hard(rev).map_err(CoreError::from)?;
232            wt.clean_all().map_err(CoreError::from)?;
233        } else {
234            if let Some(parent) = path.parent() {
235                std::fs::create_dir_all(parent).map_err(|source| CoreError::Io {
236                    path: parent.to_path_buf(),
237                    source,
238                })?;
239            }
240            self.primary
241                .worktree_add(path, rev, true)
242                .map_err(CoreError::from)?;
243        }
244        Ok(())
245    }
246
247    /// Move mainline from `base` to `new`: a push when origin arbitrates,
248    /// else the local compare-and-swap. `None` = lost the race.
249    pub fn publish(&self, new: &str, base: &str) -> Result<Option<Landed>, CoreError> {
250        let local = format!("refs/heads/{}", self.branch);
251        if self.push {
252            match self.primary.push_cas(new, &self.branch) {
253                Ok(()) => {
254                    // the local branch follows when it can
255                    let mut local_was = None;
256                    if let Some(cur) = self.primary.verify_ref(&local).map_err(CoreError::from)?
257                        && self
258                            .primary
259                            .is_ancestor(&cur, new)
260                            .map_err(CoreError::from)?
261                        && self.primary.update_ref_cas(&local, new, &cur).is_ok()
262                    {
263                        local_was = Some(cur);
264                    }
265                    Ok(Some(Landed {
266                        commit: new.to_string(),
267                        local_was,
268                    }))
269                }
270                Err(GitError::LostRace { .. }) => Ok(None),
271                Err(e) => Err(e.into()),
272            }
273        } else {
274            match self.primary.update_ref_cas(&local, new, base) {
275                Ok(()) => Ok(Some(Landed {
276                    commit: new.to_string(),
277                    local_was: Some(base.to_string()),
278                })),
279                Err(GitError::LostRace { .. }) => Ok(None),
280                Err(e) => Err(e.into()),
281            }
282        }
283    }
284
285    /// The primary checkout follows a commit that landed — when the local
286    /// branch moved with it. Call it while still holding the mainline turn.
287    pub fn follow(&self, landed: &Landed) -> Result<(), CoreError> {
288        match &landed.local_was {
289            Some(was) => claim::resync_primary(&self.primary, &self.branch, was, &landed.commit),
290            None => Ok(()),
291        }
292    }
293
294    /// Publish one orchestrator-owned mainline commit by the claim
295    /// discipline (CAS/push, never forced). `build` edits a transaction
296    /// worktree at the head and reports whether there is anything to commit;
297    /// `None` = nothing was. A lost race rebuilds on the new head — more
298    /// patiently than a claim does: these commits have no competitor for
299    /// what they change, only for the ref.
300    pub fn publish_tx(
301        &self,
302        commit_message: &str,
303        build: &dyn Fn(&Path) -> Result<bool, CoreError>,
304    ) -> Result<Option<String>, CoreError> {
305        self.layout.ensure_scratch()?;
306        let _turn = claim::tx_lock();
307        let tx = self.layout.scratch.join(format!(
308            "tx-{}-orch{}",
309            std::process::id(),
310            UtcTime::now().0
311        ));
312        let result = (|| {
313            for attempt in 0..6u64 {
314                if attempt > 0 {
315                    std::thread::sleep(std::time::Duration::from_millis(100 * attempt));
316                }
317                let base = self.head()?;
318                self.pristine(&tx, &base)?;
319                if !build(&tx)? {
320                    return Ok(None);
321                }
322                let txgit = self.primary.at(&tx);
323                txgit.add_all().map_err(CoreError::from)?;
324                txgit.commit(commit_message).map_err(CoreError::from)?;
325                let new = txgit.rev_parse("HEAD").map_err(CoreError::from)?;
326                if let Some(landed) = self.publish(&new, &base)? {
327                    self.follow(&landed)?;
328                    return Ok(Some(new));
329                }
330            }
331            Err(CoreError::refusal(
332                5,
333                format!("error: lost publish race for `{commit_message}` after retries"),
334            ))
335        })();
336        if tx.exists() {
337            let _ = self.primary.worktree_remove(&tx);
338        }
339        result
340    }
341
342    /// Put right what the audit can put right mechanically, as one mainline
343    /// commit: lapsed leases are released (`fix_leases`), and Built or
344    /// Verified units whose recorded trace no longer matches their inputs
345    /// are marked Stale with the cause (`apply_stale`) — which is what makes
346    /// a spec change that lands mid-run rebuild what it touched. Everything
347    /// else the audit found is returned in `other`.
348    pub fn heal(&self, fix_leases: bool, apply_stale: bool) -> Result<Healed, CoreError> {
349        let healed = std::cell::RefCell::new(Healed::default());
350        let message = match (fix_leases, apply_stale) {
351            (true, true) => "sdd: audit --fix-leases --apply-stale",
352            (false, true) => "sdd: audit --apply-stale",
353            _ => "sdd: audit --fix-leases",
354        };
355        let commit = self.publish_tx(message, &|tx| {
356            let inst = self.sdd_in(tx)?;
357            let (findings, edits) = audit::run(
358                &inst,
359                tx,
360                &cmd::audit_options(
361                    audit::Options {
362                        skip_rotten: true,
363                        fix_leases,
364                        apply_stale,
365                        ..Default::default()
366                    },
367                    tx,
368                    &inst,
369                ),
370                &ShRunner,
371                UtcTime::now(),
372            )?;
373            let mut h = Healed::default();
374            for edit in &edits {
375                match edit {
376                    audit::StateEdit::FixLease { unit, .. } => h.leases.push(unit.clone()),
377                    audit::StateEdit::ApplyStale { unit, cause } => {
378                        h.stale.push((unit.clone(), cause.clone()))
379                    }
380                }
381            }
382            let fixed = |f: &audit::Finding| {
383                (f.check == 7 && h.leases.contains(&f.subject))
384                    || (f.check == 5 && h.stale.iter().any(|(u, _)| u == &f.subject))
385            };
386            h.other = findings.into_iter().filter(|f| !fixed(f)).collect();
387            let changed = !edits.is_empty();
388            if changed {
389                cmd::audit::apply_edits(&inst, &edits)?;
390                let fresh = Instance::load(inst.handle())?;
391                ledger::regen(&fresh, &UtcTime::now().format_date())?;
392            }
393            *healed.borrow_mut() = h;
394            Ok(changed)
395        })?;
396        let mut healed = healed.into_inner();
397        healed.commit = commit;
398        Ok(healed)
399    }
400
401    /// Land a `Q-###` Decision-Log entry as a mainline commit (a worker
402    /// reports the question; the Decision Log is outside its write-set).
403    /// The entry says `open`, as the schema's own entries do: a question is
404    /// open unless marked resolved, and one a run has just landed is not to
405    /// be read as anything else by a tool that looks for the word.
406    pub fn land_q_entry(
407        &self,
408        q: &str,
409        unit: &str,
410        holder: &str,
411        notes: &str,
412    ) -> Result<(), CoreError> {
413        let notes = notes.replace('\n', " ");
414        self.publish_tx(&format!("sdd: record {q} (blocked {unit})"), &|tx| {
415            let inst = self.sdd_in(tx)?;
416            let entry =
417                questions::landed_entry(q, &UtcTime::now().format_date(), holder, unit, &notes);
418            match inst.shape {
419                model::Shape::Bundle => {
420                    let path = inst.root.join("decisions.md");
421                    let text = std::fs::read_to_string(&path)
422                        .unwrap_or_else(|_| "# Decisions & Open Questions\n".to_string());
423                    if text.contains(&format!("**{q}**")) {
424                        return Ok(false); // already landed
425                    }
426                    model::write_text(&path, &questions::land(&text, &entry))?;
427                }
428                model::Shape::Single => {
429                    let text = model::read_text(&inst.file)?;
430                    if text.contains(&format!("**{q}**")) {
431                        return Ok(false);
432                    }
433                    let new = match model::section_span(&text, "Decisions & Open Questions") {
434                        Some((s, e)) => format!(
435                            "{}{}{}",
436                            &text[..s],
437                            questions::land(&text[s..e], &entry),
438                            &text[e..]
439                        ),
440                        None => format!(
441                            "{}\n\n## Decisions & Open Questions\n\n{entry}",
442                            text.trim_end_matches('\n')
443                        ),
444                    };
445                    model::write_text(&inst.file, &new)?;
446                }
447            }
448            Ok(true)
449        })?;
450        Ok(())
451    }
452}
453
454/// Append one journal event at the next sequence number.
455pub fn append_event(inst: &Instance, mut event: journal::Event) -> Result<(), CoreError> {
456    let handle = inst.handle();
457    let (events, _) = journal::read(&handle)?;
458    event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
459    if event.at.is_empty() {
460        event.at = UtcTime::now().format();
461    }
462    if event.sdd.is_empty() {
463        event.sdd = inst.meta.get_str_or("version", "0.0.0").to_string();
464    }
465    journal::append_line(&handle, &journal::render_line(&event))?;
466    Ok(())
467}
468
469/// The unit's front matter after a release: Ready, no holder, no expiry.
470pub fn released_meta(inner: &str) -> String {
471    let b = yamlish::set_scalar_in_place(inner, "status", "Ready");
472    let b = yamlish::set_scalar_in_place(&b, "claimed_by", "—");
473    yamlish::set_scalar_in_place(&b, "claim_expires", "—")
474}