Skip to main content

vitrify_cli/incremental/
adopt.rs

1//! Adoption of attempts that were built but never landed.
2//!
3//! A run that is interrupted, or a lease that lapses while the work waits
4//! for the gate, leaves an attempt that its worker finished: the branch
5//! carries the unit's Built stamp and the trace it was built from. Sending
6//! that unit back to a worker would pay for a model session to write what is
7//! already written. Instead the attempt is **adopted**: the scheduler claims
8//! the unit again, [`relabel`] makes the attempt's work the new claim's
9//! branch, and the unit goes straight to the gate with no worker session.
10//!
11//! An attempt is adoptable ([`adoptable`]) when
12//!
13//! * its worker is gone — the run that made it ended or died. That is the
14//!   caller's to decide: this module only looks at git;
15//! * its branch — the newest attempt branch of the unit since the unit was
16//!   last verified — carries a Built stamp for the unit, with a recorded
17//!   trace, at its tip;
18//! * that trace still matches the unit's reading set at the current mainline
19//!   head: nothing it was built from has moved.
20//!
21//! An attempt the gate (or its worker) already judged is not adopted: one set
22//! aside as `rejected-gate`, `rejected-write-set`, `ownership-conflict`,
23//! `blocked` or `released` would only be judged the same way again, and a
24//! rejected adoption — set aside on the new claim's branch — would otherwise
25//! be adopted again, forever. Those go to a worker, as today. An attempt
26//! that changed paths outside the unit's write-set is not adopted either:
27//! the gate would reject it, and its files go to the next worker as a draft
28//! instead.
29//!
30//! # Re-labelling
31//!
32//! The attempt's own commit cannot simply be given the new claim's branch
33//! name. It forked from the old claim's commit, and mainline has rewritten
34//! the unit's fencing fields twice since (the release, the new claim), next
35//! to the status line the attempt changed: the gate's merge would conflict
36//! in the unit's own front matter. [`relabel`] therefore builds the new
37//! claim's branch the way a worker would have: forked from the new claim's
38//! commit, with one commit that carries the attempt's work — the files the
39//! unit owns that the attempt changed, as the attempt left them, and the
40//! unit's handoff fields (`status`, `built`, `trace`) from its Built stamp.
41//! Nothing else is carried, so the branch is exactly the attempt's work,
42//! relative to the new claim.
43//!
44//! Fencing holds. The token is the claim sequence the branch name carries;
45//! the old claim's branch keeps the old sequence, which the gate's fencing
46//! check rejects, and only the deliberate new claim's branch — made by
47//! [`relabel`], which refuses an existing name — can land. The gate then runs
48//! as for any attempt: fencing, the write-set check against the new claim,
49//! the input check, every row. Adoption skips the model, never the gate.
50
51use std::path::{Path, PathBuf};
52
53use vitrify_core::model::{self, Instance, Shape};
54use vitrify_core::writeset::WriteSet;
55use vitrify_core::{CoreError, journal, trace, yamlish};
56
57use crate::cmd::resolve_sdd_in;
58use crate::git::Git;
59use crate::layout;
60
61/// First words of the commit that sets an attempt aside (as the scheduler
62/// writes it: `sdd: abandoned attempt <unit> (c<n>) — <outcome>`).
63const ABANDONED: &str = "sdd: abandoned attempt";
64
65/// Outcomes that are a verdict on the work itself: an attempt set aside
66/// with one of these is not adopted.
67const JUDGED: [&str; 5] = [
68    "rejected-gate",
69    "rejected-write-set",
70    "ownership-conflict",
71    "blocked",
72    "released",
73];
74
75/// An attempt that can go to the gate without a worker.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct Attempt {
78    pub unit: String,
79    /// Its branch, `sdd/<slug>/<unit>/c<seq>`.
80    pub branch: String,
81    /// The claim sequence its branch carries: the old token.
82    pub seq: i64,
83    /// The commit at the branch's tip.
84    pub commit: String,
85    /// Where the attempt left mainline: its old claim's commit.
86    pub fork: String,
87    /// The paths the unit owns that the attempt changed since `fork`
88    /// (deletions included), sorted.
89    pub paths: Vec<String>,
90    /// The SDD's root relative to the checkout root, as `--sdd` names it.
91    pub sdd_rel: PathBuf,
92    /// The Built stamp's `built` text.
93    pub built: String,
94    /// The Built stamp's recorded trace.
95    pub trace: Vec<(String, String)>,
96}
97
98/// Why a unit has no adoptable attempt.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Refusal {
101    /// No attempt branch since the unit was last verified.
102    NoBranch,
103    /// The newest attempt was set aside with a verdict on its work.
104    Judged { branch: String, outcome: String },
105    /// The branch's tip does not stamp the unit Built with a trace.
106    NotBuilt { branch: String, status: String },
107    /// The attempt changed paths outside the unit's write-set, sorted.
108    WriteSet { branch: String, paths: Vec<String> },
109    /// Inputs the attempt was built from have moved since: the trace keys
110    /// that no longer match (`unit`, a contract key, `global`), sorted.
111    TraceMoved { branch: String, keys: Vec<String> },
112}
113
114impl Refusal {
115    /// One human line: why the unit goes to a worker instead.
116    pub fn describe(&self) -> String {
117        match self {
118            Refusal::NoBranch => "no attempt since it was last verified".to_string(),
119            Refusal::Judged { branch, outcome } => {
120                format!("its newest attempt ({branch}) was set aside as {outcome}")
121            }
122            Refusal::NotBuilt { branch, status } => {
123                format!("its newest attempt ({branch}) is not stamped Built (status {status})")
124            }
125            Refusal::WriteSet { branch, paths } => format!(
126                "its newest attempt ({branch}) changed paths outside the unit's write-set: {}",
127                paths.join(", ")
128            ),
129            Refusal::TraceMoved { branch, keys } => format!(
130                "its newest attempt ({branch}) was built from inputs that have moved: {}",
131                keys.join(", ")
132            ),
133        }
134    }
135}
136
137/// The adoptable attempt of `unit`, or why there is none. `inst` is the SDD
138/// as the current mainline head holds it, loaded from the checkout at `root`
139/// (checked out at that head); `git` reads the repository's branches (any
140/// checkout of it will do). The caller has established that no worker of a
141/// live run holds the attempt.
142pub fn adoptable(
143    git: &Git,
144    inst: &Instance,
145    root: &Path,
146    unit: &str,
147) -> Result<Result<Attempt, Refusal>, CoreError> {
148    let Some(u) = inst.unit(unit) else {
149        return Err(CoreError::refusal(
150            4,
151            format!("error: unit {unit} not found at the mainline head"),
152        ));
153    };
154    let slug = layout::sdd_slug(inst);
155    let Some((seq, branch)) = newest_attempt(git, inst, &slug, unit)? else {
156        return Ok(Err(Refusal::NoBranch));
157    };
158    let commit = git.rev_parse(&branch).map_err(CoreError::from)?;
159    let message = git.commit_message(&commit).unwrap_or_default();
160    let subject = message.lines().next().unwrap_or("");
161    if let Some(rest) = subject.strip_prefix(ABANDONED)
162        && let Some((_, outcome)) = rest.rsplit_once(" — ")
163        && JUDGED.contains(&outcome.trim())
164    {
165        return Ok(Err(Refusal::Judged {
166            branch,
167            outcome: outcome.trim().to_string(),
168        }));
169    }
170    // the Built stamp at the tip, as the branch has the unit's entry
171    let ws = WriteSet::of(inst, u, root)?;
172    let stamped = git
173        .show_text(&commit, &ws.spec_file)
174        .map_err(CoreError::from)?
175        .and_then(|text| unit_meta_in(inst.shape, &text, unit))
176        .unwrap_or_default();
177    let status = stamped.get_str_or("status", "Draft").to_string();
178    let recorded = stamped.get_map("trace").cloned().unwrap_or_default();
179    let built = stamped.get_str_or("built", "").trim().to_string();
180    if status != "Built" || recorded.is_empty() {
181        return Ok(Err(Refusal::NotBuilt {
182            branch,
183            status: if recorded.is_empty() && status == "Built" {
184                "Built, no trace".to_string()
185            } else {
186                status
187            },
188        }));
189    }
190    // the write-set check the gate will make, so a sure rejection costs no
191    // claim
192    let head = git.at(root).rev_parse("HEAD").map_err(CoreError::from)?;
193    let fork = git.merge_base(&head, &commit).map_err(CoreError::from)?;
194    let changed = git.changed_paths(&fork, &commit).map_err(CoreError::from)?;
195    let versions = || {
196        (
197            git.show_text(&fork, &ws.spec_file).ok().flatten(),
198            git.show_text(&commit, &ws.spec_file).ok().flatten(),
199        )
200    };
201    let mut outside: Vec<String> = ws
202        .violations(&changed, versions)
203        .iter()
204        .map(|v| v.path().to_string())
205        .collect();
206    if !outside.is_empty() {
207        outside.sort();
208        outside.dedup();
209        return Ok(Err(Refusal::WriteSet {
210            branch,
211            paths: outside,
212        }));
213    }
214    // the trace against the reading set the head holds now
215    let (current, problems) = trace::compute(inst, u)?;
216    if !problems.is_empty() {
217        return Err(CoreError::refusal(
218            4,
219            problems
220                .iter()
221                .map(|p| format!("error: {p}"))
222                .collect::<Vec<_>>()
223                .join("\n"),
224        ));
225    }
226    let mut keys: Vec<String> = trace::verify(&recorded, &current)
227        .into_iter()
228        .map(|m| m.key)
229        .collect();
230    if !keys.is_empty() {
231        keys.sort();
232        keys.dedup();
233        return Ok(Err(Refusal::TraceMoved { branch, keys }));
234    }
235    let mut paths: Vec<String> = changed.into_iter().filter(|p| ws.covers(p)).collect();
236    paths.sort();
237    paths.dedup();
238    let sdd_rel = inst
239        .root
240        .strip_prefix(root)
241        .map(Path::to_path_buf)
242        .unwrap_or_else(|_| inst.root.clone());
243    Ok(Ok(Attempt {
244        unit: unit.to_string(),
245        branch,
246        seq,
247        commit,
248        fork,
249        paths,
250        sdd_rel,
251        built,
252        trace: recorded,
253    }))
254}
255
256/// Re-label `attempt` as the work of the new claim `new_seq`, whose claim
257/// transaction made `claim_commit`: create the branch
258/// `sdd/<slug>/<unit>/c<new_seq>` at `claim_commit` and commit on it the
259/// attempt's work (see the module doc), in a scratch worktree at `scratch`
260/// — where the new claim's worker would have worked
261/// (`Layout::unit_worktree`) — that is removed again. Returns the branch.
262///
263/// Refuses, creating nothing, when the branch or `scratch` already exists,
264/// or `new_seq` does not supersede the attempt's claim. On a later failure
265/// the branch and the scratch worktree are removed again. The old branch is
266/// left as it is: its token can never land.
267pub fn relabel(
268    primary: &Git,
269    slug: &str,
270    attempt: &Attempt,
271    new_seq: i64,
272    claim_commit: &str,
273    scratch: &Path,
274) -> Result<String, CoreError> {
275    let refuse = |why: String| {
276        Err(CoreError::refusal(
277            1,
278            format!(
279                "error: cannot adopt {} (c{}) under claim c{new_seq}: {why}",
280                attempt.unit, attempt.seq
281            ),
282        ))
283    };
284    if new_seq <= attempt.seq {
285        return refuse("the new claim must supersede it".to_string());
286    }
287    let branch = layout::unit_branch(slug, &attempt.unit, new_seq);
288    if primary.branch_exists(&branch).map_err(CoreError::from)? {
289        return refuse(format!("branch {branch} already exists"));
290    }
291    if scratch.exists() {
292        return refuse(format!("{} already exists", scratch.display()));
293    }
294    if let Some(parent) = scratch.parent() {
295        fs_err::create_dir_all(parent).map_err(|source| CoreError::Io {
296            path: parent.to_path_buf(),
297            source,
298        })?;
299    }
300    primary
301        .worktree_add_branch(scratch, &branch, claim_commit)
302        .map_err(CoreError::from)?;
303    let carried = carry(primary, attempt, new_seq, scratch);
304    let _ = primary.worktree_remove(scratch);
305    if let Err(e) = carried {
306        let _ = primary.delete_branch(&branch);
307        return Err(e);
308    }
309    Ok(branch)
310}
311
312/// Commit the attempt's work in the worktree `scratch`, on the new branch.
313fn carry(primary: &Git, attempt: &Attempt, new_seq: i64, scratch: &Path) -> Result<(), CoreError> {
314    let wt = primary.at(scratch);
315    let mut present: Vec<String> = Vec::new();
316    let mut gone: Vec<String> = Vec::new();
317    for p in &attempt.paths {
318        let there = wt
319            .verify_ref(&format!("{}:{p}", attempt.commit))
320            .map_err(CoreError::from)?;
321        if there.is_some() {
322            present.push(p.clone());
323        } else {
324            gone.push(p.clone());
325        }
326    }
327    wt.restore_paths(&attempt.commit, &present)
328        .map_err(CoreError::from)?;
329    for p in &gone {
330        let path = scratch.join(p);
331        if path.exists() {
332            fs_err::remove_file(&path).map_err(|source| CoreError::Io {
333                path: path.clone(),
334                source,
335            })?;
336        }
337    }
338    // the handoff fields, from the attempt's stamp, onto the new claim's entry
339    let inst = Instance::load(resolve_sdd_in(scratch, &attempt.sdd_rel)?)?;
340    let Some(unit) = inst.unit(&attempt.unit) else {
341        return Err(CoreError::refusal(
342            4,
343            format!(
344                "error: unit {} not found at the new claim's commit",
345                attempt.unit
346            ),
347        ));
348    };
349    model::rewrite_unit_meta(&inst.handle(), unit, |inner| {
350        let b = yamlish::set_scalar_in_place(inner, "status", "Built");
351        let b = yamlish::set_scalar_in_place(&b, "built", &attempt.built);
352        yamlish::set_map_in_place(&b, "trace", &attempt.trace)
353    })?;
354    wt.add_all().map_err(CoreError::from)?;
355    wt.commit_note(
356        &format!(
357            "sdd: adopt {} (c{}) as c{new_seq}",
358            attempt.unit, attempt.seq
359        ),
360        &format!(
361            "Built work of {} adopted from {} ({}), with no worker session.",
362            attempt.unit,
363            attempt.branch,
364            &attempt.commit[..7.min(attempt.commit.len())]
365        ),
366    )
367    .map_err(CoreError::from)
368}
369
370/// The newest attempt branch of `unit` made after the unit was last
371/// verified (its sequence and name): earlier ones were superseded by that
372/// verification.
373fn newest_attempt(
374    git: &Git,
375    inst: &Instance,
376    slug: &str,
377    unit: &str,
378) -> Result<Option<(i64, String)>, CoreError> {
379    let (events, _) = journal::read(&inst.handle())?;
380    let verified_at = events
381        .iter()
382        .filter(|e| e.event == "verified" && e.unit.as_deref() == Some(unit))
383        .filter_map(|e| e.claim_seq)
384        .max()
385        .unwrap_or(0);
386    let mut best: Option<(i64, String)> = None;
387    for branch in git
388        .branches_under(&layout::branch_prefix(slug, unit))
389        .map_err(CoreError::from)?
390    {
391        let Some(seq) = layout::branch_seq(&branch) else {
392            continue;
393        };
394        if seq > verified_at && best.as_ref().is_none_or(|(s, _)| seq > *s) {
395            best = Some((seq, branch));
396        }
397    }
398    Ok(best)
399}
400
401/// A unit's front matter as `text` — its unit file, or the single-file SDD
402/// holding its region — has it.
403fn unit_meta_in(shape: Shape, text: &str, uid: &str) -> Option<model::Meta> {
404    match shape {
405        Shape::Bundle => model::front_matter(text),
406        Shape::Single => {
407            let (start, end) = model::find_unit_span(text, uid)?;
408            let region = &text[start..end];
409            let (_, _, inner_start, inner_end) = model::find_meta_block_span(region)?;
410            Some(model::Meta(yamlish::parse(&region[inner_start..inner_end])))
411        }
412    }
413}