use std::path::{Path, PathBuf};
use anyhow::{Context, Result, anyhow, ensure};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use crate::{
git,
land_sync_recovery::{GhPrObserver, PrObserver},
queue::{OperatorResume, Queue, Task, TaskStatus},
run::{LandApproval, Liveness, MergeRepair, MergeRepairPhase, RunState, RunStatus},
};
pub use crate::land_sync_recovery_control::BeforeWrite;
fn before_write<T>(result: Result<T>) -> Result<T> {
result.map_err(|error| {
if error.is::<BeforeWrite>() {
error
} else {
anyhow::Error::new(BeforeWrite(error))
}
})
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Request {
pub run: String,
pub head: String,
pub actor: String,
pub request: String,
}
#[derive(Debug, Clone)]
pub struct Outcome {
pub task: Task,
pub repeated: bool,
pub reconciled: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Revision {
pub request: String,
pub rev: u64,
pub instruction: String,
pub previous_instruction: String,
pub previous_task_instruction: Option<String>,
pub previous_rev: Option<u64>,
pub head: String,
pub repair: String,
pub invalidated_approval: Option<LandApproval>,
pub at: Timestamp,
}
impl RunState {
pub fn approval_revoked_by_revision(&self, question: &str) -> bool {
self.instruction_revisions.iter().any(|r| {
r.invalidated_approval
.as_ref()
.is_some_and(|a| a.question == question)
})
}
pub(crate) fn unfinished_instruction_revision(&self) -> Option<&Revision> {
self.instruction_revisions.last().filter(|revision| {
!self.merge_repairs.iter().any(|repair| {
repair.question == revision.repair && repair.phase == MergeRepairPhase::Complete
})
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Phase {
Prepared,
Authorized,
Applied,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Binding {
task: serde_json::Value,
instruction: String,
rev: u64,
head: String,
pr: String,
repair: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Receipt {
request: Request,
phase: Phase,
binding: Binding,
queued: Task,
created_at: Timestamp,
#[serde(default)]
applied_at: Option<Timestamp>,
}
fn save_receipt(path: &Path, receipt: &Receipt) -> Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(receipt)?)?;
std::fs::rename(tmp, path)?;
Ok(())
}
pub fn receipt_path(home: &Path, actor: &str, request: &str) -> PathBuf {
home.join("instruction-revision-controls")
.join(actor)
.join(format!("{request}.json"))
}
pub fn adopt_into_run(
state: &mut RunState,
key: &str,
repair: &str,
instruction: &str,
rev: u64,
head: &str,
pr: &str,
) {
let at = Timestamp::now();
state.instruction_revisions.push(Revision {
request: key.to_owned(),
rev,
instruction: instruction.to_owned(),
previous_instruction: std::mem::replace(&mut state.instruction, instruction.to_owned()),
previous_task_instruction: state.task_instruction.replace(instruction.to_owned()),
previous_rev: state.task_instruction_rev.replace(rev),
head: head.to_owned(),
repair: repair.to_owned(),
invalidated_approval: state.land_approval.take(),
at,
});
if let Some(e2e) = state.head_e2e.take() {
state
.verification_history
.push(crate::run::VerificationEvidence {
superseded_by: None,
archived_at: Some(at),
fixes_spent: Some(state.gate_fixes.len()),
gate_head: None,
gate_ran: false,
gate: Vec::new(),
e2e: Some(e2e),
});
}
state.merge_repairs.push(MergeRepair {
question: repair.to_owned(),
head: head.to_owned(),
pr: pr.to_owned(),
reviews: state.reviews.clone(),
gate: state.gate.clone(),
gate_head: state.gate_head.clone(),
gate_fixes: state.gate_fixes.clone(),
pre_gate: state.pre_gate.clone(),
phase: MergeRepairPhase::Requested,
failure: None,
});
state.gate_ran = false;
state.gate_head = None;
state.land_armed_head = None;
state.land_reruns = None;
state.parked = false;
state.status = RunStatus::Landing;
state.event(
"instruction-revision",
format!(
"owner adopted task instruction generation {rev} into this run and PR; bounded repair and a fresh review, E2E, gate and head-bound approval are required"
),
);
}
pub async fn adopt(queue: &Queue, home: &Path, request: Request) -> Result<Outcome> {
adopt_with(queue, home, request, &GhPrObserver).await
}
#[allow(clippy::too_many_lines)]
pub async fn adopt_with<O: PrObserver>(
queue: &Queue,
home: &Path,
mut request: Request,
observer: &O,
) -> Result<Outcome> {
before_write((|| -> Result<()> {
ensure!(
crate::run::is_run_id(&request.run),
"instruction adoption needs a full run id"
);
ensure!(
crate::ask::valid_asset_name(&request.actor)
&& crate::ask::valid_asset_name(&request.request),
"actor and request must be safe filenames of at most 64 bytes"
);
ensure!(
request.head.len() == 40 && request.head.bytes().all(|c| c.is_ascii_hexdigit()),
"instruction adoption needs a full 40-character HEAD SHA"
);
Ok(())
})())?;
request.head = request.head.to_ascii_lowercase();
let dir = home
.join("instruction-revision-controls")
.join(&request.actor);
before_write(std::fs::create_dir_all(&dir).map_err(Into::into))?;
let lock = before_write(
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(dir.join(format!("{}.lock", request.request)))
.map_err(Into::into),
)?;
before_write(crate::pr_head::try_lock_file(&lock).map_err(Into::into))?;
let path = receipt_path(home, &request.actor, &request.request);
let key = format!("{}/{}", request.actor, request.request);
let repair = format!("instruction-{}-{}", request.actor, request.request);
let prior: Option<Receipt> = if path.exists() {
let bytes = std::fs::read(&path).with_context(|| {
format!(
"uncertain instruction revision receipt: could not read {}; inspect before retrying",
path.display()
)
})?;
Some(serde_json::from_slice(&bytes).with_context(|| {
format!(
"uncertain instruction revision receipt: corrupt JSON in {}; inspect before retrying",
path.display()
)
})?)
} else {
None
};
if let Some(prior) = &prior {
if prior.request != request {
return Err(anyhow::Error::new(BeforeWrite(anyhow!(
"request ID already binds a different operation"
))));
}
let task = queue.get(&prior.queued.id).with_context(|| {
format!(
"uncertain instruction revision receipt: owning task {} unreadable",
prior.queued.id
)
})?;
if prior.phase == Phase::Applied {
return Ok(Outcome {
task,
repeated: true,
reconciled: false,
});
}
if task.instruction_revision_requests.contains(&key) {
let mut completed = prior.clone();
completed.phase = Phase::Applied;
completed.applied_at = Some(Timestamp::now());
save_receipt(&path, &completed)?;
return Ok(Outcome {
task,
repeated: true,
reconciled: true,
});
}
}
let fresh = prior.is_none();
let wrap = |err: anyhow::Error| -> anyhow::Error {
if fresh {
anyhow::Error::new(BeforeWrite(err))
} else {
err
}
};
crate::task_reassign::ensure_current(queue, &request.run).map_err(&wrap)?;
let mut owners = queue
.list()
.into_iter()
.filter(|t| t.execution_runs().last() == Some(&request.run));
let listed = owners
.next()
.context("run has no eligible latest task owner")
.map_err(&wrap)?;
if owners.next().is_some() {
return Err(wrap(anyhow!("run has ambiguous task ownership")));
}
if let Some(prior) = &prior
&& prior.queued.id != listed.id
{
return Err(anyhow!(
"uncertain instruction revision receipt: receipt targets task {} but current owner is {}",
prior.queued.id,
listed.id
));
}
let _claim = queue
.claim_for_instruction_revision(&listed.id)
.context("task is claimed by a running daemon or another control")
.map_err(&wrap)?;
let task = queue.get(&listed.id).map_err(&wrap)?;
let _owner = crate::pr_head::owner_lock(home, &request.run).map_err(&wrap)?;
let mut state = RunState::load_under(&request.run, home).map_err(&wrap)?;
crate::pr_head::ensure_owner(&state).map_err(&wrap)?;
let adopted = state.instruction_revisions.iter().any(|r| r.request == key);
if state.instruction_revisions.last().is_some_and(|revision| {
revision.request != key
&& !task
.instruction_revision_requests
.contains(&revision.request)
}) {
return Err(wrap(anyhow!(
"another instruction adoption is interrupted; replay its owner request first"
)));
}
match (&prior, adopted) {
(None, true) => {
return Err(anyhow!(
"uncertain instruction revision state: run already adopted request `{key}` without a receipt; inspect before retrying"
));
}
(Some(p), false) if p.phase == Phase::Authorized => {
return Err(anyhow!(
"uncertain instruction revision receipt: receipt recorded adoption but the run has none for `{key}`; inspect before retrying"
));
}
_ => {}
}
if !adopted {
verify(home, &request, &task, &state, observer, &wrap).await?;
} else {
ensure!(
task.execution_runs().last() == Some(&state.id)
&& !matches!(task.status, TaskStatus::Running | TaskStatus::Done),
"run task ownership or queue status changed"
);
let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
ensure!(
state.liveness_under(home, claimed) == Liveness::Dead,
"run is live or its ownership is unknown"
);
}
let _maintenance = crate::driver::maintenance(home, &state.id).map_err(&wrap)?;
let pr = state
.pr
.as_ref()
.map(|p| p.url.clone())
.context("run has no recorded pull request")
.map_err(&wrap)?;
let binding = Binding {
task: serde_json::to_value(&task)
.map_err(anyhow::Error::from)
.map_err(&wrap)?,
instruction: task.instruction.clone(),
rev: task.instruction_rev,
head: request.head.clone(),
pr,
repair: repair.clone(),
};
let reconciled = prior.is_some();
let mut receipt = if let Some(prior) = prior {
ensure!(
prior.binding == binding || adopted && prior.binding.same_operation(&binding),
"interrupted instruction revision is stale: task, instruction, HEAD or PR changed"
);
prior
} else {
let mut queued = task.clone();
if !crate::repair_budget::queue_resumption(queue, &mut queued, &state.id).map_err(&wrap)? {
queued.release_operator("instruction-revision", None);
}
queued.resume_override = Some(OperatorResume {
question_id: String::new(),
at: Timestamp::now(),
conductor_rehold: None,
forced: true,
pinned_run: Some(state.id.clone()),
});
queued.instruction_revision_requests.push(key.clone());
let prepared = Receipt {
request: request.clone(),
phase: Phase::Prepared,
binding,
queued,
created_at: Timestamp::now(),
applied_at: None,
};
save_receipt(&path, &prepared)?;
prepared
};
if !adopted {
adopt_into_run(
&mut state,
&key,
&repair,
&receipt.binding.instruction,
receipt.binding.rev,
&receipt.binding.head,
&receipt.binding.pr,
);
state.save_under(home)?;
}
revoke_open_approval(&state, &key)?;
if receipt.phase == Phase::Prepared {
receipt.phase = Phase::Authorized;
save_receipt(&path, &receipt)?;
}
queue.commit_instruction_revision(&mut receipt.queued, &receipt.binding.task)?;
receipt.phase = Phase::Applied;
receipt.applied_at = Some(Timestamp::now());
save_receipt(&path, &receipt)?;
Ok(Outcome {
task: queue.get(&task.id)?,
repeated: false,
reconciled,
})
}
impl Binding {
fn same_operation(&self, other: &Self) -> bool {
self.instruction == other.instruction
&& self.rev == other.rev
&& self.head == other.head
&& self.pr == other.pr
&& self.repair == other.repair
}
}
fn revoke_open_approval(state: &RunState, key: &str) -> Result<()> {
let Some(revision) = state
.instruction_revisions
.iter()
.find(|r| r.request == key)
else {
return Ok(());
};
let Some(approval) = &revision.invalidated_approval else {
return Ok(());
};
let store = crate::ask::Questions::open();
if let Ok(mut question) = store.get_for_effects(&approval.question)
&& question.status == crate::ask::QuestionStatus::Open
{
question.abandon("the task instruction was revised; this approval no longer applies");
store.put(&mut question)?;
}
Ok(())
}
async fn verify<O: PrObserver>(
home: &Path,
request: &Request,
task: &Task,
state: &RunState,
observer: &O,
wrap: &impl Fn(anyhow::Error) -> anyhow::Error,
) -> Result<()> {
(|| -> Result<()> {
ensure!(
task.execution_runs().last() == Some(&state.id)
&& task.assignment_accepts(state)
&& !matches!(task.status, TaskStatus::Running | TaskStatus::Done)
&& !task.fresh_start
&& task.review_branch.is_none()
&& task.pr_recovery.is_none(),
"run task ownership or queue status changed"
);
ensure!(
state
.origin
.as_ref()
.and_then(|o| o.task.as_deref())
.is_none_or(|owner| owner == task.id),
"run belongs to another task"
);
ensure!(
task.instruction_rev > state.task_instruction_rev.unwrap_or(0)
&& !task.instruction.trim().is_empty(),
"task has no newer instruction generation than the retained run"
);
let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
ensure!(
state.liveness_under(home, claimed) == Liveness::Dead,
"run is live or its ownership is unknown"
);
ensure!(
state.status.resumable()
&& state.released_to.is_none()
&& state.retired_to.is_none()
&& state.pr_taken_over_by.is_none()
&& state.merge_decision.is_none(),
"run ownership is final or holds an owner stop decision"
);
ensure!(
state.merge_repairs.iter().all(|r| matches!(
r.phase,
MergeRepairPhase::Complete | MergeRepairPhase::Failed
)),
"a repair is already in flight on this run"
);
ensure!(
state.merge_repairs.len() < state.config.graph.land_rounds
&& state.config.graph.review_rounds > 0,
"repair generation budget exhausted or review disabled; no instruction revision was adopted"
);
Ok(())
})()
.map_err(wrap)?;
let winner = state
.winner()
.cloned()
.context("run has no retained winner")
.map_err(wrap)?;
if !git::is_clean(&winner.worktree).await.map_err(wrap)? {
return Err(wrap(anyhow!("retained worktree has uncommitted changes")));
}
let scratch = home.join("runs").join(&state.id).join("rebase");
if git::checked_rebase_in_progress(&scratch)
.await
.map_err(wrap)?
{
return Err(wrap(anyhow!(
"landing rebase is already in progress in scratch worktree"
)));
}
let local = git::rev_parse(&winner.worktree, "HEAD")
.await
.map_err(wrap)?;
let branch = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
.await
.map_err(wrap)?;
if local != branch {
return Err(wrap(anyhow!(
"retained worktree does not match the winner branch"
)));
}
if !local.eq_ignore_ascii_case(&request.head) {
return Err(wrap(anyhow!(
"retained HEAD changed since the owner request (expected {}, actual {local})",
request.head
)));
}
let pushed = state
.pr_pushed_head
.as_deref()
.context("run has no recorded published PR head")
.map_err(wrap)?;
if !pushed.eq_ignore_ascii_case(&local) {
return Err(wrap(anyhow!(
"retained HEAD ({local}) does not match recorded published PR head ({pushed})"
)));
}
let record = state
.pr
.as_ref()
.context("run has no recorded pull request")
.map_err(wrap)?;
if record.state != "open" {
return Err(wrap(anyhow!("recorded pull request is not open")));
}
let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
let remote = git::remote_head(&state.repo, &state.config.merge.remote, &public)
.await
.map_err(wrap)?;
if !remote
.as_deref()
.is_some_and(|r| r.eq_ignore_ascii_case(&local))
{
return Err(wrap(anyhow!(
"public branch `{public}` ({}) does not match retained HEAD ({local})",
remote.as_deref().unwrap_or("missing")
)));
}
let observed = observer
.observe_pr(&state.repo, &record.url)
.await
.map_err(wrap)?;
(|| -> Result<()> {
ensure!(observed.open, "pull request is no longer open");
ensure!(
observed.url == record.url && observed.number == record.number,
"observed pull request does not match the run's recorded pull request"
);
ensure!(
observed.head.eq_ignore_ascii_case(&local),
"published PR head ({}) does not match retained HEAD ({local})",
observed.head
);
if let Some(base) = observed.base_branch.as_deref().filter(|b| !b.is_empty()) {
ensure!(
base == state.base_branch,
"pull request base branch changed (expected {}, observed {base})",
state.base_branch
);
}
Ok(())
})()
.map_err(wrap)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::run::GateRepairE2e;
#[test]
fn adoption_revokes_approval_and_verification_but_keeps_history() {
let mut state = RunState::new(
PathBuf::from("."),
"main".into(),
"abc".into(),
"use teravars 0.7.0".into(),
crate::config::Config::default(),
);
state.task_instruction = Some("use teravars 0.7.0".into());
state.land_approval = Some(LandApproval {
question: "q-old".into(),
head: "h".into(),
});
state.land_armed_head = Some("h".into());
state.gate_ran = true;
state.gate_head = Some("h".into());
state.head_e2e = Some(GateRepairE2e::new("h".into(), true, Vec::new()));
adopt_into_run(
&mut state,
"cli/r",
"instruction-cli-r",
"use teravars 0.8.0",
3,
"h",
"https://github.com/o/r/pull/1",
);
assert!(state.land_approval.is_none() && state.land_armed_head.is_none());
assert!(!state.gate_ran && state.gate_head.is_none() && state.head_e2e.is_none());
assert_eq!(state.verification_history.len(), 1);
assert!(state.approval_revoked_by_revision("q-old"));
assert!(!state.approval_revoked_by_revision("q-new"));
assert_eq!(state.instruction, "use teravars 0.8.0");
assert_eq!(
state.task_instruction.as_deref(),
Some("use teravars 0.8.0")
);
assert_eq!(state.task_instruction_rev, Some(3));
let revision = &state.instruction_revisions[0];
assert_eq!(revision.previous_instruction, "use teravars 0.7.0");
assert_eq!(state.merge_repairs.len(), 1);
assert_eq!(state.merge_repairs[0].phase, MergeRepairPhase::Requested);
assert_eq!(state.merge_repairs[0].gate_head.as_deref(), Some("h"));
}
}