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