1use std::path::Path;
10
11use anyhow::Result;
12use jiff::Timestamp;
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 git,
17 queue::{Queue, Task, TaskStatus},
18 run::{
19 CommandOutcome, GateRepairE2e, MergeRepairPhase, RunState, RunStatus, VerificationEvidence,
20 },
21};
22
23pub const GRANT_ATTEMPTS: usize = 1;
25
26pub const MAX_GRANTS: usize = 4;
28
29pub const EXHAUSTED_DETAIL: &str = "landing base synchronization budget exhausted";
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Stop {
35 pub attempts: usize,
37 pub limit: usize,
39 pub head: String,
41 pub pr_head: String,
43 pub pr_url: String,
45 pub pr_number: u64,
47 pub tip: String,
49 pub detail: String,
51 pub at: Timestamp,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Scope {
58 pub tip: String,
60 pub instruction: String,
62 pub assignment: usize,
64 pub pr_head: String,
66 pub pr_url: String,
68 pub pr_number: u64,
70 pub grant_index: usize,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct ArchivedVerification {
77 pub archived_at: Timestamp,
79 pub head: String,
81 pub gate_head: Option<String>,
83 pub gate_ran: bool,
85 pub gate: Vec<CommandOutcome>,
87 pub head_e2e: Option<GateRepairE2e>,
89 pub gate_repair_e2e: Option<GateRepairE2e>,
91 #[serde(default)]
93 pub review_verified_heads: Vec<(usize, Option<String>)>,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct Authorization {
99 pub request: String,
101 pub task: String,
103 pub run: String,
105 pub stop: Stop,
107 pub scope: Scope,
109 #[serde(default)]
111 pub decision: Option<Timestamp>,
112 #[serde(default)]
114 pub generation: Option<u64>,
115 pub granted_attempts: usize,
117 pub at: Timestamp,
119 pub consumed: bool,
121 #[serde(default)]
123 pub consumed_at: Option<Timestamp>,
124 #[serde(default)]
126 pub invalidated: Option<String>,
127 #[serde(default)]
129 pub archived_verification: Option<ArchivedVerification>,
130}
131
132impl Authorization {
133 pub(crate) fn refuse(&mut self, reason: impl Into<String>) {
135 self.invalidated = Some(reason.into());
136 self.consumed = true;
137 if self.consumed_at.is_none() {
138 self.consumed_at = Some(Timestamp::now());
139 }
140 }
141}
142
143#[derive(Debug, Clone, Default, Serialize, Deserialize)]
145pub struct Recovery {
146 #[serde(default)]
148 pub extra_attempts: usize,
149 #[serde(default)]
151 pub stops: Vec<Stop>,
152 #[serde(default)]
154 pub stop: Option<Stop>,
155 #[serde(default)]
157 pub authorizations: Vec<Authorization>,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct ObservedPr {
163 pub url: String,
165 pub number: u64,
167 pub open: bool,
169 pub head: String,
171 pub base_branch: Option<String>,
173}
174
175pub trait PrObserver {
177 fn observe_pr(
179 &self,
180 repo: &Path,
181 pr_url: &str,
182 ) -> impl std::future::Future<Output = Result<ObservedPr>> + Send;
183}
184
185#[derive(Debug, Default, Clone, Copy)]
187pub struct GhPrObserver;
188
189impl PrObserver for GhPrObserver {
190 async fn observe_pr(&self, repo: &Path, pr_url: &str) -> Result<ObservedPr> {
191 crate::land::observe_pr_summary(repo, pr_url).await
192 }
193}
194
195fn matches_exhausted_detail(detail: &str) -> bool {
196 let trimmed = detail.trim();
197 trimmed == EXHAUSTED_DETAIL
198 || trimmed == format!("could not synchronize landing base: {EXHAUSTED_DETAIL}")
199}
200
201fn matches_exhausted_event(message: &str) -> bool {
202 let trimmed = message.trim();
203 trimmed == format!("stopped: could not synchronize landing base: {EXHAUSTED_DETAIL}")
204 || trimmed == format!("stopped: {EXHAUSTED_DETAIL}")
205 || trimmed == format!("gave up: {EXHAUSTED_DETAIL}")
206 || trimmed == format!("gave up: could not synchronize landing base: {EXHAUSTED_DETAIL}")
207}
208
209fn legacy_exhausted_diagnostic(state: &RunState) -> bool {
210 if let Some(last_land) = state.events.iter().rev().find(|e| e.node == "land") {
211 matches_exhausted_event(&last_land.message)
212 } else {
213 state
214 .merge
215 .as_ref()
216 .is_some_and(|m| !m.ok && matches_exhausted_detail(&m.detail))
217 }
218}
219
220fn exhausted_stop_timestamp(state: &RunState) -> Timestamp {
221 state
222 .events
223 .iter()
224 .rev()
225 .find(|e| e.node == "land" && matches_exhausted_event(&e.message))
226 .map_or(state.updated_at, |e| e.at)
227}
228
229impl RunState {
230 pub fn land_sync_budget(&self) -> usize {
232 self.config
233 .graph
234 .land_rounds
235 .saturating_add(self.land_sync_recovery.extra_attempts)
236 .saturating_sub(
237 self.land_sync_recovery
238 .authorizations
239 .iter()
240 .filter(|a| a.invalidated.is_some() && a.archived_verification.is_some())
241 .count(),
242 )
243 }
244
245 pub fn land_sync_grants_remaining(&self) -> usize {
247 MAX_GRANTS.saturating_sub(self.land_sync_recovery.extra_attempts)
248 }
249
250 pub fn land_sync_exhausted(&self) -> bool {
253 if self.status != RunStatus::Blocked {
254 return false;
255 }
256 if self.released_to.is_some()
257 || self.retired_to.is_some()
258 || self.pr_taken_over_by.is_some()
259 {
260 return false;
261 }
262 if !crate::handover::landing_checkpoint(self)
263 || self.base_sync_blocked()
264 || self.pr_publication_pending
265 {
266 return false;
267 }
268 if self.merge_decision.is_some()
269 || self.resource_block.is_some()
270 || self.sequencer_stop.is_some()
271 || self.land_rebase_from.is_some()
272 || self.land_sync_target.is_some()
273 {
274 return false;
275 }
276 if self.merge_repairs.last().is_some_and(|r| {
277 matches!(
278 r.phase,
279 MergeRepairPhase::Requested
280 | MergeRepairPhase::Fixing
281 | MergeRepairPhase::Reviewing
282 )
283 }) || self
284 .repair_grants
285 .last()
286 .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
287 || self
288 .rebase_fixes
289 .iter()
290 .any(|r| r.stop.is_none() && !r.finished)
291 {
292 return false;
293 }
294 if !self.land_sync_pending
295 || self.land_sync_attempts == 0
296 || self.land_sync_attempts < self.land_sync_budget()
297 {
298 return false;
299 }
300 if let Some(stop) = &self.land_sync_recovery.stop {
301 stop.detail == EXHAUSTED_DETAIL
302 && stop.attempts == self.land_sync_attempts
303 && stop.limit == self.land_sync_budget()
304 && self
305 .pr
306 .as_ref()
307 .is_some_and(|pr| pr.url == stop.pr_url && pr.number == stop.pr_number)
308 && self.land_sync_recovery.stops.contains(stop)
309 } else {
310 self.land_sync_recovery
311 .authorizations
312 .last()
313 .is_some_and(|a| {
314 a.invalidated.is_some()
315 && a.archived_verification.is_some()
316 && a.stop.attempts == self.land_sync_attempts
317 })
318 || legacy_exhausted_diagnostic(self)
319 }
320 }
321
322 pub fn has_unconsumed_land_sync_authorization(&self) -> bool {
324 self.land_sync_recovery
325 .authorizations
326 .iter()
327 .any(|a| !a.consumed && a.invalidated.is_none())
328 }
329
330 pub fn land_sync_recovery_pending(&self) -> bool {
332 self.land_sync_exhausted()
333 && self
334 .land_sync_recovery
335 .authorizations
336 .last()
337 .is_some_and(|a| {
338 !a.consumed
339 && a.invalidated.is_none()
340 && a.run == self.id
341 && a.granted_attempts == GRANT_ATTEMPTS
342 && a.scope.grant_index == self.land_sync_recovery.extra_attempts
343 && self.land_sync_recovery.stop.as_ref() == Some(&a.stop)
344 })
345 }
346
347 pub(crate) fn land_sync_unstarted_grant(&self) -> bool {
350 self.status.resumable()
351 && self
352 .land_sync_recovery
353 .authorizations
354 .last()
355 .is_some_and(|a| {
356 a.consumed
357 && a.invalidated.is_none()
358 && a.archived_verification.is_some()
359 && self.land_sync_attempts == a.stop.attempts
360 && self.land_sync_recovery.extra_attempts
361 == a.scope.grant_index.saturating_add(GRANT_ATTEMPTS)
362 })
363 }
364
365 pub fn land_sync_next_action(&self) -> String {
367 let attempts = self.land_sync_attempts;
368 let limit = self.land_sync_budget();
369 let grants = self.land_sync_recovery.extra_attempts;
370 let head = self
371 .land_sync_recovery
372 .stop
373 .as_ref()
374 .map(|s| s.head.as_str())
375 .or(self.pr_pushed_head.as_deref())
376 .unwrap_or("<full-head-sha>");
377 if let Some(reason) = self
378 .land_sync_recovery
379 .authorizations
380 .last()
381 .and_then(|a| a.invalidated.as_ref())
382 && !self.land_sync_recovery_pending()
383 {
384 if self.land_sync_grants_remaining() == 0 {
385 return format!(
386 "Landing base-sync recovery approval invalidated: {reason}; lifetime grant limit reached ({grants}/{MAX_GRANTS})"
387 );
388 }
389 return format!(
390 "Landing base-sync recovery approval invalidated: {reason}. Authorize a new bounded attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} grants used)",
391 self.id
392 );
393 }
394 if self.land_sync_recovery_pending() || self.land_sync_unstarted_grant() {
395 return format!(
396 "Landing base-sync recovery approval recorded; resume the retained run to spend {GRANT_ATTEMPTS} approved synchronization attempt ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)"
397 );
398 }
399 if self.land_sync_grants_remaining() == 0 {
400 return format!(
401 "Lifetime landing base-sync recovery limit reached ({grants}/{MAX_GRANTS} grants used, {attempts}/{limit} attempts); inspect the retained branch and PR before manual intervention"
402 );
403 }
404 format!(
405 "Authorize {GRANT_ATTEMPTS} bounded landing base-sync attempt with `magi task control recover-land-sync {} --request <unique-id> --head {head}` ({attempts}/{limit} attempts, {grants}/{MAX_GRANTS} recovery grants used)",
406 self.id
407 )
408 }
409
410 pub(crate) fn record_land_sync_exhausted_stop(&mut self, head: &str, pr_head: &str, tip: &str) {
412 let Some(pr) = self.pr.as_ref() else {
413 return;
414 };
415 let limit = self.land_sync_budget();
416 if self.land_sync_recovery.stop.as_ref().is_some_and(|s| {
417 s.attempts == self.land_sync_attempts
418 && s.limit == limit
419 && s.head.eq_ignore_ascii_case(head)
420 && s.pr_head.eq_ignore_ascii_case(pr_head)
421 && s.pr_url == pr.url
422 && s.pr_number == pr.number
423 && s.detail == EXHAUSTED_DETAIL
424 }) {
425 return;
426 }
427 let at = exhausted_stop_timestamp(self);
428 let stop = Stop {
429 attempts: self.land_sync_attempts,
430 limit,
431 head: head.to_ascii_lowercase(),
432 pr_head: pr_head.to_ascii_lowercase(),
433 pr_url: pr.url.clone(),
434 pr_number: pr.number,
435 tip: tip.to_ascii_lowercase(),
436 detail: EXHAUSTED_DETAIL.to_owned(),
437 at,
438 };
439 if !self.land_sync_recovery.stops.contains(&stop) {
440 self.land_sync_recovery.stops.push(stop.clone());
441 }
442 self.land_sync_recovery.stop = Some(stop);
443 }
444
445 pub(crate) fn consume_land_sync_recovery(
451 &mut self,
452 head: &str,
453 pr_head: &str,
454 ) -> std::result::Result<(), String> {
455 if !self.land_sync_recovery_pending() {
456 return Err("no matching pending landing base-sync recovery authorization".into());
457 }
458 let now = Timestamp::now();
459 let granted = self
460 .land_sync_recovery
461 .authorizations
462 .last()
463 .map(|a| a.granted_attempts)
464 .unwrap_or(0);
465 let Some(next_extra) = self.land_sync_recovery.extra_attempts.checked_add(granted) else {
466 return Err("landing base-sync grant counter overflow".into());
467 };
468 if granted != GRANT_ATTEMPTS || next_extra > MAX_GRANTS {
469 if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
470 auth.refuse(format!(
471 "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
472 self.land_sync_recovery.extra_attempts
473 ));
474 }
475 return Err("lifetime landing base-sync recovery limit reached".into());
476 }
477 let head_mismatch = self
478 .land_sync_recovery
479 .authorizations
480 .last()
481 .is_some_and(|a| {
482 !a.stop.head.eq_ignore_ascii_case(head)
483 || !a.stop.pr_head.eq_ignore_ascii_case(pr_head)
484 });
485 if head_mismatch {
486 if let Some(auth) = self.land_sync_recovery.authorizations.last_mut() {
487 auth.refuse(format!(
488 "retained/published HEAD changed from {}/{} to {head}/{pr_head}",
489 auth.stop.head, auth.stop.pr_head
490 ));
491 }
492 return Err("retained or published HEAD changed before consumption".into());
493 }
494
495 let gate = std::mem::take(&mut self.gate);
498 let gate_head = self.gate_head.take();
499 let gate_ran = std::mem::replace(&mut self.gate_ran, false);
500 let head_e2e = self.head_e2e.take();
501 let gate_repair_e2e = self.gate_repair_e2e.take();
502 self.pre_gate.clear();
503 self.pre_gate_commit = None;
504
505 let mut review_verified_heads = Vec::with_capacity(self.reviews.len());
506 for review in &mut self.reviews {
507 review_verified_heads.push((review.round, review.verified_head.take()));
508 }
509
510 if gate_ran || !gate.is_empty() || head_e2e.is_some() {
511 self.verification_history.push(VerificationEvidence {
512 superseded_by: None,
513 archived_at: Some(now),
514 fixes_spent: Some(self.gate_fixes.len()),
515 gate_head: gate_head.clone(),
516 gate_ran,
517 gate: gate.clone(),
518 e2e: head_e2e.clone(),
519 });
520 }
521 if let Some(repair_e2e) = &gate_repair_e2e {
522 self.verification_history.push(VerificationEvidence {
523 superseded_by: None,
524 archived_at: Some(now),
525 fixes_spent: Some(self.gate_fixes.len()),
526 gate_head: None,
527 gate_ran: false,
528 gate: Vec::new(),
529 e2e: Some(repair_e2e.clone()),
530 });
531 }
532
533 let archived = ArchivedVerification {
534 archived_at: now,
535 head: head.to_ascii_lowercase(),
536 gate_head,
537 gate_ran,
538 gate,
539 head_e2e,
540 gate_repair_e2e,
541 review_verified_heads,
542 };
543
544 let auth = self
545 .land_sync_recovery
546 .authorizations
547 .last_mut()
548 .expect("pending authorization exists");
549 auth.consumed = true;
550 auth.consumed_at = Some(now);
551 auth.archived_verification = Some(archived);
552
553 self.land_sync_recovery.extra_attempts = next_extra;
554 self.land_sync_recovery.stop = None;
555 Ok(())
556 }
557}
558
559pub(crate) fn queue_existing_authorization(queue: &Queue, task: &mut Task, run: &str) -> bool {
561 let Some(state) = latest_exhausted_run(queue, task) else {
562 return false;
563 };
564 if state.id != run || !(state.land_sync_recovery_pending() || state.land_sync_unstarted_grant())
565 {
566 return false;
567 }
568 let Some(auth) = state.land_sync_recovery.authorizations.last() else {
569 return false;
570 };
571 if task.id != auth.task
572 || !task.assignment_accepts(&state)
573 || task.instruction != auth.scope.instruction
574 || task.operator_decided_at != auth.decision
575 || auth
576 .generation
577 .is_some_and(|g| task.resumption.as_ref().map(|r| r.generation) != Some(g))
578 || !task.land_sync_recovery_requests.contains(&auth.request)
579 || task.fresh_start
580 || task.review_branch.is_some()
581 || task.pr_recovery.is_some()
582 || matches!(task.status, TaskStatus::Running | TaskStatus::Done)
583 {
584 return false;
585 }
586 task.status = TaskStatus::Queued;
587 task.hold_source = None;
588 task.hold_reason = None;
589 task.held_at = None;
590 true
591}
592
593pub(crate) fn held_task(queue: &Queue, task: &Task) -> bool {
596 held_run(queue, task).is_some()
597}
598
599pub(crate) fn held_run(queue: &Queue, task: &Task) -> Option<RunState> {
602 latest_exhausted_run(queue, task).filter(|state| !state.land_sync_recovery_pending())
603}
604
605pub(crate) fn latest_exhausted_run(queue: &Queue, task: &Task) -> Option<RunState> {
608 let home = queue.root().parent()?;
609 task.execution_runs()
610 .last()
611 .and_then(|id| RunState::load_under(id, home).ok())
612 .filter(|state| {
613 state.land_sync_exhausted()
614 || state.has_unconsumed_land_sync_authorization()
615 || state.land_sync_unstarted_grant()
616 })
617}
618
619#[derive(Debug)]
626pub(crate) struct ValidationFailure {
627 pub reason: String,
628 pub observation_failed: bool,
629}
630
631impl ValidationFailure {
632 fn observation(reason: String) -> Self {
633 Self {
634 reason,
635 observation_failed: true,
636 }
637 }
638}
639
640impl From<String> for ValidationFailure {
641 fn from(reason: String) -> Self {
642 Self {
643 reason,
644 observation_failed: false,
645 }
646 }
647}
648
649impl From<&str> for ValidationFailure {
650 fn from(reason: &str) -> Self {
651 reason.to_owned().into()
652 }
653}
654
655pub(crate) async fn validate_pending_authorization<O: PrObserver>(
656 home: &Path,
657 state: &RunState,
658 task_override: Option<&Task>,
659 observed_override: Option<&ObservedPr>,
660 observer: &O,
661) -> std::result::Result<(String, String), ValidationFailure> {
662 let unstarted = state.land_sync_unstarted_grant();
663 if !state.land_sync_recovery_pending() && !unstarted {
664 return Err("landing base-sync stop or pending authorization state changed".into());
665 }
666 if let Err(error) = crate::pr_head::ensure_owner(state) {
667 return Err(format!("run ownership check failed: {error:#}").into());
668 }
669 let auth = state
670 .land_sync_recovery
671 .authorizations
672 .last()
673 .ok_or_else(|| "missing pending landing base-sync authorization".to_owned())?;
674 if auth.invalidated.is_some() {
675 return Err("landing base-sync recovery authorization was invalidated".into());
676 }
677 if auth.granted_attempts != GRANT_ATTEMPTS
678 || (!unstarted && state.land_sync_grants_remaining() < auth.granted_attempts)
679 {
680 return Err(format!(
681 "lifetime landing base-sync recovery limit reached ({}/{MAX_GRANTS})",
682 state.land_sync_recovery.extra_attempts
683 )
684 .into());
685 }
686
687 if !auth.task.is_empty() {
688 let loaded_task;
689 let task = match task_override {
690 Some(task) => task,
691 None => {
692 loaded_task = Queue::at(home.join("queue")).get(&auth.task).map_err(|e| {
693 ValidationFailure::observation(format!(
694 "owning task {} unreadable: {e:#}",
695 auth.task
696 ))
697 })?;
698 &loaded_task
699 }
700 };
701 if task.id != auth.task {
702 return Err("authorization targets a different task".into());
703 }
704 if state
705 .origin
706 .as_ref()
707 .and_then(|o| o.task.as_deref())
708 .is_some_and(|owner| owner != task.id)
709 {
710 return Err("run belongs to another task".into());
711 }
712 if task.execution_runs().last().map(String::as_str) != Some(state.id.as_str()) {
713 return Err("run is no longer the task's latest execution".into());
714 }
715 if !task.assignment_accepts(state) || task.reassignments.len() != auth.scope.assignment {
716 return Err("task repository assignment changed since authorization".into());
717 }
718 if task.status == TaskStatus::Done
719 || task.fresh_start
720 || task.review_branch.is_some()
721 || task.pr_recovery.is_some()
722 {
723 return Err("task queue state changed since authorization".into());
724 }
725 if task.instruction != auth.scope.instruction
726 || !crate::daemon::compatible_run_instruction(state, task)
727 {
728 return Err("task instruction changed since authorization".into());
729 }
730 if task.operator_decided_at != auth.decision {
731 return Err("a newer owner decision superseded this recovery authorization".into());
732 }
733 if let Some(generation) = auth.generation
734 && task.resumption.as_ref().map(|r| r.generation) != Some(generation)
735 {
736 return Err("task resumption generation changed since authorization".into());
737 }
738 if task_override.is_some()
739 && !task
740 .resume_override
741 .as_ref()
742 .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
743 && !(task.resume_override.is_none()
744 && task.land_sync_recovery_requests.contains(&auth.request))
745 {
746 return Err("task exact-run pin is missing or targets another run".into());
747 }
748 }
749
750 let winner = state
751 .winner()
752 .ok_or_else(|| "run has no retained winner".to_owned())?;
753 let clean = git::is_clean(&winner.worktree).await.map_err(|e| {
754 ValidationFailure::observation(format!(
755 "could not inspect retained worktree cleanliness: {e:#}"
756 ))
757 })?;
758 if !clean {
759 return Err("retained worktree has uncommitted changes".into());
760 }
761 let scratch = home.join("runs").join(&state.id).join("rebase");
762 let rebase_in_progress = git::checked_rebase_in_progress(&scratch)
763 .await
764 .map_err(|e| {
765 ValidationFailure::observation(format!("could not inspect scratch rebase state: {e:#}"))
766 })?;
767 if rebase_in_progress {
768 return Err("landing rebase is already in progress in scratch worktree".into());
769 }
770 let local_head = git::rev_parse(&winner.worktree, "HEAD")
771 .await
772 .map_err(|e| {
773 ValidationFailure::observation(format!("could not read retained worktree HEAD: {e:#}"))
774 })?;
775 let branch_head = git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch))
776 .await
777 .map_err(|e| {
778 ValidationFailure::observation(format!("could not read winner branch ref: {e:#}"))
779 })?;
780 if local_head != branch_head {
781 return Err("retained worktree HEAD does not match the winner branch ref".into());
782 }
783 if !local_head.eq_ignore_ascii_case(&auth.stop.head) {
784 return Err(format!(
785 "retained HEAD changed from {} to {local_head}",
786 auth.stop.head
787 )
788 .into());
789 }
790 if !state
791 .pr_pushed_head
792 .as_deref()
793 .is_some_and(|h| h.eq_ignore_ascii_case(&local_head))
794 {
795 return Err("saved pr_pushed_head no longer matches the retained HEAD".into());
796 }
797 if !auth.stop.pr_head.eq_ignore_ascii_case(&local_head)
798 || !auth.scope.pr_head.eq_ignore_ascii_case(&local_head)
799 {
800 return Err("authorized PR head does not match the retained HEAD".into());
801 }
802 if !state.pr.as_ref().is_some_and(|pr| {
803 pr.state == "open" && pr.url == auth.scope.pr_url && pr.number == auth.scope.pr_number
804 }) {
805 return Err("recorded pull request metadata changed since authorization".into());
806 }
807
808 let fetched_pr;
809 let observed = match observed_override {
810 Some(observed) => observed,
811 None => {
812 fetched_pr = observer
813 .observe_pr(&state.repo, &auth.scope.pr_url)
814 .await
815 .map_err(|e| {
816 ValidationFailure::observation(format!(
817 "could not verify open pull request state: {e:#}"
818 ))
819 })?;
820 &fetched_pr
821 }
822 };
823 if !observed.open {
824 return Err("pull request is no longer open".into());
825 }
826 if observed.url != auth.scope.pr_url || observed.number != auth.scope.pr_number {
827 return Err("observed pull request does not match authorized pull request".into());
828 }
829 if observed.head.len() != 40 || !observed.head.bytes().all(|b| b.is_ascii_hexdigit()) {
830 return Err(ValidationFailure::observation(
831 "observed pull request head is unreadable".into(),
832 ));
833 }
834 if !observed.head.eq_ignore_ascii_case(&local_head) {
835 return Err(format!(
836 "published PR head changed from {} to {}",
837 auth.scope.pr_head, observed.head
838 )
839 .into());
840 }
841 if observed
842 .base_branch
843 .as_deref()
844 .is_some_and(|b| !b.is_empty() && b != state.base_branch)
845 {
846 return Err("pull request base branch changed since authorization".into());
847 }
848
849 let fetched = git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch)
850 .await
851 .map_err(|e| {
852 ValidationFailure::observation(format!(
853 "could not fetch base branch for revalidation: {e:#}"
854 ))
855 })?;
856 if !fetched.ok() {
857 return Err(ValidationFailure::observation(format!(
858 "could not fetch base branch for revalidation: {}",
859 fetched.stderr
860 )));
861 }
862 let onto = format!("{}/{}", state.config.merge.remote, state.base_branch);
863 let current_tip = git::rev_parse(&state.repo, &onto).await.map_err(|e| {
864 ValidationFailure::observation(format!("could not resolve fetched base tip: {e:#}"))
865 })?;
866 let descends_scope = git::ancestry(&state.repo, &auth.scope.tip, ¤t_tip)
867 .await
868 .map_err(|e| {
869 ValidationFailure::observation(format!(
870 "could not verify base tip lineage against authorized tip: {e:#}"
871 ))
872 })?;
873 if !descends_scope {
874 return Err(format!(
875 "fetched base tip {current_tip} does not fast-forward from authorized tip {}",
876 auth.scope.tip
877 )
878 .into());
879 }
880 let descends_stop = git::ancestry(&state.repo, &auth.stop.tip, ¤t_tip)
881 .await
882 .map_err(|e| {
883 ValidationFailure::observation(format!(
884 "could not verify base tip lineage against stopped tip: {e:#}"
885 ))
886 })?;
887 if !descends_stop {
888 return Err(format!(
889 "fetched base tip {current_tip} does not fast-forward from stopped tip {}",
890 auth.stop.tip
891 )
892 .into());
893 }
894
895 Ok((local_head, observed.head.clone()))
896}
897
898pub(crate) enum DispatchDecision {
900 Proceed,
902 Hold {
904 reason: String,
905 state: Box<RunState>,
906 },
907}
908
909pub(crate) async fn dispatch_check(queue: &Queue, home: &Path, task: &Task) -> DispatchDecision {
911 dispatch_check_with(queue, home, task, &GhPrObserver).await
912}
913
914pub(crate) async fn dispatch_check_with<O: PrObserver>(
916 queue: &Queue,
917 home: &Path,
918 task: &Task,
919 observer: &O,
920) -> DispatchDecision {
921 let Some(state) = latest_exhausted_run(queue, task) else {
922 return DispatchDecision::Proceed;
923 };
924 if task
927 .resume_override
928 .as_ref()
929 .is_some_and(|pin| pin.pinned_run.as_deref() == Some(state.id.as_str()))
930 && let Some(pr) = &state.pr
931 && let Ok(observed) = observer.observe_pr(&state.repo, &pr.url).await
932 && !observed.open
933 && observed.url == pr.url
934 && observed.number == pr.number
935 {
936 return DispatchDecision::Proceed;
937 }
938 if !state.has_unconsumed_land_sync_authorization() && !state.land_sync_unstarted_grant() {
939 return DispatchDecision::Hold {
940 reason: format!(
941 "Landing base synchronization remains stopped. {} Ordinary resume or release grants no additional synchronization budget and starts no replacement competition.",
942 state.land_sync_next_action()
943 ),
944 state: Box::new(state),
945 };
946 }
947 match validate_pending_authorization(home, &state, Some(task), None, observer).await {
948 Ok(_) => DispatchDecision::Proceed,
949 Err(failure) => {
950 let reason = failure.reason;
951 let mut updated = state;
952 if !failure.observation_failed
953 && let Ok(_owner) = crate::pr_head::owner_lock(home, &updated.id)
954 && let Ok(mut reloaded) = RunState::load_under(&updated.id, home)
955 && let Ok(claimed) =
956 crate::daemon::is_working_on_other(home, &reloaded.id, Timestamp::now())
957 && reloaded.liveness_under(home, claimed) == crate::run::Liveness::Dead
958 && let Ok(_exec) = crate::driver::maintenance(home, &reloaded.id)
959 && (reloaded.land_sync_recovery_pending() || reloaded.land_sync_unstarted_grant())
960 && let Some(auth) = reloaded.land_sync_recovery.authorizations.last_mut()
961 && auth.invalidated.is_none()
962 && updated
963 .land_sync_recovery
964 .authorizations
965 .last()
966 .is_some_and(|prior| prior.request == auth.request)
967 {
968 auth.refuse(&reason);
969 reloaded.event(
970 "land-sync-recovery",
971 format!("dispatch revalidation refused: {reason}"),
972 );
973 let _ = reloaded.save_under(home);
974 updated = reloaded;
975 }
976 DispatchDecision::Hold {
977 reason: format!(
978 "Landing base-sync recovery refused at dispatch: {reason}. {}",
979 updated.land_sync_next_action()
980 ),
981 state: Box::new(updated),
982 }
983 }
984 }
985}
986
987impl Task {
988 pub(crate) fn land_sync_notice(&mut self, state: &RunState) {
990 if !state.land_sync_exhausted() {
991 return;
992 }
993 let stop = state.land_sync_recovery.stop.as_ref();
994 self.held_at = Some(stop.map_or_else(|| exhausted_stop_timestamp(state), |s| s.at));
995 self.notice_cause("land-sync-exhausted", Some(&state.id), None);
996 if let Some(cause) = &mut self.hold_notice_cause {
997 cause.target = Some(match stop {
998 Some(s) => format!("{}:{}:{}:{}", s.head, s.attempts, s.limit, s.at),
999 None => format!(
1000 "legacy:{}:{}:{}",
1001 state.pr_pushed_head.as_deref().unwrap_or("unknown"),
1002 state.land_sync_attempts,
1003 state.land_sync_budget()
1004 ),
1005 });
1006 }
1007 }
1008}