1#[cfg(test)]
34thread_local! {
35 pub(crate) static LIST_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
36}
37
38use std::collections::HashMap;
39use std::num::NonZeroUsize;
40use std::path::{Path, PathBuf};
41
42use anyhow::{Context, Result, bail};
43use jiff::Timestamp;
44use serde::{Deserialize, Serialize};
45
46use crate::ask::Questions;
47use crate::config::BuildCache;
48use crate::id_reserve::{IdSource, path_exists};
49
50pub const SCHEMA: u32 = 28;
155
156const RECOVERY_HOLD_SCHEMA: u32 = 24;
157const REOPEN_HOLD_SCHEMA: u32 = 28;
158
159pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
165 match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
166 (Some(a), Some(b)) => a.cmp(&b),
167 (Some(_), None) => std::cmp::Ordering::Less,
168 (None, Some(_)) => std::cmp::Ordering::Greater,
169 (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
170 }
171}
172
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(tag = "kind", rename_all = "snake_case")]
181pub enum MachineHoldCause {
182 DiskCapacity {
184 reason: String,
186 #[serde(default)]
188 before_start: bool,
189 },
190 HeadE2e {
192 stop: crate::head_e2e_stop::Stop,
194 },
195}
196
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
199#[serde(rename_all = "lowercase")]
200pub enum HoldSource {
201 Manual,
203 Machine,
205}
206
207impl HoldSource {
208 pub fn label(self) -> &'static str {
210 match self {
211 Self::Manual => "manual",
212 Self::Machine => "machine",
213 }
214 }
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(tag = "kind", rename_all = "lowercase")]
221pub enum Source {
222 Human,
224 Agent {
227 run: String,
229 node: String,
231 },
232 Issue {
234 number: u64,
236 repo: String,
238 },
239}
240
241#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243pub struct IssueRef {
244 pub number: u64,
246 pub repo: String,
248}
249
250pub const CHAT_NODE: &str = "chat";
253
254impl Source {
255 pub fn label(&self) -> String {
257 match self {
258 Self::Human => "human".to_owned(),
259 Self::Agent { run, node } => format!("{node}@{}", short(run)),
260 Self::Issue { number, .. } => format!("issue #{number}"),
261 }
262 }
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "lowercase")]
268pub enum TaskStatus {
269 Queued,
271 Running,
273 Done,
275 Failed,
277 Held,
279 Blocked,
283 Parked,
288}
289
290impl TaskStatus {
291 pub fn runnable(self) -> bool {
293 matches!(self, Self::Queued | Self::Failed | Self::Parked)
294 }
295
296 pub fn as_str(self) -> &'static str {
298 match self {
299 Self::Queued => "queued",
300 Self::Running => "running",
301 Self::Done => "done",
302 Self::Failed => "failed",
303 Self::Held => "held",
304 Self::Blocked => "blocked",
305 Self::Parked => "parked",
306 }
307 }
308}
309
310#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
313pub struct TaskCounts {
314 pub queued: usize,
316 pub running: usize,
318 pub done: usize,
320 pub failed: usize,
322 pub held: usize,
324 pub blocked: usize,
326 pub parked: usize,
328}
329
330impl TaskCounts {
331 pub fn of(tasks: &[Task]) -> Self {
335 Self::of_statuses(tasks.iter().map(|task| task.status))
336 }
337
338 pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
340 let mut counts = Self::default();
341 for status in statuses {
342 match status {
343 TaskStatus::Queued => counts.queued += 1,
344 TaskStatus::Running => counts.running += 1,
345 TaskStatus::Done => counts.done += 1,
346 TaskStatus::Failed => counts.failed += 1,
347 TaskStatus::Held => counts.held += 1,
348 TaskStatus::Blocked => counts.blocked += 1,
349 TaskStatus::Parked => counts.parked += 1,
350 }
351 }
352 counts
353 }
354}
355
356#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
358pub struct Reassignment {
359 pub from: PathBuf,
361 pub to: PathBuf,
363 pub actor: String,
365 pub at: Timestamp,
367 pub run_boundary: usize,
369}
370
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373#[serde(tag = "kind", content = "talk", rename_all = "snake_case")]
374pub enum CompletionActor {
375 Cli,
377 Web,
379 Chat(String),
381 Conductor,
383 DaemonSettle,
385}
386
387#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
389#[serde(rename_all = "snake_case")]
390pub enum CompletionAction {
391 Complete,
393 Reopen,
395}
396
397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399struct ReopenHold {
400 occurrence: String,
401 held_at: Timestamp,
402 decision: Option<Timestamp>,
403 #[serde(default)]
404 legacy: bool,
405}
406
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
409pub struct CompletionRunSnapshot {
410 pub id: String,
412 pub status: Option<crate::run::RunStatus>,
414 pub pr_url: Option<String>,
416 pub pr_state: Option<String>,
418 pub pr_head: Option<String>,
420 #[serde(default)]
422 pub branches: Vec<String>,
423 pub error: Option<String>,
425}
426
427impl CompletionRunSnapshot {
428 fn from_run(state: &crate::run::RunState) -> Self {
429 let mut branches: Vec<String> = state
430 .candidates
431 .iter()
432 .map(|candidate| candidate.branch.clone())
433 .collect();
434 if let Some(branch) = &state.pr_head
435 && !branches.contains(branch)
436 {
437 branches.push(branch.clone());
438 }
439 Self {
440 id: state.id.clone(),
441 status: Some(state.status),
442 pr_url: state.pr.as_ref().map(|pr| pr.url.clone()),
443 pr_state: state.pr.as_ref().map(|pr| pr.state.clone()),
444 pr_head: state
445 .pr_merged_head
446 .clone()
447 .or_else(|| state.pr_pushed_head.clone()),
448 branches,
449 error: None,
450 }
451 }
452}
453
454#[derive(Debug, Clone)]
456pub struct CompletionContext {
457 pub actor: CompletionActor,
459 pub reason: Option<String>,
461 pub discard: bool,
463 pub run: Option<CompletionRunSnapshot>,
465 pub unavailable_runs: Vec<String>,
467}
468
469impl CompletionContext {
470 pub fn new(actor: CompletionActor, reason: Option<String>, home: &Path, task: &Task) -> Self {
472 let run = task
473 .runs
474 .last()
475 .map(|id| match crate::run::RunState::load_under(id, home) {
476 Ok(state) => CompletionRunSnapshot::from_run(&state),
477 Err(error) => CompletionRunSnapshot {
478 id: id.clone(),
479 status: None,
480 pr_url: None,
481 pr_state: None,
482 pr_head: None,
483 branches: Vec::new(),
484 error: Some(format!("{error:#}")),
485 },
486 });
487 Self {
488 actor,
489 reason,
490 discard: false,
491 run,
492 unavailable_runs: Vec::new(),
493 }
494 }
495
496 pub fn from_run(
498 actor: CompletionActor,
499 reason: Option<String>,
500 _task: &Task,
501 state: &crate::run::RunState,
502 ) -> Self {
503 Self {
504 actor,
505 reason,
506 discard: false,
507 run: Some(CompletionRunSnapshot::from_run(state)),
508 unavailable_runs: Vec::new(),
509 }
510 }
511}
512
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515pub struct CompletionEvent {
516 pub occurrence: String,
518 pub action: CompletionAction,
520 pub actor: CompletionActor,
522 pub reason: Option<String>,
524 pub discard: bool,
526 pub prior_status: TaskStatus,
528 #[serde(default)]
530 pub prior_hold_reason: Option<String>,
531 #[serde(default)]
533 pub prior_block_reason: Option<String>,
534 #[serde(default)]
536 pub prior_error: Option<String>,
537 pub at: Timestamp,
539 pub run: Option<CompletionRunSnapshot>,
541 #[serde(default, skip_serializing_if = "Vec::is_empty")]
543 pub unavailable_runs: Vec<String>,
544}
545
546#[derive(Debug, Clone, Serialize, Deserialize)]
548#[serde(deny_unknown_fields)]
549pub struct Task {
550 pub schema: u32,
552 pub id: String,
554 pub title: String,
556 pub instruction: String,
558 #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
560 pub sources: crate::refs::Sources,
561 pub repo: PathBuf,
563 #[serde(default)]
565 pub reassignments: Vec<Reassignment>,
566 pub source: Source,
568 #[serde(default, skip_serializing_if = "Option::is_none")]
570 pub issue: Option<IssueRef>,
571 #[serde(default)]
573 pub chat: Option<String>,
574 #[serde(default)]
576 pub priority: i32,
577 #[serde(default)]
588 pub solo: bool,
589 pub status: TaskStatus,
591 #[serde(default)]
593 pub completion_history: Vec<CompletionEvent>,
594 #[serde(default)]
596 pub attempts: usize,
597 #[serde(default)]
599 pub attempt_limit: Option<NonZeroUsize>,
600 #[serde(default)]
603 pub runs: Vec<String>,
604 #[serde(default)]
606 pub startup_failures: Vec<crate::run::StartupFailure>,
607 #[serde(default)]
609 pub last_error: Option<String>,
610 #[serde(default)]
623 pub hold_reason: Option<String>,
624 #[serde(default)]
627 pub hold_source: Option<HoldSource>,
628 #[serde(default, skip_serializing_if = "Option::is_none")]
629 recovery_budget_hold: Option<RecoveryBudgetHold>,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
633 reopen_hold: Option<ReopenHold>,
634 #[serde(default)]
636 pub machine_hold_cause: Option<MachineHoldCause>,
637 #[serde(default)]
639 pub disk_resume_run: Option<String>,
640 #[serde(default)]
642 pub disk_checked_at: Option<Timestamp>,
643 #[serde(default)]
655 pub diagnostic: Option<String>,
656 #[serde(default)]
666 pub blocked_by: Vec<String>,
667 #[serde(default)]
670 pub block_reason: Option<String>,
671 #[serde(default)]
684 pub blocked_from: Option<TaskStatus>,
685 #[serde(default)]
687 pub blocked_at: Option<Timestamp>,
688 #[serde(default)]
699 pub answers: Vec<AnsweredQuestion>,
700 #[serde(default)]
706 pub triage_applied: Vec<String>,
707 #[serde(default)]
713 pub actions_applied: Vec<String>,
714 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
717 pub decision_effects: std::collections::BTreeMap<String, String>,
718 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
721 pub superseded_resumes: std::collections::BTreeMap<String, String>,
722 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
726 pub dispatched_resumes: std::collections::BTreeMap<String, String>,
727 #[serde(default)]
729 pub base_recovery_requests: Vec<String>,
730 #[serde(default)]
732 pub land_sync_recovery_requests: Vec<String>,
733 #[serde(default)]
738 pub resume_override: Option<OperatorResume>,
739 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub sync_only: Option<crate::base_sync_only::Request>,
742 #[serde(default)]
744 pub repair_grants: Vec<crate::repair_budget::Receipt>,
745 #[serde(default)]
747 pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
748 #[serde(default)]
751 pub resumption: Option<Resumption>,
752 #[serde(default)]
754 pub resumption_history: Vec<Resumption>,
755 #[serde(default)]
757 pub operator_decided_at: Option<Timestamp>,
758 #[serde(default)]
770 pub review_branch: Option<String>,
771 #[serde(default)]
773 pub review_instruction: Option<String>,
774 #[serde(default)]
776 pub pr_recovery: Option<crate::pr_recovery::Selection>,
777 #[serde(default)]
780 pub fresh_start: bool,
781 #[serde(default)]
783 pub replacement: Option<crate::merge_decision::Replacement>,
784 #[serde(default)]
795 pub interrupt: bool,
796 #[serde(default)]
819 pub urgent: bool,
820 #[serde(default)]
834 pub immediate: bool,
835 #[serde(skip)]
840 pub(crate) unfiled: bool,
841 #[serde(default)]
847 pub attachments: Vec<String>,
848 #[serde(default)]
852 pub followup: Option<FollowUp>,
853 #[serde(default)]
859 pub origin_chat: Option<String>,
860 #[serde(default)]
867 pub overrides: Option<RunOverrides>,
868 #[serde(default)]
875 pub review_of: Option<String>,
876 #[serde(default)]
881 pub held_at: Option<Timestamp>,
882 #[serde(default)]
886 pub park_reason: Option<String>,
887 #[serde(default)]
890 pub chat_notice: Option<ChatNotice>,
891 #[serde(default)]
893 pub chat_notices: Vec<String>,
894 #[serde(default)]
897 pub hold_notice_cause: Option<NoticeCause>,
898 #[serde(default)]
903 pub passes: Vec<TaskPass>,
904 #[serde(default)]
908 pub dispatched_at: Option<Timestamp>,
909 #[serde(default)]
911 pub recovery_budget: Option<RecoveryBudget>,
912 #[serde(default)]
915 pub recovery_admission: Option<RecoveryAdmission>,
916 #[serde(default)]
919 pub recovery_generations: Vec<RecoveryBudget>,
920 pub created_at: Timestamp,
922 pub updated_at: Timestamp,
924}
925
926#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
928pub struct RecoveryAdmission {
929 pub base: String,
931 pub inputs: String,
933}
934
935#[derive(Debug, Clone, Serialize, Deserialize)]
936struct RecoveryBudgetHold {
937 admission: RecoveryAdmission,
938 run: String,
939 pass: usize,
940 held_at: Timestamp,
941 decision: Option<Timestamp>,
942 #[serde(default)]
943 legacy: bool,
944}
945
946#[derive(Debug, Clone, Serialize, Deserialize)]
949pub struct RecoveryBudget {
950 pub instruction: String,
952 pub base: String,
954 pub inputs: String,
956 pub stage: String,
958 pub failures: usize,
960 #[serde(default)]
963 pub progress: Option<String>,
964}
965
966impl RecoveryBudget {
967 fn budget_reason(&self) -> String {
968 format!(
969 "[recovery-budget] {} failed passes against unchanged inputs ({}). Inspect the retained recovery sources and correct the cause, change the inputs, or explicitly release the task to approve another generation. Automatic requeue does not reset this budget.",
970 self.failures, self.stage
971 )
972 }
973}
974
975fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
976 use crate::proc::Quiet as _;
977 use std::hash::{Hash, Hasher};
978 let mut patches = Vec::new();
979 for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
980 let output = std::process::Command::new("git")
981 .current_dir(&state.repo)
982 .args(["diff", "--binary", &state.base_commit, &candidate.branch])
983 .quiet()
984 .output()
985 .ok()?;
986 if !output.status.success() {
987 return None;
988 }
989 patches.push(output.stdout);
990 }
991 patches.sort();
992 patches.dedup();
993 let mut hash = std::collections::hash_map::DefaultHasher::new();
994 patches.hash(&mut hash);
995 Some(format!("{:x}", hash.finish()))
996}
997
998pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
1002 serde_json::to_string(
1003 &sources
1004 .start_from
1005 .iter()
1006 .map(|i| ("start", &i.token, &i.sha))
1007 .chain(
1008 sources
1009 .pick_commits
1010 .iter()
1011 .map(|i| ("pick", &i.token, &i.sha)),
1012 )
1013 .collect::<Vec<_>>(),
1014 )
1015 .unwrap_or_default()
1016}
1017
1018#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1020pub struct NoticeCause {
1021 pub stage: String,
1023 #[serde(default, skip_serializing_if = "Option::is_none")]
1026 pub target: Option<String>,
1027 pub run: Option<String>,
1029 pub pass: Option<usize>,
1031}
1032
1033pub(crate) fn is_done_notice_key(key: &str) -> bool {
1035 key == "done"
1036 || key
1037 .strip_prefix("done#")
1038 .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
1039}
1040
1041#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1043#[serde(rename_all = "snake_case")]
1044pub enum PassCost {
1045 Spent,
1047 Refunded,
1049}
1050
1051#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1053pub struct TaskPass {
1054 pub run: String,
1056 pub pass_index: usize,
1058 pub cost: PassCost,
1060 pub attempts_after: usize,
1062 #[serde(default)]
1064 pub started_at: Option<Timestamp>,
1065 pub settled_at: Timestamp,
1067 #[serde(default)]
1069 pub parked: Option<crate::run::ParkCause>,
1070}
1071
1072#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1074#[serde(rename_all = "lowercase")]
1075pub enum ChatNoticeOutcome {
1076 Posted,
1078 Skipped,
1080}
1081
1082#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1084pub struct ChatNotice {
1085 pub key: String,
1087 pub at: Timestamp,
1089 pub outcome: ChatNoticeOutcome,
1091}
1092
1093#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1095pub struct RunOverrides {
1096 #[serde(default)]
1099 pub inherit_daemon_options: bool,
1100 #[serde(default)]
1102 pub merge: Option<String>,
1103 #[serde(default)]
1105 pub candidates: Option<usize>,
1106 #[serde(default)]
1108 pub judges: Option<usize>,
1109 #[serde(default)]
1111 pub reviewers: Option<usize>,
1112 #[serde(default)]
1114 pub review_rounds: Option<usize>,
1115 #[serde(default)]
1117 pub seed: Option<u64>,
1118 #[serde(default)]
1120 pub config: Option<PathBuf>,
1121 #[serde(default, skip_serializing_if = "Option::is_none")]
1123 pub build_cache: Option<BuildCache>,
1124}
1125
1126impl RunOverrides {
1127 pub fn merge_over(&mut self, other: &RunOverrides) {
1129 macro_rules! take {
1130 ($($f:ident),*) => {$(
1131 if other.$f.is_some() {
1132 self.$f.clone_from(&other.$f);
1133 }
1134 )*};
1135 }
1136 take!(
1137 merge,
1138 candidates,
1139 judges,
1140 reviewers,
1141 review_rounds,
1142 seed,
1143 config,
1144 build_cache
1145 );
1146 }
1147
1148 pub fn apply(&self, config: &mut crate::config::Config) {
1150 if let Some(n) = self.candidates {
1151 config.graph.implementers = n;
1152 }
1153 if let Some(n) = self.judges {
1154 config.graph.judges = n;
1155 }
1156 if let Some(n) = self.reviewers {
1157 config.graph.reviewers = n;
1158 }
1159 if let Some(n) = self.review_rounds {
1160 config.graph.review_rounds = n;
1161 }
1162 if let Some(m) = &self.merge
1163 && let Ok(mode) = crate::daemon::merge_mode(m)
1164 {
1165 config.merge.mode = mode;
1166 }
1167 if let Some(s) = self.seed {
1168 config.blind.seed = Some(s);
1169 }
1170 if let Some(mode) = self.build_cache {
1171 config.verify.build_cache = mode;
1172 }
1173 }
1174}
1175
1176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1178pub struct FollowUp {
1179 pub run: String,
1181 #[serde(default)]
1183 pub origin_task: Option<String>,
1184 pub pr: String,
1186 pub findings: Vec<String>,
1188 pub generation: u32,
1191}
1192
1193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1195pub struct Resumption {
1196 pub generation: u64,
1198 pub source: String,
1200 pub question_id: Option<String>,
1202 pub at: Timestamp,
1204 pub instruction: String,
1206 pub answers_through: usize,
1208 pub runs_through: usize,
1211 pub cleared_reason: Option<String>,
1213 #[serde(default)]
1215 pub blocking_evidence: Vec<String>,
1216}
1217
1218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1221pub struct OperatorResume {
1222 pub question_id: String,
1224 pub at: Timestamp,
1226 #[serde(default)]
1229 pub conductor_rehold: Option<String>,
1230 #[serde(default)]
1233 pub forced: bool,
1234 #[serde(default)]
1241 pub pinned_run: Option<String>,
1242}
1243
1244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1247pub struct AnsweredQuestion {
1248 pub question: String,
1250 pub answer: String,
1252}
1253
1254fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1255 for entry in entries {
1256 if !ledger.contains(&entry) {
1257 ledger.push(entry);
1258 }
1259 }
1260}
1261
1262fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1263 older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1264 if !older.is_empty() {
1265 older.append(ledger);
1266 *ledger = older;
1267 }
1268}
1269
1270impl Task {
1271 pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1273 let now = Timestamp::now();
1274 let origin_chat = match &source {
1275 Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1276 _ => None,
1277 };
1278 Self {
1279 schema: SCHEMA,
1280 id: new_id(),
1281 title,
1282 instruction,
1283 sources: crate::refs::Sources::default(),
1284 repo,
1285 reassignments: Vec::new(),
1286 source,
1287 issue: None,
1288 chat: None,
1289 priority: 0,
1290 solo: false,
1291 status: TaskStatus::Queued,
1292 completion_history: Vec::new(),
1293 attempts: 0,
1294 attempt_limit: None,
1295 runs: Vec::new(),
1296 startup_failures: Vec::new(),
1297 last_error: None,
1298 hold_reason: None,
1299 hold_source: None,
1300 recovery_budget_hold: None,
1301 reopen_hold: None,
1302 machine_hold_cause: None,
1303 disk_resume_run: None,
1304 disk_checked_at: None,
1305 diagnostic: None,
1306 blocked_by: Vec::new(),
1307 block_reason: None,
1308 blocked_from: None,
1309 blocked_at: None,
1310 answers: Vec::new(),
1311 triage_applied: Vec::new(),
1312 actions_applied: Vec::new(),
1313 decision_effects: Default::default(),
1314 superseded_resumes: Default::default(),
1315 dispatched_resumes: Default::default(),
1316 base_recovery_requests: Vec::new(),
1317 land_sync_recovery_requests: Vec::new(),
1318 resume_override: None,
1319 sync_only: None,
1320 repair_grants: Vec::new(),
1321 repair_reconciliations: Vec::new(),
1322 resumption: None,
1323 resumption_history: Vec::new(),
1324 operator_decided_at: None,
1325 review_branch: None,
1326 review_instruction: None,
1327 pr_recovery: None,
1328 fresh_start: false,
1329 replacement: None,
1330 interrupt: false,
1331 urgent: false,
1332 immediate: false,
1333 unfiled: true,
1334 attachments: Vec::new(),
1335 followup: None,
1336 origin_chat,
1337 overrides: None,
1338 review_of: None,
1339 held_at: None,
1340 park_reason: None,
1341 chat_notice: None,
1342 chat_notices: Vec::new(),
1343 hold_notice_cause: None,
1344 passes: Vec::new(),
1345 dispatched_at: None,
1346 recovery_budget: None,
1347 recovery_admission: None,
1348 recovery_generations: Vec::new(),
1349 created_at: now,
1350 updated_at: now,
1351 }
1352 }
1353
1354 pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1356 self.stamp_schema();
1357 if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1358 self.hold_manual(Some(
1359 "Repository reassigned; inspect history and release to start fresh.".into(),
1360 ));
1361 }
1362 let at = Timestamp::now();
1363 self.reassignments.push(Reassignment {
1364 from: self.repo.clone(),
1365 to: repo.clone(),
1366 actor: actor.to_owned(),
1367 at,
1368 run_boundary: self.runs.len(),
1369 });
1370 self.repo = repo;
1371 self.review_branch = None;
1372 self.review_instruction = None;
1373 self.pr_recovery = None;
1374 self.replacement = None;
1375 self.interrupt = false;
1376 self.resume_override = None;
1377 self.fresh_start = true;
1378 self.operator_decided_at = Some(at);
1379 }
1380
1381 pub fn publication_branch(&self) -> String {
1383 crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1384 }
1385
1386 pub fn execution_runs(&self) -> &[String] {
1388 let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1389 self.runs.get(boundary..).unwrap_or_default()
1390 }
1391
1392 pub fn stale_pr_attention(&self, home: &Path) -> Option<String> {
1394 if self.status != TaskStatus::Done {
1395 return None;
1396 }
1397 let run = crate::run::RunState::load_under(self.execution_runs().last()?, home).ok()?;
1398 self.assignment_accepts(&run)
1399 .then(|| run.stale_pr_cause())
1400 .flatten()
1401 }
1402
1403 pub fn execution_run(&self, run: &str) -> bool {
1405 self.execution_runs().iter().any(|id| id == run)
1406 }
1407
1408 pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1410 self.reassignments.last().is_none_or(|boundary| {
1411 self.execution_run(&run.id)
1412 && run.task_assignment == self.reassignments.len()
1413 && run.created_at > boundary.at
1414 && run
1415 .repo
1416 .canonicalize()
1417 .ok()
1418 .zip(self.repo.canonicalize().ok())
1419 .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1420 })
1421 }
1422
1423 pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1425 self.reassignments
1426 .last()
1427 .is_some_and(|r| q.asked_at <= r.at)
1428 || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1429 }
1430
1431 pub fn chat_talk(&self) -> Option<&str> {
1433 if let Some(id) = &self.origin_chat {
1434 return Some(id);
1435 }
1436 match &self.source {
1437 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1438 _ => None,
1439 }
1440 }
1441
1442 pub fn filed_by_chat(&self) -> Option<&str> {
1446 match &self.source {
1447 Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1448 _ => None,
1449 }
1450 }
1451
1452 pub fn issue_ref(&self) -> Option<IssueRef> {
1454 self.issue.clone().or_else(|| match &self.source {
1455 Source::Issue { number, repo } => Some(IssueRef {
1456 number: *number,
1457 repo: repo.clone(),
1458 }),
1459 _ => None,
1460 })
1461 }
1462
1463 pub fn source_label(&self) -> String {
1465 let actor = self.source.label();
1466 match &self.issue {
1467 Some(issue) if self.source == Source::Human => format!("issue #{}", issue.number),
1468 Some(issue) => format!("{actor} · issue #{}", issue.number),
1469 None => actor,
1470 }
1471 }
1472
1473 pub fn chat_notice_key(&self) -> Option<String> {
1476 match self.status {
1477 TaskStatus::Done => Some(
1478 self.completion_history
1479 .iter()
1480 .rev()
1481 .find(|event| event.action == CompletionAction::Complete)
1482 .map_or_else(
1483 || "done".to_owned(),
1484 |event| format!("done:{}", event.occurrence),
1485 ),
1486 ),
1487 TaskStatus::Held => {
1488 let cause = self
1489 .hold_notice_cause
1490 .clone()
1491 .unwrap_or_else(|| self.unresolved_hold_cause());
1492 Some(format!(
1493 "cause:{}",
1494 serde_json::to_string(&cause).expect("cause")
1495 ))
1496 }
1497 TaskStatus::Blocked => {
1498 let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1499 let evidence = self
1502 .hold_notice_cause
1503 .as_ref()
1504 .filter(|c| c.stage.starts_with("conductor-evidence:"));
1505 Some(format!(
1506 "dependencies:{}",
1507 serde_json::to_string(&(ids, evidence)).expect("ids")
1508 ))
1509 }
1510 _ => None,
1511 }
1512 }
1513
1514 fn unresolved_hold_cause(&self) -> NoticeCause {
1515 NoticeCause {
1516 stage: "hold".into(),
1517 target: None,
1518 run: self.runs.last().cloned(),
1519 pass: None,
1520 }
1521 }
1522
1523 pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1525 let key = match self.status {
1526 TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1527 "held#{}",
1528 self.held_at.map(|t| t.to_string()).unwrap_or_default()
1529 )),
1530 TaskStatus::Blocked => Some(format!(
1531 "blocked#{}#{}",
1532 self.blocked_by.join(","),
1533 self.block_reason.as_deref().unwrap_or_default()
1534 )),
1535 _ => None,
1536 };
1537 key.filter(|key| self.legacy_notice_matches(key))
1538 }
1539
1540 pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1541 match self.status {
1542 TaskStatus::Held if self.hold_notice_cause.is_none() => key
1543 .strip_prefix("held#")
1544 .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1545 TaskStatus::Blocked
1546 if self
1547 .hold_notice_cause
1548 .as_ref()
1549 .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1550 {
1551 key.strip_prefix("blocked#").is_some_and(|tail| {
1552 let Some((ids, _)) = tail.split_once('#') else {
1553 return false;
1554 };
1555 let old: std::collections::BTreeSet<_> =
1556 ids.split(',').filter(|id| !id.is_empty()).collect();
1557 let current: std::collections::BTreeSet<_> =
1558 self.blocked_by.iter().map(String::as_str).collect();
1559 old == current
1560 })
1561 }
1562 _ => false,
1563 }
1564 }
1565
1566 fn import_chat_notice(&mut self) {
1567 if let Some(n) = &self.chat_notice {
1568 let key = if is_done_notice_key(&n.key) {
1569 "done".to_owned()
1570 } else if self.legacy_notice_matches(&n.key) {
1571 self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1572 } else {
1573 n.key.clone()
1574 };
1575 if !self.chat_notices.contains(&key) {
1576 self.chat_notices.push(key);
1577 }
1578 }
1579 }
1580
1581 pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1584 self.import_chat_notice();
1585 self.hold_notice_cause = Some(NoticeCause {
1586 stage: stage.to_owned(),
1587 target: None,
1588 run: run.map(str::to_owned),
1589 pass,
1590 });
1591 }
1592
1593 pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1596 let recovery_only = matches!(
1597 stage,
1598 "startup-source" | "startup-candidates" | "startup-public-head"
1599 );
1600 match self.hold_notice_cause.as_ref() {
1601 Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1602 None if recovery_only
1603 && self
1604 .chat_notice
1605 .as_ref()
1606 .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1607 {
1608 return;
1609 }
1610 _ => {}
1611 }
1612 self.notice_cause(stage, None, None);
1613 }
1614
1615 pub(crate) fn fail_startup(
1618 &mut self,
1619 stage: &str,
1620 why: impl Into<String>,
1621 max_attempts: usize,
1622 ) {
1623 let unresolved = self.hold_notice_cause.clone();
1624 self.fail(why, max_attempts);
1625 self.hold_notice_cause = unresolved;
1626 self.startup_notice_cause(stage);
1627 }
1628
1629 pub(crate) fn fail_startup_target(
1631 &mut self,
1632 stage: &str,
1633 target: String,
1634 why: impl Into<String>,
1635 max_attempts: usize,
1636 ) {
1637 self.fail_startup(stage, why, max_attempts);
1638 if let Some(cause) = self.hold_notice_cause.as_mut() {
1639 cause.target = Some(target);
1640 }
1641 }
1642
1643 pub fn chat_notice_due(&self) -> Option<String> {
1645 self.filed_by_chat()?;
1646 if self.schema < 13 {
1647 return None;
1648 }
1649 let key = self.chat_notice_key()?;
1650 if self.chat_notices.contains(&key) {
1651 return None;
1652 }
1653 match &self.chat_notice {
1654 Some(n)
1655 if n.key == key
1656 || (key == "done" && is_done_notice_key(&n.key))
1657 || self.legacy_notice_matches(&n.key) =>
1658 {
1659 None
1660 }
1661 _ => Some(key),
1662 }
1663 }
1664
1665 pub fn short(&self) -> &str {
1667 short(&self.id)
1668 }
1669
1670 pub fn mark_triage_applied(&mut self, question_id: &str) {
1672 if !self.triage_applied(question_id) {
1673 self.triage_applied.push(question_id.to_owned());
1674 }
1675 }
1676
1677 pub fn action_applied(&self, question_id: &str) -> bool {
1680 self.actions_applied.iter().any(|id| id == question_id)
1681 }
1682
1683 pub fn mark_action_applied(&mut self, question_id: &str) {
1685 if !self.action_applied(question_id) {
1686 self.actions_applied.push(question_id.to_owned());
1687 }
1688 }
1689
1690 pub fn triage_applied(&self, question_id: &str) -> bool {
1692 self.triage_applied.iter().any(|id| id == question_id)
1693 }
1694
1695 pub fn start(&mut self, run: String) {
1708 self.stamp_schema();
1709 self.status = TaskStatus::Running;
1710 self.attempts += 1;
1711 self.runs.retain(|id| id != &run);
1712 if let Some(pin) = &self.resume_override
1713 && pin.pinned_run.as_ref() == Some(&run)
1714 && !pin.question_id.is_empty()
1715 {
1716 self.dispatched_resumes
1717 .insert(pin.question_id.clone(), run.clone());
1718 }
1719 self.runs.push(run);
1720 self.last_error = None;
1721 self.park_reason = None;
1722 self.fresh_start = false;
1723 self.interrupt = false;
1724 self.resume_override = None;
1726 self.disk_resume_run = None;
1729 }
1730
1731 pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1733 if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1734 self.startup_failures.push(failure);
1735 }
1736 }
1737
1738 pub fn link_run(&mut self, run: &str) -> bool {
1743 if self.runs.iter().any(|r| r == run) {
1744 return false;
1745 }
1746 self.runs.push(run.to_owned());
1747 true
1748 }
1749
1750 pub fn succeed(&mut self, context: CompletionContext) {
1760 if self.status == TaskStatus::Done {
1761 return;
1762 }
1763 self.record_completion(CompletionAction::Complete, context);
1764 self.stamp_schema();
1765 self.status = TaskStatus::Done;
1766 if let Some(pin) = self.resume_override.take()
1767 && !pin.question_id.is_empty()
1768 && let Some(run) = pin.pinned_run
1769 {
1770 self.superseded_resumes.insert(pin.question_id, run);
1773 }
1774 self.sync_only = None;
1775 self.last_error = None;
1776 self.park_reason = None;
1777 self.hold_reason = None;
1778 self.hold_source = None;
1779 self.machine_hold_cause = None;
1780 self.disk_resume_run = None;
1781 self.disk_checked_at = None;
1782 self.diagnostic = None;
1783 self.blocked_by.clear();
1784 self.block_reason = None;
1785 self.blocked_from = None;
1786 }
1787
1788 pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1796 let note = note.into();
1797 if context.reason.is_none() {
1798 context.reason = Some(note.clone());
1799 }
1800 self.succeed(context);
1801 self.attempts = self.attempts.saturating_sub(1);
1802 self.last_error = Some(note);
1803 }
1804
1805 fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1806 self.completion_history.push(CompletionEvent {
1807 occurrence: format!(
1808 "{}-{:016x}{:016x}",
1809 Timestamp::now(),
1810 crate::rng::entropy(),
1811 crate::rng::entropy()
1812 ),
1813 action,
1814 actor: context.actor,
1815 reason: context.reason,
1816 discard: context.discard,
1817 prior_status: self.status,
1818 at: Timestamp::now(),
1819 prior_hold_reason: self.hold_reason.clone(),
1820 prior_block_reason: self.block_reason.clone(),
1821 prior_error: self.last_error.clone(),
1822 run: context.run,
1823 unavailable_runs: context.unavailable_runs,
1824 });
1825 self.stamp_schema();
1826 }
1827
1828 pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1831 anyhow::ensure!(
1832 self.status == TaskStatus::Done,
1833 "only a done task can be reopened"
1834 );
1835 anyhow::ensure!(
1836 context
1837 .reason
1838 .as_deref()
1839 .is_some_and(|reason| !reason.trim().is_empty()),
1840 "reopen requires a non-empty reason"
1841 );
1842 let reason = context.reason.clone();
1843 self.record_completion(CompletionAction::Reopen, context);
1844 self.hold_manual(reason);
1845 self.resume_override = None;
1846 self.reopen_hold =
1847 self.held_at
1848 .zip(self.completion_history.last())
1849 .map(|(held_at, event)| ReopenHold {
1850 occurrence: event.occurrence.clone(),
1851 held_at,
1852 decision: self.operator_decided_at,
1853 legacy: false,
1854 });
1855 self.fresh_start = false;
1856 self.last_error = None;
1857 self.diagnostic = None;
1858 Ok(())
1859 }
1860
1861 pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1891 if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1892 {
1893 return &[];
1894 }
1895 &self.execution_runs()[..self.execution_runs().len() - 1]
1896 }
1897
1898 pub fn successor_of(&self, run: &str) -> Option<&String> {
1906 let runs = self.execution_runs();
1907 let pos = runs.iter().rposition(|r| r == run)?;
1908 runs.get(pos + 1)
1909 }
1910
1911 pub fn earlier_attempts(&self) -> &[String] {
1918 self.execution_runs()
1919 }
1920
1921 fn preserve_legacy_build_cache(&mut self) {
1922 if self.schema < 23 {
1923 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1924 inherit_daemon_options: true,
1925 ..RunOverrides::default()
1926 });
1927 overrides.build_cache.get_or_insert(BuildCache::Shared);
1928 }
1929 }
1930
1931 fn stamp_schema(&mut self) {
1936 self.preserve_legacy_build_cache();
1937 if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1938 self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1939 }
1940 self.snapshot_legacy_reopen_hold();
1941 self.schema = self.schema.max(SCHEMA);
1942 }
1943
1944 fn note_held(&mut self) {
1947 self.stamp_schema();
1948 self.recovery_budget_hold = None;
1949 self.reopen_hold = None;
1950 let continuing = self.status == TaskStatus::Held
1951 || (self.status == TaskStatus::Blocked
1952 && (self.blocked_from == Some(TaskStatus::Held)
1953 || (self.blocked_from.is_none()
1954 && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1955 if !continuing || self.held_at.is_none() {
1956 self.held_at = Some(Timestamp::now());
1957 }
1958 }
1959
1960 pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1976 let why = why.into();
1977 if self.status == TaskStatus::Running {
1978 let run = self.runs.last().cloned();
1979 self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1980 }
1981 self.diagnostic = None;
1982 self.park_reason = None;
1983 self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1984 self.note_held();
1985 self.hold_source = Some(HoldSource::Machine);
1986 self.machine_hold_cause = None;
1987 self.disk_resume_run = None;
1988 self.disk_checked_at = None;
1989 self.hold_reason = Some(why.clone());
1990 TaskStatus::Held
1991 } else {
1992 TaskStatus::Failed
1993 };
1994 self.last_error = Some(why);
1995 }
1996
1997 pub fn stall(&mut self, why: impl Into<String>) {
2007 self.last_error = Some(why.into());
2008 self.diagnostic = None;
2009 self.attempts = self.attempts.saturating_sub(1);
2010 self.status = TaskStatus::Failed;
2011 }
2012
2013 pub fn park(&mut self, why: impl Into<String>) {
2019 self.diagnostic = None;
2020 self.attempts = self.attempts.saturating_sub(1);
2021 self.status = TaskStatus::Parked;
2022 self.park_reason = Some(why.into());
2023 self.stamp_schema();
2026 }
2027
2028 pub fn record_pass(
2030 &mut self,
2031 run: &str,
2032 pass_index: usize,
2033 attempts_before: usize,
2034 parked: Option<crate::run::ParkCause>,
2035 ) {
2036 self.record_pass_at(run, pass_index, None, attempts_before, parked);
2037 }
2038
2039 pub fn record_pass_at(
2042 &mut self,
2043 run: &str,
2044 pass_index: usize,
2045 started_at: Option<Timestamp>,
2046 attempts_before: usize,
2047 parked: Option<crate::run::ParkCause>,
2048 ) {
2049 if self
2050 .passes
2051 .iter()
2052 .any(|p| p.run == run && p.pass_index == pass_index)
2053 {
2054 return;
2055 }
2056 let cost = if self.attempts < attempts_before {
2057 PassCost::Refunded
2058 } else {
2059 PassCost::Spent
2060 };
2061 self.passes.push(TaskPass {
2062 run: run.to_owned(),
2063 pass_index,
2064 started_at: self.dispatched_at.or(started_at),
2065 cost,
2066 attempts_after: self.attempts,
2067 settled_at: Timestamp::now(),
2068 parked,
2069 });
2070 self.stamp_schema();
2071 }
2072
2073 pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
2076 if self.status != TaskStatus::Parked || self.fresh_start {
2077 return None;
2078 }
2079 let pass = self.passes.last()?;
2080 if self.execution_runs().last() != Some(&pass.run)
2081 || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
2082 {
2083 return None;
2084 }
2085 Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
2088 }
2089
2090 pub fn operator_held(&self) -> bool {
2096 self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2097 }
2098
2099 pub fn hold_manual(&mut self, reason: Option<String>) {
2109 self.operator_decided_at = Some(Timestamp::now());
2111 if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2112 self.resume_override = None;
2113 }
2114 self.hold_unrequested_retry(reason);
2115 }
2116
2117 pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2120 self.park_reason = None;
2121 self.note_held();
2122 self.status = TaskStatus::Held;
2123 if reason.is_some() {
2124 self.hold_reason = reason;
2125 }
2126 self.hold_source = Some(HoldSource::Manual);
2127 self.machine_hold_cause = None;
2128 self.disk_resume_run = None;
2129 self.disk_checked_at = None;
2130 self.blocked_by.clear();
2131 self.block_reason = None;
2132 self.blocked_from = None;
2133 }
2134
2135 pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2136 let recovery_hold = self.recovery_budget_hold.take();
2137 self.hold_unrequested_retry(Some(reason));
2138 self.recovery_budget_hold = recovery_hold;
2139 }
2140
2141 pub fn hold_machine(&mut self, reason: Option<String>) {
2146 self.park_reason = None;
2147 self.note_held();
2148 self.status = TaskStatus::Held;
2149 if reason.is_some() {
2150 self.hold_reason = reason;
2151 }
2152 self.hold_source = Some(HoldSource::Machine);
2153 self.machine_hold_cause = None;
2154 self.disk_resume_run = None;
2155 self.disk_checked_at = None;
2156 self.blocked_by.clear();
2157 self.block_reason = None;
2158 self.blocked_from = None;
2159 }
2160
2161 pub(crate) fn mark_disk_capacity(&mut self) {
2163 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2164 reason: self.hold_reason.clone().unwrap_or_default(),
2165 before_start: false,
2166 });
2167 }
2168
2169 pub(crate) fn mark_startup_disk_capacity(&mut self) {
2170 self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2171 reason: self.hold_reason.clone().unwrap_or_default(),
2172 before_start: true,
2173 });
2174 }
2175
2176 pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2177 if self.has_disk_capacity_cause()
2178 && matches!(
2179 self.machine_hold_cause,
2180 Some(MachineHoldCause::DiskCapacity {
2181 before_start: true,
2182 ..
2183 })
2184 )
2185 {
2186 None
2187 } else {
2188 self.execution_runs().last()
2189 }
2190 }
2191
2192 pub fn has_disk_capacity_cause(&self) -> bool {
2194 matches!(
2195 (&self.machine_hold_cause, self.hold_reason.as_deref()),
2196 (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2197 )
2198 }
2199
2200 pub(crate) fn resume_disk_wait(&mut self) {
2202 let retained = self.disk_wait_run().cloned();
2203 self.status = TaskStatus::Queued;
2204 self.held_at = None;
2205 self.hold_source = None;
2206 self.hold_reason = None;
2207 self.machine_hold_cause = None;
2208 self.last_error = None;
2209 self.disk_resume_run = retained;
2210 }
2211
2212 pub(crate) fn hold_head_e2e(
2214 &mut self,
2215 stop: crate::head_e2e_stop::Stop,
2216 reason: String,
2217 last_error: String,
2218 ) {
2219 self.hold_machine(Some(reason));
2220 self.last_error = Some(last_error);
2221 self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2222 }
2223
2224 pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2226 if let Some(at) = stop.recorded_at {
2227 self.held_at = Some(at);
2228 }
2229 self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2230 if let Some(cause) = &mut self.hold_notice_cause {
2231 cause.target = Some(stop.id.clone());
2232 }
2233 }
2234
2235 pub fn has_head_e2e_cause(&self) -> bool {
2237 matches!(
2238 self.machine_hold_cause,
2239 Some(MachineHoldCause::HeadE2e { .. })
2240 )
2241 }
2242
2243 pub fn head_e2e_stop_id(&self) -> Option<&str> {
2245 if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2246 return Some(stop.id.as_str());
2247 }
2248 self.hold_notice_cause
2249 .as_ref()
2250 .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2251 .and_then(|c| c.target.as_deref())
2252 }
2253
2254 pub(crate) fn resume_head_e2e_wait(&mut self) {
2257 self.status = TaskStatus::Queued;
2258 self.held_at = None;
2259 self.hold_source = None;
2260 self.hold_reason = None;
2261 self.machine_hold_cause = None;
2262 self.last_error = None;
2263 self.diagnostic = None;
2264 self.blocked_by.clear();
2265 self.block_reason = None;
2266 self.blocked_from = None;
2267 }
2268
2269 pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2279 self.stamp_schema();
2280 let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2281 let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2282 if self.status != TaskStatus::Blocked || before != after {
2283 self.blocked_at = Some(Timestamp::now());
2284 }
2285 if self.status != TaskStatus::Blocked {
2286 self.blocked_from = Some(self.status);
2287 }
2288 self.status = TaskStatus::Blocked;
2289 self.blocked_by = blocked_by;
2290 self.block_reason = reason;
2291 }
2292
2293 pub fn unblock(&mut self, resolved_id: &str) {
2316 if self.status != TaskStatus::Blocked {
2317 return;
2318 }
2319 self.blocked_by.retain(|id| id != resolved_id);
2320 self.restore_if_unblocked();
2321 }
2322
2323 pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2334 if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2335 return false;
2336 }
2337 self.blocked_by.retain(|id| id != deleted_id);
2338 self.restore_if_unblocked();
2339 true
2340 }
2341
2342 fn restore_if_unblocked(&mut self) {
2346 if self.blocked_by.is_empty() {
2347 self.status = match self.blocked_from {
2348 Some(TaskStatus::Running) => TaskStatus::Queued,
2349 Some(other) => other,
2350 None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2351 TaskStatus::Held
2352 }
2353 None => TaskStatus::Queued,
2354 };
2355 self.block_reason = None;
2356 self.blocked_from = None;
2357 }
2358 }
2359
2360 pub fn record_answer(&mut self, question: String, answer: String) {
2365 self.answers.push(AnsweredQuestion { question, answer });
2366 }
2367
2368 pub fn request_review(&mut self, branch: String) {
2372 self.release();
2373 self.review_branch = Some(branch);
2374 self.review_instruction = Some(self.instruction.clone());
2375 }
2376
2377 pub fn requeue(&mut self) {
2380 self.release();
2381 self.review_branch = None;
2383 self.review_instruction = None;
2384 self.fresh_start = true;
2385 }
2386
2387 pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2396 if branch.is_some() {
2397 self.review_branch = branch;
2398 self.review_instruction = Some(self.instruction.clone());
2399 }
2400 self.hold_machine(Some(reason));
2401 }
2402
2403 pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2405 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2406 bail!(
2407 "task {} is {}; urgent can only change while queued or held; \
2408 wait for the active attempt to finish and requeue or hold the task first",
2409 self.short(),
2410 self.status.as_str()
2411 );
2412 }
2413 self.urgent = urgent;
2414 Ok(())
2415 }
2416
2417 pub fn set_immediate(&mut self, immediate: bool) -> Result<()> {
2421 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2422 bail!(
2423 "task {} is {}; immediate can only change while queued or held; \
2424 wait for the active attempt to finish and requeue or hold the task first",
2425 self.short(),
2426 self.status.as_str()
2427 );
2428 }
2429 self.immediate = immediate;
2430 Ok(())
2431 }
2432
2433 pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2442 if self.status == TaskStatus::Running {
2443 bail!(
2444 "task {} is running; its priority cannot be changed until \
2445 this attempt finishes",
2446 self.short()
2447 );
2448 }
2449 self.priority = priority;
2450 Ok(())
2451 }
2452
2453 pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2468 if interrupt && !self.status.runnable() {
2469 bail!(
2470 "task {} is {}; only a queued or failed task can be marked \
2471 to interrupt",
2472 self.short(),
2473 self.status.as_str()
2474 );
2475 }
2476 self.interrupt = interrupt;
2477 Ok(())
2478 }
2479
2480 pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2482 self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2483 }
2484
2485 pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2488 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2489 bail!("only queued or held tasks can change the attempt limit");
2490 }
2491 self.stamp_schema();
2492 self.attempt_limit = limit;
2493 Ok(())
2494 }
2495
2496 pub fn implementers(&self) -> Option<usize> {
2498 if self.solo {
2499 Some(1)
2500 } else {
2501 self.overrides.as_ref().and_then(|o| o.candidates)
2502 }
2503 }
2504
2505 pub fn build_cache_override(
2510 &self,
2511 config: &crate::config::Config,
2512 ) -> Option<(BuildCache, &'static str)> {
2513 self.overrides
2514 .as_ref()
2515 .and_then(|o| o.build_cache)
2516 .map(|mode| (mode, "task-override"))
2517 .or_else(|| {
2518 ((self.immediate || self.urgent) && crate::build_target::urgent_isolation(config))
2519 .then_some((
2520 BuildCache::Isolated,
2521 if self.immediate {
2522 "immediate"
2523 } else {
2524 "urgent"
2525 },
2526 ))
2527 })
2528 }
2529
2530 pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2533 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2534 bail!(
2535 "task {} is {}; only queued or held tasks can change build cache",
2536 self.short(),
2537 self.status.as_str()
2538 );
2539 }
2540 self.stamp_schema();
2541 if self.overrides.is_some() || mode.is_some() {
2542 let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2543 inherit_daemon_options: true,
2544 ..RunOverrides::default()
2545 });
2546 overrides.build_cache = mode;
2547 }
2548 Ok(())
2549 }
2550
2551 pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2554 self.check_implementers_editable()?;
2555 let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2556 let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2557 if let Some(o) = &self.overrides {
2558 o.apply(&mut config);
2559 }
2560 self.set_implementers(count, &config)
2561 }
2562
2563 fn check_implementers_editable(&self) -> Result<()> {
2564 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2565 bail!(
2566 "task {} is {}; only queued or held tasks can change implementers",
2567 self.short(),
2568 self.status.as_str()
2569 );
2570 }
2571 Ok(())
2572 }
2573
2574 pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2576 self.check_implementers_editable()?;
2577 crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2578 self.stamp_schema();
2579 self.solo = count == 1;
2580 let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2581 inherit_daemon_options: true,
2582 ..Default::default()
2583 });
2584 overrides.candidates = (count > 1).then_some(usize::from(count));
2585 let mut settings = overrides.clone();
2586 settings.inherit_daemon_options = false;
2587 self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2589 {
2590 None
2591 } else {
2592 Some(overrides)
2593 };
2594 Ok(())
2595 }
2596
2597 pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2609 if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2610 bail!(
2611 "task {} is {}; only a queued or held task's instruction can \
2612 be edited",
2613 self.short(),
2614 self.status.as_str()
2615 );
2616 }
2617 if self.review_branch.is_some() && self.review_instruction.is_none() {
2620 self.review_instruction = Some(self.instruction.clone());
2621 }
2622 if self.instruction != instruction {
2623 self.resume_override = None;
2626 }
2627 if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2628 self.hold_manual(self.hold_reason.clone());
2629 }
2630 self.machine_hold_cause = None;
2631 self.disk_resume_run = None;
2632 self.disk_checked_at = None;
2633 self.title = title;
2634 self.instruction = instruction;
2635 Ok(())
2636 }
2637
2638 pub fn handed_off(&mut self, why: impl Into<String>) {
2658 let why = why.into();
2659 self.diagnostic = None;
2660 self.note_held();
2661 self.status = TaskStatus::Held;
2662 self.hold_source = Some(HoldSource::Machine);
2663 self.machine_hold_cause = None;
2664 self.disk_resume_run = None;
2665 self.disk_checked_at = None;
2666 self.hold_reason = Some(why.clone());
2667 self.last_error = Some(why);
2668 }
2669
2670 pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2672 self.recovery_budget = None;
2673 self.recovery_generations.clear();
2674 self.recovery_admission = None;
2675 if self
2676 .resumption
2677 .as_ref()
2678 .is_some_and(|r| r.instruction != self.instruction)
2679 {
2680 self.resume_override = None;
2683 }
2684 let approval = Resumption {
2685 generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2686 source: source.to_owned(),
2687 question_id: question_id.map(str::to_owned),
2688 at: Timestamp::now(),
2689 instruction: self.instruction.clone(),
2690 answers_through: self.answers.len(),
2691 runs_through: self.runs.len(),
2692 blocking_evidence: Vec::new(),
2693 cleared_reason: self
2694 .hold_reason
2695 .clone()
2696 .or_else(|| self.block_reason.clone()),
2697 };
2698 self.release();
2699 self.operator_decided_at = Some(approval.at);
2700 if let Some(previous) = self.resumption.replace(approval) {
2701 self.resumption_history.push(previous);
2702 }
2703 }
2704
2705 pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2707 let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2708 || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2709 |a| (a.base.clone(), a.inputs.clone()),
2710 );
2711 let progress = recovery_progress(state);
2712 let stage = if state.prep_failure.is_some() {
2713 "preparation"
2714 } else {
2715 "execution"
2716 };
2717 let matches = |b: &RecoveryBudget| {
2718 b.instruction == self.instruction
2719 && b.base == base
2720 && b.inputs == inputs
2721 && (progress.is_none() || b.progress == progress)
2722 };
2723 if !self.recovery_budget.as_ref().is_some_and(matches) {
2724 let previous = self
2725 .recovery_generations
2726 .iter()
2727 .position(matches)
2728 .map(|index| self.recovery_generations.remove(index));
2729 if let Some(old) = self.recovery_budget.take() {
2730 self.recovery_generations.push(old);
2731 }
2732 self.recovery_budget = previous;
2733 }
2734 if let Some(budget) = &mut self.recovery_budget {
2735 budget.failures = budget.failures.saturating_add(1);
2736 budget.stage = stage.to_owned();
2737 } else {
2738 self.recovery_budget = Some(RecoveryBudget {
2739 instruction: self.instruction.clone(),
2740 base,
2741 inputs,
2742 stage: stage.to_owned(),
2743 failures: 1,
2744 progress,
2745 });
2746 }
2747 }
2748
2749 pub(crate) fn recovery_exhausted(
2750 &self,
2751 base: &str,
2752 inputs: &str,
2753 limit: usize,
2754 ) -> Option<String> {
2755 let same_input = |b: &&RecoveryBudget| {
2756 b.instruction == self.instruction && b.base == base && b.inputs == inputs
2757 };
2758 let budget = self
2759 .recovery_budget
2760 .as_ref()
2761 .filter(same_input)
2762 .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2763 (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2764 }
2765
2766 pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2767 self.hold_unrequested_retry(Some(reason));
2768 if let Some(pass) = self.passes.last()
2769 && self.execution_runs().last() == Some(&pass.run)
2770 {
2771 self.recovery_budget_hold = Some(RecoveryBudgetHold {
2772 admission,
2773 run: pass.run.clone(),
2774 pass: pass.pass_index,
2775 held_at: self.held_at.expect("hold timestamp just recorded"),
2776 decision: self.operator_decided_at,
2777 legacy: false,
2778 });
2779 }
2780 }
2781
2782 fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2783 self.status == TaskStatus::Held
2784 && self.hold_source == Some(HoldSource::Manual)
2785 && self.machine_hold_cause.is_none()
2786 && self.recovery_budget.as_ref().is_some_and(|budget| {
2787 budget.instruction == self.instruction
2788 && budget.base == admission.base
2789 && budget.inputs == admission.inputs
2790 && budget.stage == "execution"
2791 && budget.failures > 0
2792 && self
2793 .hold_reason
2794 .as_ref()
2795 .is_some_and(|reason| *reason == budget.budget_reason())
2796 })
2797 }
2798
2799 fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2800 let held_at = self.held_at?;
2801 let settled = self.passes.last()?;
2802 let admission = self.recovery_admission.as_ref()?;
2803 if !self.matches_budget_hold(admission)
2804 || self.execution_runs().last() != Some(&settled.run)
2805 || settled.cost != PassCost::Spent
2806 || settled.parked.is_some()
2807 || settled.settled_at > held_at
2808 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2809 {
2810 return None;
2811 }
2812 Some(RecoveryBudgetHold {
2813 admission: admission.clone(),
2814 run: settled.run.clone(),
2815 pass: settled.pass_index,
2816 held_at,
2817 decision: self.operator_decided_at,
2818 legacy: true,
2819 })
2820 }
2821
2822 pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2823 let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2824 self.held_at,
2825 self.passes.last(),
2826 run.passes.last(),
2827 self.recovery_admission.as_ref(),
2828 ) else {
2829 return false;
2830 };
2831 if !self.matches_budget_hold(admission)
2832 || self.execution_runs().last() != Some(&run.id)
2833 || settled.run != run.id
2834 || settled.pass_index != pass.index
2835 || settled.cost != PassCost::Spent
2836 || settled.parked.is_some()
2837 || settled.settled_at < pass.started_at
2838 || settled.settled_at > held_at
2839 || self.operator_decided_at.is_some_and(|at| at >= held_at)
2840 || !crate::daemon::compatible_run_instruction(run, self)
2841 {
2842 return false;
2843 }
2844 match &self.recovery_budget_hold {
2845 Some(hold) => {
2846 hold.run == run.id
2847 && hold.pass == pass.index
2848 && hold.held_at == held_at
2849 && hold.decision == self.operator_decided_at
2850 && &hold.admission == admission
2851 && (!hold.legacy
2852 || self
2853 .operator_decided_at
2854 .is_none_or(|at| at < pass.started_at))
2855 }
2856 None => {
2857 self.schema < RECOVERY_HOLD_SCHEMA
2858 && self
2859 .operator_decided_at
2860 .is_none_or(|at| at < pass.started_at)
2861 }
2862 }
2863 }
2864
2865 pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2866 self.stamp_schema();
2867 self.repair_grants.push(receipt.clone());
2868 self.status = TaskStatus::Queued;
2869 self.hold_source = None;
2870 self.hold_reason = None;
2871 self.held_at = None;
2872 self.recovery_budget_hold = None;
2873 self.reopen_hold = None;
2874 self.resume_override = Some(OperatorResume {
2875 question_id: String::new(),
2876 at: receipt.at,
2877 conductor_rehold: None,
2878 forced: true,
2879 pinned_run: Some(receipt.request.run.clone()),
2880 });
2881 }
2882
2883 fn snapshot_legacy_reopen_hold(&mut self) {
2886 if self.schema >= REOPEN_HOLD_SCHEMA || self.reopen_hold.is_some() {
2887 return;
2888 }
2889 let Some(event) = self.completion_history.last() else {
2890 return;
2891 };
2892 if event.action == CompletionAction::Reopen
2893 && self.status == TaskStatus::Held
2894 && self.hold_source == Some(HoldSource::Manual)
2895 && event.reason.is_some()
2896 && self.hold_reason == event.reason
2897 && let (Some(held_at), Some(decision)) = (self.held_at, self.operator_decided_at)
2898 && held_at >= event.at
2899 && decision >= event.at
2900 {
2901 self.reopen_hold = Some(ReopenHold {
2902 occurrence: event.occurrence.clone(),
2903 held_at,
2904 decision: Some(decision),
2905 legacy: true,
2906 });
2907 }
2908 }
2909
2910 pub(crate) fn held_by_reopen(
2913 &self,
2914 occurrence: &str,
2915 run: &str,
2916 legacy_confirmation: Option<&str>,
2917 ) -> bool {
2918 let Some(event) = self.completion_history.last() else {
2919 return false;
2920 };
2921 if self.status != TaskStatus::Held
2922 || self.hold_source != Some(HoldSource::Manual)
2923 || !self.blocked_by.is_empty()
2924 || self.resume_override.is_some()
2925 || self.fresh_start
2926 || event.action != CompletionAction::Reopen
2927 || event.occurrence != occurrence
2928 || event.run.as_ref().map(|r| r.id.as_str()) != Some(run)
2929 || event.reason.is_none()
2930 || self.hold_reason != event.reason
2931 {
2932 return false;
2933 }
2934 let (Some(held_at), Some(decided), Some(hold)) =
2935 (self.held_at, self.operator_decided_at, &self.reopen_hold)
2936 else {
2937 return false;
2938 };
2939 hold.occurrence == occurrence
2940 && hold.held_at == held_at
2941 && hold.decision == Some(decided)
2942 && if hold.legacy {
2943 legacy_confirmation == Some(format!("{held_at}/{decided}").as_str())
2944 } else {
2945 legacy_confirmation.is_none()
2946 }
2947 }
2948
2949 pub fn release(&mut self) {
2953 self.import_chat_notice();
2956 if self.hold_notice_cause.is_none()
2957 && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2958 {
2959 self.hold_notice_cause = Some(self.unresolved_hold_cause());
2960 }
2961 let refused_handover = self.status == TaskStatus::Held
2962 && self.hold_source == Some(HoldSource::Machine)
2963 && self.review_branch.is_some()
2964 && self
2965 .review_instruction
2966 .as_ref()
2967 .is_none_or(|i| *i == self.instruction);
2968 self.status = TaskStatus::Queued;
2969 self.held_at = None;
2970 self.attempts = 0;
2971 self.last_error = None;
2972 self.park_reason = None;
2973 self.hold_reason = None;
2976 self.hold_source = None;
2977 self.machine_hold_cause = None;
2978 self.disk_resume_run = None;
2979 self.disk_checked_at = None;
2980 self.diagnostic = None;
2981 self.blocked_by.clear();
2986 self.block_reason = None;
2987 self.blocked_from = None;
2988 if !refused_handover {
2992 self.review_branch = None;
2993 self.review_instruction = None;
2994 }
2995 self.fresh_start = false;
2996 }
2997}
2998
2999fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
3003 use std::io::ErrorKind;
3004 let (stem, ext) = match name.rfind('.') {
3005 Some(i) if i > 0 => (&name[..i], &name[i..]),
3006 _ => (name, ""),
3007 };
3008 for n in 1u32.. {
3009 let candidate = if n == 1 {
3010 name.to_owned()
3011 } else {
3012 let suffix = format!("-{n}");
3013 let room = 64usize.saturating_sub(suffix.len() + ext.len());
3014 let stem: String = stem.chars().take(room).collect();
3015 format!("{stem}{suffix}{ext}")
3016 };
3017 if !crate::ask::valid_asset_name(&candidate) {
3018 bail!("no valid attachment name is left for `{name}`");
3019 }
3020 let path = dir.join(&candidate);
3021 match std::fs::OpenOptions::new()
3022 .write(true)
3023 .create_new(true)
3024 .open(&path)
3025 {
3026 Ok(mut out) => {
3027 let copied = std::fs::File::open(src)
3028 .and_then(|mut input| std::io::copy(&mut input, &mut out));
3029 if let Err(e) = copied {
3030 drop(out);
3031 let _ = std::fs::remove_file(&path);
3032 return Err(e).with_context(|| format!("copy {}", src.display()));
3033 }
3034 return Ok((candidate, path));
3035 }
3036 Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
3037 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
3038 }
3039 }
3040 unreachable!("the counter never runs out")
3041}
3042
3043const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
3046
3047pub(crate) struct TaskLock {
3050 path: PathBuf,
3051 token: String,
3052}
3053
3054fn owner_token() -> String {
3057 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3058 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3059 let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
3060 format!("{}-{:016x}", std::process::id(), r.next_u64())
3061}
3062
3063fn break_marker(path: &Path, token: &str) -> PathBuf {
3066 let mut h: u64 = 0xcbf29ce484222325;
3067 for b in token.bytes() {
3068 h ^= u64::from(b);
3069 h = h.wrapping_mul(0x100000001b3);
3070 }
3071 let mut name = path.as_os_str().to_owned();
3072 name.push(format!(".break-{h:016x}"));
3073 PathBuf::from(name)
3074}
3075
3076fn older_than_stale(path: &Path) -> bool {
3077 std::fs::metadata(path)
3078 .and_then(|m| m.modified())
3079 .ok()
3080 .and_then(|t| t.elapsed().ok())
3081 .is_some_and(|age| age > TASK_LOCK_STALE)
3082}
3083
3084fn writer_may_be_gone(token: &str) -> bool {
3085 let Some(pid) = token
3086 .split_once('-')
3087 .and_then(|(pid, _)| pid.parse::<u32>().ok())
3088 else {
3089 return true;
3092 };
3093 if pid == std::process::id() {
3094 return false;
3095 }
3096 crate::proc::pid_status(pid) == Some(false)
3098}
3099
3100const MAX_MARKER_DEPTH: u8 = 3;
3104
3105fn take_marker(
3111 path: &Path,
3112 token: &str,
3113 depth: u8,
3114 retry: crate::lock_file::Retry,
3115) -> Option<(PathBuf, String)> {
3116 use std::io::Write;
3117 let marker = break_marker(path, token);
3118 for _ in 0..2 {
3119 match retry.create(&marker) {
3120 Ok(mut f) => {
3121 let mine = owner_token();
3122 if f.write_all(mine.as_bytes()).is_err() {
3123 drop(f);
3124 let _ = std::fs::remove_file(&marker);
3125 return None;
3126 }
3127 return Some((marker, mine));
3128 }
3129 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3130 let judged = std::fs::read_to_string(&marker).ok();
3131 match judged.filter(|_| older_than_stale(&marker)) {
3132 Some(judged) if depth < MAX_MARKER_DEPTH => {
3133 remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
3134 }
3135 _ => return None,
3136 }
3137 }
3138 Err(_) => return None,
3139 }
3140 }
3141 None
3142}
3143
3144fn remove_lock_if(
3149 path: &Path,
3150 token: &str,
3151 require_stale: bool,
3152 depth: u8,
3153 retry: crate::lock_file::Retry,
3154) -> Option<bool> {
3155 let (marker, mine) = take_marker(path, token, depth, retry)?;
3156 let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
3157 && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
3158 if still {
3159 let _ = std::fs::remove_file(path);
3160 }
3161 if depth >= MAX_MARKER_DEPTH {
3163 if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
3164 let _ = std::fs::remove_file(&marker);
3165 }
3166 } else {
3167 let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
3168 }
3169 Some(still)
3170}
3171
3172#[cfg(test)]
3175fn break_stale(path: &Path, judged: &str) -> bool {
3176 break_stale_with(path, judged, crate::lock_file::Retry::new(None))
3177}
3178
3179fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
3180 remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3181}
3182
3183impl Drop for TaskLock {
3184 fn drop(&mut self) {
3185 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3186 let retry = crate::lock_file::Retry::new(Some(deadline));
3187 loop {
3188 match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3189 Some(_) => return,
3190 None if std::time::Instant::now() > deadline => return,
3191 None => std::thread::sleep(std::time::Duration::from_millis(5)),
3192 }
3193 }
3194 }
3195}
3196
3197#[derive(Debug, thiserror::Error)]
3198#[error("task changed during completion decision; reload and inspect it")]
3199pub(crate) struct CompletionSnapshotChanged;
3200
3201#[derive(Debug, Clone)]
3203pub struct Queue {
3204 root: PathBuf,
3205 ids: IdSource,
3206}
3207
3208fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3209 let mut wanted = Vec::new();
3210 for src in sources {
3211 let name = src
3212 .file_name()
3213 .and_then(|n| n.to_str())
3214 .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3215 if !crate::ask::valid_asset_name(name) {
3216 bail!(
3217 "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3218 with no `..`; rename the file and try again"
3219 );
3220 }
3221 if !src.is_file() {
3222 bail!("attachment `{}` is not a file", src.display());
3223 }
3224 wanted.push((src, name));
3225 }
3226 Ok(wanted)
3227}
3228
3229impl Queue {
3230 pub fn open() -> Self {
3232 Self::at(crate::run::home().join("queue"))
3233 }
3234
3235 pub fn at(root: PathBuf) -> Self {
3238 Self {
3239 root,
3240 ids: IdSource::new(new_id),
3241 }
3242 }
3243
3244 #[doc(hidden)]
3247 pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3248 self.ids = IdSource::custom(f);
3249 self
3250 }
3251
3252 fn file_with(
3263 &self,
3264 task: &mut Task,
3265 hook: impl FnMut(&mut Task) -> Result<bool>,
3266 undo: impl FnMut(&mut Task),
3267 ) -> Result<()> {
3268 self.reserve_id(task, hook, undo, true)
3269 }
3270
3271 fn reserve_id(
3279 &self,
3280 task: &mut Task,
3281 mut hook: impl FnMut(&mut Task) -> Result<bool>,
3282 mut undo: impl FnMut(&mut Task),
3283 store: bool,
3284 ) -> Result<()> {
3285 let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3286 let initial = task.id.clone();
3287 self.ids
3288 .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3289 task.id = id.to_owned();
3290 let _lock = self.lock_task(&task.id)?;
3291 if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3292 return Ok(false);
3293 }
3294 if store {
3295 if let Err(e) = self.write_record(task) {
3296 undo(task);
3297 return Err(e);
3298 }
3299 task.unfiled = false;
3300 }
3301 Ok(true)
3302 })?;
3303 Ok(())
3304 }
3305
3306 fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3311 if path_exists(&self.lock_path(id))? || path_exists(&self.filing_reservation_path(id))? {
3312 return Ok(true);
3313 }
3314 Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3315 }
3316
3317 fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3321 Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3322 }
3323
3324 pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3327 let mut claim = None;
3328 self.file_with(
3329 task,
3330 |t| {
3331 if self.id_in_use(&t.id, true)? {
3332 return Ok(false);
3333 }
3334 claim = Some(self.claim(&t.id)?);
3335 Ok(true)
3336 },
3337 |_| {},
3338 )?;
3339 claim.context("claim missing after filing")
3340 }
3341
3342 pub fn root(&self) -> &Path {
3344 &self.root
3345 }
3346
3347 pub fn path_of(&self, id: &str) -> PathBuf {
3349 self.root.join(format!("{id}.json"))
3350 }
3351
3352 pub fn attachments_dir(&self, id: &str) -> PathBuf {
3355 self.root.join(format!("{id}.attachments"))
3356 }
3357
3358 pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3369 let wanted = validate_attachments(sources)?;
3370 if task.unfiled && task.attachments.is_empty() {
3371 let names = std::cell::RefCell::new(Vec::new());
3374 self.reserve_id(
3375 task,
3376 |t| {
3377 if self.id_in_use(&t.id, true)? {
3378 return Ok(false);
3379 }
3380 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3381 Ok(true)
3382 },
3383 |_| {},
3384 false,
3385 )?;
3386 return Ok(names.into_inner());
3387 }
3388 self.copy_attachments(task, &wanted)
3389 }
3390
3391 fn copy_attachments(
3393 &self,
3394 task: &mut Task,
3395 wanted: &[(&PathBuf, &str)],
3396 ) -> Result<Vec<String>> {
3397 let dir = self.attachments_dir(&task.id);
3398 let existed = dir.is_dir();
3399 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3400 let mut created: Vec<PathBuf> = Vec::new();
3401 let mut names = Vec::new();
3402 let mut copy_all = || -> Result<()> {
3403 for (src, name) in wanted {
3404 let (stored, path) = copy_new(&dir, src, name)?;
3405 created.push(path);
3406 names.push(stored);
3407 }
3408 Ok(())
3409 };
3410 if let Err(e) = copy_all() {
3411 for path in &created {
3412 let _ = std::fs::remove_file(path);
3413 }
3414 if !existed {
3415 let _ = std::fs::remove_dir(&dir);
3416 }
3417 return Err(e);
3418 }
3419 task.attachments.extend(names.iter().cloned());
3420 Ok(names)
3421 }
3422
3423 pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3434 if task.unfiled && task.attachments.is_empty() {
3435 return self.attach_and_file(task, sources);
3436 }
3437 let dir = self.attachments_dir(&task.id);
3438 let existed = dir.is_dir();
3439 let before = task.attachments.len();
3440 let names = self.attach(task, sources)?;
3441 if let Err(e) = self.put(task) {
3442 for name in &names {
3443 let _ = std::fs::remove_file(dir.join(name));
3444 }
3445 if !existed {
3446 let _ = std::fs::remove_dir(&dir);
3447 }
3448 task.attachments.truncate(before);
3449 return Err(e);
3450 }
3451 Ok(names)
3452 }
3453
3454 fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3458 let wanted = validate_attachments(sources)?;
3459 let before = task.attachments.len();
3460 let names = std::cell::RefCell::new(Vec::new());
3461 let result = self.file_with(
3462 task,
3463 |t| {
3464 if self.id_in_use(&t.id, true)? {
3465 return Ok(false);
3466 }
3467 *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3468 Ok(true)
3469 },
3470 |t| {
3471 let dir = self.attachments_dir(&t.id);
3472 for name in names.borrow().iter() {
3473 let _ = std::fs::remove_file(dir.join(name));
3474 }
3475 let _ = std::fs::remove_dir(&dir);
3477 t.attachments.truncate(before);
3478 },
3479 );
3480 result.map(|()| names.into_inner())
3481 }
3482
3483 pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3487 let dir = self.attachments_dir(&task.id);
3488 task.attachments
3489 .iter()
3490 .map(|n| {
3491 let p = dir.join(n);
3492 std::path::absolute(&p).unwrap_or(p)
3493 })
3494 .collect()
3495 }
3496
3497 pub fn put(&self, task: &mut Task) -> Result<()> {
3506 if task.unfiled {
3507 return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3509 }
3510 let _lock = self.lock_task(&task.id)?;
3511 self.put_unlocked(task)
3512 }
3513
3514 pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3519 let _lock = self.lock_task(&task.id)?;
3520 if path_exists(&self.path_of(&task.id))?
3521 || path_exists(&self.filing_reservation_path(&task.id))?
3522 {
3523 return Ok(false);
3524 }
3525 self.write_record(task)?;
3526 task.unfiled = false;
3527 Ok(true)
3528 }
3529
3530 fn filing_reservation_path(&self, id: &str) -> PathBuf {
3531 self.root.join(format!("{id}.filing-reservation"))
3532 }
3533
3534 pub(crate) fn reserve_unused_id(&self) -> Result<String> {
3539 let mut chosen = String::new();
3540 self.ids.reserve(None, "task", |id| {
3541 let _lock = self.lock_task(id)?;
3542 if path_exists(&self.path_of(id))?
3543 || path_exists(&self.tombstone_path(id))?
3544 || self.id_in_use(id, true)?
3545 {
3546 return Ok(false);
3547 }
3548 std::fs::File::create_new(self.filing_reservation_path(id))?.sync_all()?;
3549 chosen = id.to_owned();
3550 Ok(true)
3551 })?;
3552 Ok(chosen)
3553 }
3554
3555 pub(crate) fn file_with_exact_id(
3565 &self,
3566 task: &mut Task,
3567 sources: &[PathBuf],
3568 allow_clean_unfiled_attachments: bool,
3569 verify_attachments: impl FnOnce(&Task) -> Result<()>,
3570 ) -> Result<bool> {
3571 let wanted = validate_attachments(sources)?;
3572 let _lock = self.lock_task(&task.id)?;
3573 anyhow::ensure!(
3574 path_exists(&self.filing_reservation_path(&task.id))?,
3575 "task id {} has no durable filing reservation",
3576 task.id
3577 );
3578 if path_exists(&self.path_of(&task.id))? {
3579 return Ok(false);
3580 }
3581 anyhow::ensure!(
3583 !path_exists(&self.tombstone_path(&task.id))?,
3584 "reserved task {} was deleted; refusing to file it again",
3585 task.id
3586 );
3587 if path_exists(&self.lock_path(&task.id))? {
3588 bail!(
3589 "reserved task id {} is claimed; cannot finish filing",
3590 task.id
3591 );
3592 }
3593 let dir = self.attachments_dir(&task.id);
3594 if path_exists(&dir)? {
3595 if allow_clean_unfiled_attachments {
3596 std::fs::remove_dir_all(&dir)
3597 .with_context(|| format!("clean partial attachments {}", dir.display()))?;
3598 } else {
3599 bail!(
3600 "reserved task id {} already has an attachment directory",
3601 task.id
3602 );
3603 }
3604 }
3605 if !wanted.is_empty() {
3606 let before = task.attachments.len();
3607 let names = self.copy_attachments(task, &wanted)?;
3608 if let Err(e) = verify_attachments(task).and_then(|()| self.write_record(task)) {
3609 for name in &names {
3610 let _ = std::fs::remove_file(dir.join(name));
3611 }
3612 let _ = std::fs::remove_dir(&dir);
3613 task.attachments.truncate(before);
3614 return Err(e);
3615 }
3616 } else {
3617 verify_attachments(task)?;
3618 self.write_record(task)?;
3619 }
3620 task.unfiled = false;
3621 Ok(true)
3622 }
3623
3624 fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3626 self.merge_stored(task);
3627 if let Some(boundary) = task.reassignments.last() {
3628 let stored = self.get(&task.id)?;
3629 anyhow::ensure!(
3630 task.reassignments == stored.reassignments
3631 && task.repo == stored.repo
3632 && task.runs.get(..boundary.run_boundary)
3633 == stored.runs.get(..boundary.run_boundary),
3634 "historical repository execution cannot be restarted; reload the task"
3635 );
3636 }
3637 self.write_record(task)
3638 }
3639
3640 pub(crate) fn commit_base_recovery(
3642 &self,
3643 task: &mut Task,
3644 expected: &serde_json::Value,
3645 ) -> Result<()> {
3646 let _lock = self.lock_task(&task.id)?;
3647 anyhow::ensure!(
3648 serde_json::to_value(self.get(&task.id)?)? == *expected,
3649 "task changed during base recovery; inspect the pending authorization"
3650 );
3651 self.put_unlocked(task)
3653 }
3654
3655 pub(crate) fn commit_land_sync_recovery(
3657 &self,
3658 task: &mut Task,
3659 expected: &serde_json::Value,
3660 ) -> Result<()> {
3661 let _lock = self.lock_task(&task.id)?;
3662 anyhow::ensure!(
3663 serde_json::to_value(self.get(&task.id)?)? == *expected,
3664 "task changed during landing base-sync recovery; inspect the pending authorization"
3665 );
3666 self.put_unlocked(task)
3667 }
3668
3669 pub(crate) fn commit_repair_grant(
3670 &self,
3671 task: &mut Task,
3672 expected: &serde_json::Value,
3673 ) -> Result<()> {
3674 let _lock = self.lock_task(&task.id)?;
3675 anyhow::ensure!(
3676 serde_json::to_value(self.get(&task.id)?)? == *expected,
3677 "repair grant refused: task changed during admission"
3678 );
3679 self.write_record(task)
3680 .context(crate::repair_budget::PublicationUnknown)
3681 }
3682
3683 pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3685 let _lock = self.lock_task(&task.id)?;
3686 anyhow::ensure!(
3687 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3688 "task changed during disk monitoring"
3689 );
3690 task.stamp_schema();
3691 self.write_record_inner(task, false)
3692 }
3693
3694 pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3696 let _lock = self.lock_task(&task.id)?;
3697 let stored = self.get(&task.id)?;
3698 anyhow::ensure!(
3699 serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3700 && stored.reassignments.len() + 1 == task.reassignments.len()
3701 && stored.repo == task.reassignments.last().expect("new boundary").from
3702 && stored.runs == task.runs,
3703 "task changed during reassignment; retry after inspecting it"
3704 );
3705 self.write_record(task)
3706 }
3707
3708 pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3710 let _lock = self.lock_task(&task.id)?;
3711 anyhow::ensure!(
3712 serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3713 CompletionSnapshotChanged
3714 );
3715 self.write_record(task)
3716 }
3717
3718 fn merge_stored(&self, task: &mut Task) {
3720 if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3721 stored.import_chat_notice();
3722 let local_decision = task.completion_history.iter().any(|event| {
3725 !stored
3726 .completion_history
3727 .iter()
3728 .any(|saved| saved.occurrence == event.occurrence)
3729 && event.at > stored.updated_at
3730 });
3731 let unseen_decision = stored.completion_history.iter().any(|event| {
3732 !task
3733 .completion_history
3734 .iter()
3735 .any(|mine| mine.occurrence == event.occurrence)
3736 });
3737 let mut history = std::mem::take(&mut stored.completion_history);
3738 for event in std::mem::take(&mut task.completion_history) {
3739 if !history
3740 .iter()
3741 .any(|stored| stored.occurrence == event.occurrence)
3742 {
3743 history.push(event);
3744 }
3745 }
3746 if unseen_decision {
3747 task.import_chat_notice();
3750 let mut stale = std::mem::replace(task, stored);
3751 append_missing(&mut task.answers, stale.answers);
3752 if task.reassignments == stale.reassignments {
3753 append_missing(&mut task.runs, stale.runs);
3754 }
3755 for (ledger, entries) in [
3756 (&mut task.decision_effects, stale.decision_effects),
3757 (&mut task.superseded_resumes, stale.superseded_resumes),
3758 (&mut task.dispatched_resumes, stale.dispatched_resumes),
3759 ] {
3760 for (key, value) in entries {
3761 ledger.entry(key).or_insert(value);
3762 }
3763 }
3764 append_missing(&mut task.actions_applied, stale.actions_applied);
3765 append_missing(&mut task.triage_applied, stale.triage_applied);
3766 append_missing(&mut task.chat_notices, stale.chat_notices);
3767 append_missing(
3768 &mut task.base_recovery_requests,
3769 stale.base_recovery_requests,
3770 );
3771 append_missing(
3772 &mut task.land_sync_recovery_requests,
3773 stale.land_sync_recovery_requests,
3774 );
3775 prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3778 a.request.request == b.request.request
3779 });
3780 prepend_missing_by(
3781 &mut task.repair_reconciliations,
3782 stale.repair_reconciliations,
3783 |a, b| a.request.request == b.request.request,
3784 );
3785 stale.resumption_history.extend(stale.resumption);
3788 stale.resumption_history.retain(|approval| {
3789 task.resumption
3790 .as_ref()
3791 .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3792 });
3793 prepend_missing_by(
3794 &mut task.resumption_history,
3795 stale.resumption_history,
3796 |a, b| a.at == b.at && a.generation == b.generation,
3797 );
3798 for failure in stale.startup_failures {
3799 task.record_startup_failure(failure);
3800 }
3801 for pass in stale.passes {
3802 if !task.passes.iter().any(|stored| {
3803 stored.run == pass.run && stored.pass_index == pass.pass_index
3804 }) {
3805 task.passes.push(pass);
3806 }
3807 }
3808 task.completion_history = history;
3809 if !task.decision_effects.is_empty() {
3810 task.stamp_schema();
3811 }
3812 return;
3813 }
3814 if stored.reassignments.len() > task.reassignments.len() {
3815 let stale = std::mem::replace(task, stored.clone());
3818 for answer in stale.answers {
3819 if !task.answers.contains(&answer) {
3820 task.answers.push(answer);
3821 }
3822 }
3823 }
3824 if task.updated_at < stored.updated_at
3827 && (task.sync_only != stored.sync_only
3828 || stored.sync_only.is_some()
3829 || (task.reopen_hold.is_some() && task.reopen_hold != stored.reopen_hold)
3830 || stored
3831 .recovery_budget_hold
3832 .as_ref()
3833 .is_some_and(|hold| hold.held_at > task.updated_at)
3834 || stored.repair_grants.last().is_some_and(|grant| {
3835 task.repair_grants.last() != Some(grant)
3836 || stored.operator_decided_at > task.operator_decided_at
3837 || stored
3838 .resume_override
3839 .as_ref()
3840 .is_some_and(|pin| pin.at > task.updated_at)
3841 || (task.resume_override != stored.resume_override
3842 && task
3843 .resume_override
3844 .as_ref()
3845 .is_some_and(|pin| pin.at == grant.at))
3846 }))
3847 && task
3848 .operator_decided_at
3849 .is_none_or(|at| at <= stored.updated_at)
3850 && task
3851 .resume_override
3852 .as_ref()
3853 .is_none_or(|pin| pin.at <= stored.updated_at)
3854 && !local_decision
3855 {
3856 *task = stored.clone();
3857 }
3858 task.completion_history = history;
3859 append_missing(
3860 &mut task.base_recovery_requests,
3861 stored.base_recovery_requests,
3862 );
3863 append_missing(
3864 &mut task.land_sync_recovery_requests,
3865 stored.land_sync_recovery_requests,
3866 );
3867 append_missing(&mut task.actions_applied, stored.actions_applied);
3868 append_missing(&mut task.triage_applied, stored.triage_applied);
3869 for receipt in &stored.repair_grants {
3870 if !task
3871 .repair_grants
3872 .iter()
3873 .any(|r| r.request.request == receipt.request.request)
3874 {
3875 task.repair_grants.push(receipt.clone());
3877 }
3878 }
3879 for receipt in &stored.repair_reconciliations {
3880 if !task.repair_reconciliations.contains(receipt) {
3881 task.repair_reconciliations.push(receipt.clone());
3884 task.resume_override = stored.resume_override.clone();
3885 task.status = stored.status;
3886 task.hold_source = stored.hold_source;
3887 task.machine_hold_cause = stored.machine_hold_cause.clone();
3888 task.disk_resume_run = stored.disk_resume_run.clone();
3889 task.disk_checked_at = stored.disk_checked_at;
3890 task.hold_reason = stored.hold_reason.clone();
3891 task.held_at = stored.held_at;
3892 }
3893 }
3894 task.superseded_resumes.extend(stored.superseded_resumes);
3895 task.dispatched_resumes.extend(stored.dispatched_resumes);
3896 if task.status != TaskStatus::Running
3897 && let Some(pin) = &stored.resume_override
3898 && !pin.question_id.is_empty()
3899 && let Some(run) = &pin.pinned_run
3900 && task.resume_override.as_ref().is_none_or(|next| {
3901 next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3902 })
3903 {
3904 task.superseded_resumes
3905 .insert(pin.question_id.clone(), run.clone());
3906 }
3907 for (id, receipt) in stored.decision_effects {
3910 task.decision_effects.insert(id, receipt);
3911 }
3912 if !task.decision_effects.is_empty() {
3913 task.stamp_schema();
3914 }
3915 if task.chat.is_none() {
3918 task.chat = stored.chat.clone();
3919 }
3920 if task.issue.is_none() {
3921 task.issue = stored.issue.clone();
3922 }
3923 append_missing(&mut task.chat_notices, stored.chat_notices);
3924 for failure in stored.startup_failures {
3925 task.record_startup_failure(failure);
3926 }
3927 append_missing(&mut task.runs, stored.runs);
3928 for p in stored.passes {
3929 if !task
3930 .passes
3931 .iter()
3932 .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3933 {
3934 task.passes.push(p);
3935 }
3936 }
3937 if let Some(n) = stored.chat_notice
3940 && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3941 {
3942 task.chat_notice = Some(n);
3943 }
3944 }
3945 }
3946
3947 pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3950 let path = self.path_of(&task.id);
3951 let tmp = path.with_extension("json.tmp");
3952 std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3953 std::fs::rename(tmp, path)?;
3954 Ok(())
3955 }
3956
3957 fn write_record(&self, task: &mut Task) -> Result<()> {
3959 self.write_record_inner(task, true)
3960 }
3961
3962 fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3963 task.import_chat_notice();
3964 if task.status != TaskStatus::Held && task.sync_only.is_none() {
3965 task.recovery_budget_hold = None;
3966 }
3967 task.updated_at = Timestamp::now();
3968 std::fs::create_dir_all(&self.root)
3969 .with_context(|| format!("create {}", self.root.display()))?;
3970 let body = serde_json::to_string_pretty(task).context("serialize task")?;
3971 let path = self.path_of(&task.id);
3972 let tmp = path.with_extension("json.tmp");
3973 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3974 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3975 if let (Some(notice), Some(home)) = (
3980 notify.then(|| crate::notices::task_held(task)).flatten(),
3981 self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3982 ) {
3983 crate::notices::raise_in(home, notice);
3984 }
3985 Ok(())
3986 }
3987
3988 pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3993 let id = self.resolve_id(id)?;
3994 let _lock = self.lock_task(&id)?;
3995 let mut task = self.get(&id)?;
3996 if !f(&mut task) {
3997 return Ok(false);
3998 }
3999 self.put_unlocked(&mut task)?;
4000 Ok(true)
4001 }
4002
4003 pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
4008 let id = self.resolve_id(id)?;
4009 let _lock = self.lock_task(&id)?;
4012 let mut task = self.get(&id)?;
4013 if task.link_run(run) {
4014 self.put_unlocked(&mut task)?;
4015 }
4016 Ok(task)
4017 }
4018
4019 pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
4027 std::fs::create_dir_all(&self.root)
4028 .with_context(|| format!("create {}", self.root.display()))?;
4029 let path = self.root.join(format!("{id}.write-lock"));
4030 let started = std::time::Instant::now();
4031 let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
4032 let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
4033 loop {
4034 match retry.create(&path) {
4035 Ok(mut file) => {
4036 use std::io::Write;
4037 let token = owner_token();
4038 if let Err(e) = file.write_all(token.as_bytes()) {
4039 drop(file);
4040 let _ = std::fs::remove_file(&path);
4041 return Err(e).with_context(|| format!("lock {}", path.display()));
4042 }
4043 return Ok(TaskLock { path, token });
4044 }
4045 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4046 let judged = std::fs::read_to_string(&path).ok();
4049 let broken = judged
4050 .filter(|_| older_than_stale(&path))
4051 .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
4052 if !broken {
4056 if started.elapsed() > TASK_LOCK_STALE {
4057 bail!("could not lock task {id}");
4058 }
4059 std::thread::sleep(std::time::Duration::from_millis(15));
4060 }
4061 }
4062 Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
4063 }
4064 }
4065 }
4066
4067 pub fn get(&self, id: &str) -> Result<Task> {
4069 let resolved = self.resolve_id(id)?;
4070 read_path(&self.path_of(&resolved))
4071 }
4072
4073 pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
4105 self.remove_with_receipt(id, in_flight, questions, None)
4106 }
4107
4108 pub(crate) fn discard_triage(
4110 &self,
4111 id: &str,
4112 questions: &Questions,
4113 inquiry: &str,
4114 ) -> Result<Removal> {
4115 self.remove_with_receipt(id, false, questions, Some(inquiry))
4116 }
4117
4118 pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
4119 let path = self
4120 .root
4121 .join("triage-discard")
4122 .join(format!("{inquiry}.json"));
4123 let bytes = match std::fs::read(path) {
4124 Ok(bytes) => bytes,
4125 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
4126 Err(e) => return Err(e.into()),
4127 };
4128 let receipt: Task = serde_json::from_slice(&bytes)?;
4129 Ok(receipt.id == id && !self.path_of(id).exists())
4130 }
4131
4132 fn remove_with_receipt(
4133 &self,
4134 id: &str,
4135 in_flight: bool,
4136 questions: &Questions,
4137 inquiry: Option<&str>,
4138 ) -> Result<Removal> {
4139 let resolved = self.resolve_id(id)?;
4140 if in_flight {
4141 bail!("task {resolved} is being run by a live daemon right now");
4142 }
4143 let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
4144 if let Some(path) = &receipt {
4145 std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
4146 }
4147 self.write_tombstone(&resolved)?;
4148 if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
4149 Some(path) => std::fs::rename(p, path),
4150 None => std::fs::remove_file(p),
4151 }) {
4152 if self.path_of(&resolved).exists() {
4156 let _ = std::fs::remove_file(self.tombstone_path(&resolved));
4157 }
4158 return Err(e);
4159 }
4160 let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
4161 Ok(Removal {
4162 id: resolved,
4163 released,
4164 still_blocked,
4165 })
4166 }
4167
4168 fn tombstone_path(&self, id: &str) -> PathBuf {
4171 self.root.join(format!("{id}.removed"))
4172 }
4173
4174 fn write_tombstone(&self, id: &str) -> Result<()> {
4175 let path = self.tombstone_path(id);
4176 let tmp = self.root.join(format!("{id}.removed.tmp"));
4177 std::fs::write(&tmp, b"")
4178 .and_then(|()| std::fs::rename(&tmp, &path))
4179 .with_context(|| format!("write {}", path.display()))
4180 }
4181
4182 fn was_deleted(&self, id: &str) -> bool {
4186 self.tombstone_path(id).is_file() && !self.path_of(id).exists()
4187 }
4188
4189 pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
4193 let deleted = deleted_blockers(self, questions, &task.blocked_by);
4194 deleted
4195 .into_iter()
4196 .filter(|id| task.dependency_deleted(id))
4197 .collect()
4198 }
4199
4200 pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
4204 let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
4205 return;
4206 };
4207 let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
4208 let waiting = dependent.status == TaskStatus::Blocked;
4209 let message = match (ja, waiting) {
4210 (true, false) => format!(
4211 "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
4212 dependent.short(),
4213 short(deleted)
4214 ),
4215 (true, true) => format!(
4216 "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
4217 dependent.short(),
4218 short(deleted)
4219 ),
4220 (false, false) => format!(
4221 "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
4222 dependent.short(),
4223 short(deleted)
4224 ),
4225 (false, true) => format!(
4226 "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
4227 dependent.short(),
4228 short(deleted)
4229 ),
4230 };
4231 crate::notices::raise_in(
4232 home,
4233 crate::notices::Notice::info(
4234 &format!("unblocked:{}:{}", dependent.id, deleted),
4235 message,
4236 )
4237 .link(crate::notices::Link::Task {
4238 id: dependent.id.clone(),
4239 }),
4240 );
4241 }
4242
4243 fn release_dependents_of(
4248 &self,
4249 dependency: &str,
4250 questions: &Questions,
4251 ) -> (Vec<String>, Vec<String>) {
4252 let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
4253 for listed in self.list() {
4254 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
4255 matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
4256 }) {
4257 continue;
4258 }
4259 let Ok(_claim) = self.claim(&listed.id) else {
4260 continue;
4261 };
4262 let Ok(mut task) = self.get(&listed.id) else {
4263 continue;
4264 };
4265 let references: Vec<String> = task.blocked_by.iter().filter(|id| {
4266 matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
4267 }).cloned().collect();
4268 if references.is_empty() {
4269 continue;
4270 }
4271 for reference in references {
4272 task.dependency_deleted(&reference);
4273 }
4274 if self.put(&mut task).is_err() {
4275 continue;
4276 }
4277 self.note_dependency_deleted(&task, dependency);
4278 if task.status == TaskStatus::Blocked {
4279 still_blocked.push(task.id.clone());
4280 } else {
4281 released.push(task.id.clone());
4282 }
4283 }
4284 (released, still_blocked)
4285 }
4286
4287 fn remove_record_with_attachments(
4291 &self,
4292 resolved: &str,
4293 remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4294 ) -> Result<()> {
4295 self.sweep_removed_attachments();
4302 let attachments = self.attachments_dir(resolved);
4303 let aside = self.root.join(format!("{resolved}.attachments.removing"));
4304 let moved = match std::fs::rename(&attachments, &aside) {
4305 Ok(()) => true,
4306 Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4307 Err(e) => {
4308 return Err(e).with_context(|| format!("remove {}", attachments.display()));
4309 }
4310 };
4311 let path = self.path_of(resolved);
4312 if let Err(e) = remove_record(&path) {
4313 if moved {
4314 let _ = std::fs::rename(&aside, &attachments);
4315 }
4316 return Err(e).with_context(|| format!("remove {}", path.display()));
4317 }
4318 if moved {
4319 if let Err(e) = std::fs::remove_dir_all(&aside) {
4320 tracing::warn!("leftover attachments {}: {e}", aside.display());
4321 }
4322 }
4323 let lock = self.lock_path(resolved);
4324 if let Err(e) = std::fs::remove_file(&lock) {
4325 if e.kind() != std::io::ErrorKind::NotFound {
4326 return Err(e).with_context(|| format!("remove {}", lock.display()));
4327 }
4328 }
4329 Ok(())
4330 }
4331
4332 fn sweep_removed_attachments(&self) {
4338 let Ok(entries) = std::fs::read_dir(&self.root) else {
4339 return;
4340 };
4341 for entry in entries.flatten() {
4342 let name = entry.file_name();
4343 let name = name.to_string_lossy();
4344 let Some(id) = name.strip_suffix(".attachments.removing") else {
4345 continue;
4346 };
4347 if !self.path_of(id).exists() {
4350 if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4351 tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4352 }
4353 }
4354 }
4355 self.sweep_tombstones();
4356 }
4357
4358 fn sweep_tombstones(&self) {
4367 let Ok(entries) = std::fs::read_dir(&self.root) else {
4368 return;
4369 };
4370 let tasks = self.list();
4371 for entry in entries.flatten() {
4372 let name = entry.file_name();
4373 let name = name.to_string_lossy();
4374 let Some(id) = name.strip_suffix(".removed") else {
4375 continue;
4376 };
4377 if self.path_of(id).exists()
4378 || tasks.iter().any(|t| {
4379 t.blocked_by
4380 .iter()
4381 .any(|b| id.starts_with(b) || id.ends_with(b))
4382 })
4383 {
4384 continue;
4385 }
4386 let old = entry
4387 .metadata()
4388 .and_then(|m| m.modified())
4389 .ok()
4390 .and_then(|m| m.elapsed().ok())
4391 .is_some_and(|age| age >= TOMBSTONE_GRACE);
4392 if old {
4393 let _ = std::fs::remove_file(entry.path());
4394 }
4395 }
4396 }
4397
4398 fn lock_path(&self, id: &str) -> PathBuf {
4401 self.root.join(format!("{id}.lock"))
4402 }
4403
4404 pub fn list(&self) -> Vec<Task> {
4417 #[cfg(test)]
4418 LIST_READS.with(|count| count.set(count.get() + 1));
4419 let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4420 .into_iter()
4421 .flatten()
4422 .flatten()
4423 .map(|e| e.path())
4424 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4425 .filter_map(|p| read_path(&p).ok())
4426 .collect();
4427 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4428 tasks
4429 }
4430
4431 pub fn unreadable(&self) -> Vec<PathBuf> {
4435 std::fs::read_dir(&self.root)
4436 .into_iter()
4437 .flatten()
4438 .flatten()
4439 .map(|e| e.path())
4440 .filter(|p| p.extension().is_some_and(|x| x == "json"))
4441 .filter(|p| read_path(p).is_err())
4442 .collect()
4443 }
4444
4445 pub fn superseded(&self) -> HashMap<String, String> {
4458 let mut by = HashMap::new();
4459 for task in self.list() {
4460 for earlier in &task.runs {
4461 if let Some(later) = task.successor_of(earlier) {
4462 by.insert(earlier.clone(), later.clone());
4463 }
4464 }
4465 }
4466 by
4467 }
4468
4469 pub fn superseded_by(&self, run: &str) -> Option<String> {
4477 for task in self.list() {
4478 if task.runs.iter().any(|r| r == run) {
4479 return task.successor_of(run).cloned();
4480 }
4481 }
4482 None
4483 }
4484
4485 pub fn latest_attempt(&self, run: &str) -> Option<String> {
4496 for task in self.list() {
4497 if task.runs.iter().any(|r| r == run) {
4498 return task.runs.last().filter(|last| **last != run).cloned();
4499 }
4500 }
4501 None
4502 }
4503
4504 pub fn next_runnable(&self) -> Option<Task> {
4509 let mut runnable: Vec<Task> = self
4510 .list()
4511 .into_iter()
4512 .filter(|t| t.status.runnable())
4513 .collect();
4514 runnable.sort_unstable_by(dispatch_order);
4515 runnable.into_iter().next()
4516 }
4517
4518 pub fn claim(&self, id: &str) -> Result<Claim> {
4525 std::fs::create_dir_all(&self.root)
4526 .with_context(|| format!("create {}", self.root.display()))?;
4527 let path = self.lock_path(id);
4528 let retry = crate::lock_file::Retry::new(None);
4529 match retry.create(&path) {
4530 Ok(mut f) => {
4531 use std::io::Write as _;
4532 let _ = writeln!(f, "{}", std::process::id());
4534 Ok(Claim { path })
4535 }
4536 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4537 bail!("task {id} is already claimed ({} exists)", path.display())
4538 }
4539 Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4540 }
4541 }
4542
4543 #[must_use]
4546 pub fn is_claimed(&self, id: &str) -> bool {
4547 self.lock_path(id).exists()
4548 }
4549
4550 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4552 if !prefix.is_empty()
4553 && prefix != "."
4554 && prefix != ".."
4555 && !prefix.contains(['/', '\\'])
4556 && self.path_of(prefix).is_file()
4557 {
4558 return Ok(prefix.to_owned());
4559 }
4560 let ids = record_ids(&self.root, "json")?;
4561 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4562 Reference::Found(id) => Ok(id),
4563 Reference::Missing => bail!("no task matches `{prefix}`"),
4564 Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4565 }
4566 }
4567
4568 pub fn revision(&self) -> u64 {
4575 self.revision_excluding(&std::collections::BTreeSet::new())
4576 }
4577
4578 pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4581 use std::hash::{Hash as _, Hasher as _};
4582
4583 let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4584 .into_iter()
4585 .flatten()
4586 .flatten()
4587 .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4588 .filter(|e| {
4589 let path = e.path();
4590 !path
4591 .file_stem()
4592 .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4593 })
4594 .filter_map(|e| {
4595 let name = e.file_name().to_string_lossy().into_owned();
4596 let mtime = e
4597 .metadata()
4598 .ok()?
4599 .modified()
4600 .ok()?
4601 .duration_since(std::time::UNIX_EPOCH)
4602 .ok()?
4603 .as_millis() as u64;
4604 Some((name, mtime))
4605 })
4606 .collect();
4607
4608 if entries.is_empty() {
4609 return 0;
4610 }
4611
4612 entries.sort_unstable();
4613 let mut hasher = std::hash::DefaultHasher::new();
4614 for (name, mtime) in &entries {
4615 name.hash(&mut hasher);
4616 mtime.hash(&mut hasher);
4617 }
4618 let h = hasher.finish();
4619 if h == 0 { 1 } else { h }
4620 }
4621}
4622
4623const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4626
4627#[derive(Debug, Clone)]
4629pub struct Removal {
4630 pub id: String,
4632 pub released: Vec<String>,
4636 pub still_blocked: Vec<String>,
4639}
4640
4641#[derive(Debug)]
4643pub struct Claim {
4644 path: PathBuf,
4645}
4646
4647impl Drop for Claim {
4648 fn drop(&mut self) {
4649 let _ = std::fs::remove_file(&self.path);
4650 }
4651}
4652
4653pub fn title_from(instruction: &str, max: usize) -> String {
4656 let Some(line) = first_line(instruction) else {
4657 return "(empty task)".to_owned();
4658 };
4659 if line.chars().count() <= max {
4660 return line.to_owned();
4661 }
4662 let head: String = line.chars().take(max.saturating_sub(1)).collect();
4663 format!("{head}…")
4664}
4665
4666pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4672 let line = instruction
4673 .lines()
4674 .map(str::trim)
4675 .find(|l| !l.is_empty())?
4676 .trim_start_matches(['#', '-', '*', '>', ' '])
4677 .trim();
4678 (!line.is_empty()).then_some(line)
4679}
4680
4681#[cfg(test)]
4682thread_local! {
4683 pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4684}
4685
4686fn read_path(path: &Path) -> Result<Task> {
4687 #[cfg(test)]
4688 TASK_READS.with(|count| count.set(count.get() + 1));
4689 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4690 let mut task: Task =
4691 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4692 if task.schema > SCHEMA {
4698 bail!(
4699 "task {} was written by a different magi (schema {}, this build \
4700 speaks {SCHEMA})",
4701 task.id,
4702 task.schema
4703 );
4704 }
4705 task.preserve_legacy_build_cache();
4706 task.snapshot_legacy_reopen_hold();
4707 if task.schema < 22
4708 && task.status == TaskStatus::Held
4709 && task.hold_source == Some(HoldSource::Machine)
4710 && task.resume_override.is_none()
4711 && task
4712 .hold_reason
4713 .as_deref()
4714 .is_some_and(crate::disk::is_gate_reason)
4715 {
4716 task.mark_disk_capacity();
4717 }
4718 Ok(task)
4719}
4720
4721#[derive(Debug, PartialEq, Eq)]
4724pub(crate) enum Reference {
4725 Found(String),
4726 Missing,
4727 Ambiguous,
4728}
4729
4730pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4731 let mut hits = Vec::new();
4732 for candidate in ids {
4733 if candidate == id {
4734 return Reference::Found(candidate.to_owned());
4735 }
4736 if candidate.starts_with(id) || candidate.ends_with(id) {
4737 hits.push(candidate);
4738 }
4739 }
4740 match hits.as_slice() {
4741 [] => Reference::Missing,
4742 [one] => Reference::Found((*one).to_owned()),
4743 _ => Reference::Ambiguous,
4744 }
4745}
4746
4747pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4750 let entries = match std::fs::read_dir(root) {
4751 Ok(entries) => entries,
4752 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4753 Err(e) => return Err(e.into()),
4754 };
4755 let mut ids = Vec::new();
4756 for entry in entries {
4757 let path = entry?.path();
4758 if path.extension().is_some_and(|e| e == extension)
4759 && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4760 {
4761 ids.push(id.to_owned());
4762 }
4763 }
4764 Ok(ids)
4765}
4766
4767#[derive(Debug, PartialEq, Eq)]
4770pub enum Dependency {
4771 Task(String),
4773 Question(String),
4775 Deleted(String),
4777 Missing,
4779 Ambiguous,
4781 Unknown,
4783}
4784
4785pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4787 let (Ok(tasks), Ok(qs), Ok(removed)) = (
4788 record_ids(queue.root(), "json"),
4789 record_ids(questions.root(), "json"),
4790 record_ids(queue.root(), "removed"),
4791 ) else {
4792 return Dependency::Unknown;
4793 };
4794 let mut ids = tasks
4797 .iter()
4798 .chain(qs.iter())
4799 .chain(removed.iter())
4800 .cloned()
4801 .collect::<Vec<_>>();
4802 ids.sort();
4803 ids.dedup();
4804 match resolve_reference(id, ids.iter().map(String::as_str)) {
4805 Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4806 Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4807 Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4808 Reference::Found(_) => Dependency::Unknown,
4809 Reference::Missing => Dependency::Missing,
4810 Reference::Ambiguous => Dependency::Ambiguous,
4811 }
4812}
4813
4814pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4816 for id in ids {
4817 if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4818 dependency(queue, questions, id)
4819 {
4820 *id = full;
4821 }
4822 }
4823}
4824
4825pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4828 let inventory = crate::blockers::Inventory::load(queue, questions);
4829 let mut text = String::from(
4830 "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4831 );
4832 match record_ids(queue.root(), "json") {
4833 Ok(ids) => {
4834 for id in ids {
4835 match queue.get(&id) {
4836 Ok(task) => text.push_str(&format!(
4837 "{}: {}; blocked_by={:?}; chain={:?}\n",
4838 task.id,
4839 task.status.as_str(),
4840 task.blocked_by,
4841 inventory.waits_on(&task)
4842 )),
4843 Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4844 }
4845 }
4846 }
4847 Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4848 }
4849 text
4850}
4851
4852pub fn missing_blockers(
4854 queue: &Queue,
4855 questions: &Questions,
4856 blocked_by: &[String],
4857) -> Vec<String> {
4858 blocked_by
4859 .iter()
4860 .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4861 .cloned()
4862 .collect()
4863}
4864
4865pub fn deleted_blockers(
4868 queue: &Queue,
4869 questions: &Questions,
4870 blocked_by: &[String],
4871) -> Vec<String> {
4872 blocked_by
4873 .iter()
4874 .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4875 .cloned()
4876 .collect()
4877}
4878
4879pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4891 missing_blocker_hold_reason_in(blocked_by, missing, "en")
4892}
4893
4894pub fn missing_blocker_hold_reason_in(
4896 blocked_by: &[String],
4897 missing: &[String],
4898 language: &str,
4899) -> String {
4900 if crate::lang::is_japanese(language) {
4901 format!(
4902 "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4903 blocked_by.join(", "),
4904 missing.join(", "),
4905 )
4906 } else {
4907 format!(
4908 "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4909 blocked_by.join(", "),
4910 missing.join(", "),
4911 )
4912 }
4913}
4914
4915pub fn short(id: &str) -> &str {
4917 id.split('-').next_back().unwrap_or(id)
4918}
4919
4920fn new_id() -> String {
4921 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4922 let seed = crate::rng::entropy();
4923 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4924}
4925
4926#[cfg(test)]
4927mod tests {
4928 #[test]
4929 fn reassignment_clears_repository_bound_execution_selections() {
4930 let mut task = Task::new(
4931 "move".into(),
4932 "evidence".into(),
4933 "old".into(),
4934 Source::Human,
4935 );
4936 task.review_branch = Some("old-review".into());
4937 task.review_instruction = Some("old criteria".into());
4938 task.pr_recovery = Some(crate::pr_recovery::Selection {
4939 url: "https://example.invalid/pull/1".into(),
4940 branch: "old-pr".into(),
4941 head: "head".into(),
4942 source_head: None,
4943 source_run: None,
4944 source_proof: None,
4945 disposition: None,
4946 instruction: "old criteria".into(),
4947 approved_at: Timestamp::now(),
4948 });
4949 task.replacement = Some(crate::merge_decision::Replacement {
4950 question: "owner".into(),
4951 run: "old-run".into(),
4952 pr: "https://example.invalid/pull/1".into(),
4953 agent: "worker".into(),
4954 context: "evidence".into(),
4955 });
4956 task.resume_override = Some(OperatorResume {
4957 question_id: "old-question".into(),
4958 at: Timestamp::now(),
4959 conductor_rehold: None,
4960 forced: true,
4961 pinned_run: Some("old-run".into()),
4962 });
4963 task.interrupt = true;
4964 task.reassign_repository("new".into(), "test");
4965 assert!(task.review_branch.is_none());
4966 assert!(task.review_instruction.is_none());
4967 assert!(task.pr_recovery.is_none());
4968 assert!(task.replacement.is_none());
4969 assert!(task.resume_override.is_none());
4970 assert!(!task.interrupt);
4971 assert!(task.fresh_start);
4972 assert_eq!(task.instruction, "evidence");
4973 }
4974
4975 #[test]
4976 fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4977 let t = Task::new(
4978 "retry".into(),
4979 "do it".into(),
4980 PathBuf::from("."),
4981 Source::Human,
4982 );
4983 let mut value = serde_json::to_value(&t).unwrap();
4984 for field in ["resumption", "resumption_history", "operator_decided_at"] {
4985 value.as_object_mut().unwrap().remove(field);
4986 }
4987 value["schema"] = serde_json::json!(15);
4988 let mut legacy: Task = serde_json::from_value(value).unwrap();
4989 legacy.hold_machine(Some("automatic retry".into()));
4990 legacy.release();
4991 assert!(legacy.resumption.is_none());
4992 assert!(legacy.resumption_history.is_empty());
4993 assert!(legacy.operator_decided_at.is_none());
4994 legacy.release_operator("cli", None);
4995 legacy.start("run".into());
4996 let reloaded: Task =
4997 serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4998 assert!(reloaded.resume_override.is_none());
4999 assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
5000 }
5001
5002 #[test]
5003 fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
5004 let mut base = RunOverrides {
5005 merge: Some("pr".to_owned()),
5006 candidates: Some(3),
5007 ..RunOverrides::default()
5008 };
5009 base.merge_over(&RunOverrides {
5010 merge: Some("none".to_owned()),
5011 seed: Some(7),
5012 ..RunOverrides::default()
5013 });
5014 assert_eq!(base.merge.as_deref(), Some("none"));
5015 assert_eq!(base.candidates, Some(3));
5016 assert_eq!(base.seed, Some(7));
5017 }
5018
5019 #[test]
5020 fn an_already_landed_task_is_done_with_its_attempt_refunded() {
5021 let mut t = task("relanded");
5022 t.attempts = 1;
5023 t.status = TaskStatus::Running;
5024 t.already_landed("already in main as 0e368de", completion(&t));
5025 assert_eq!(t.status, TaskStatus::Done);
5026 assert_eq!(t.attempts, 0);
5027 assert!(t.hold_reason.is_none());
5028 assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
5029 }
5030
5031 #[test]
5032 fn missing_blocker_reason_follows_the_language() {
5033 let b = vec!["a".to_owned()];
5034 let en = missing_blocker_hold_reason_in(&b, &b, "en");
5035 assert_eq!(en, missing_blocker_hold_reason(&b, &b));
5036 assert!(en.starts_with("blocked on a"));
5037 assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
5038 assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
5039 }
5040
5041 use super::*;
5042
5043 fn completion(task: &Task) -> CompletionContext {
5044 CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
5045 }
5046
5047 #[test]
5048 fn completion_retains_the_hold_dependency_and_failure_it_clears() {
5049 let mut held = task("held evidence");
5050 held.hold_manual(Some("owner approval required".into()));
5051 held.last_error = Some("review budget exhausted".into());
5052 held.succeed(completion(&held));
5053 let event = held.completion_history.last().unwrap();
5054 assert_eq!(event.prior_status, TaskStatus::Held);
5055 assert_eq!(
5056 event.prior_hold_reason.as_deref(),
5057 Some("owner approval required")
5058 );
5059 assert_eq!(
5060 event.prior_error.as_deref(),
5061 Some("review budget exhausted")
5062 );
5063 assert!(held.hold_reason.is_none());
5064 assert!(held.last_error.is_none());
5065 let mut blocked = task("dependency evidence");
5066 blocked.block(
5067 vec!["dependency".into()],
5068 Some("waiting on migration".into()),
5069 );
5070 blocked.succeed(completion(&blocked));
5071 let event = blocked.completion_history.last().unwrap();
5072 assert_eq!(event.prior_status, TaskStatus::Blocked);
5073 assert_eq!(
5074 event.prior_block_reason.as_deref(),
5075 Some("waiting on migration")
5076 );
5077 assert!(blocked.block_reason.is_none());
5078 assert!(blocked.blocked_by.is_empty());
5079 let saved = serde_json::to_vec(&held).unwrap();
5080 let restored: Task = serde_json::from_slice(&saved).unwrap();
5081 assert_eq!(restored.completion_history, held.completion_history);
5082 }
5083
5084 #[test]
5085 fn completion_audit_is_append_only_under_stale_puts() {
5086 let dir = tempfile::tempdir().unwrap();
5087 let queue = Queue::at(dir.path().join("queue"));
5088 let mut current = task("audited");
5089 current.hold_manual(Some("inspect".into()));
5090 queue.put(&mut current).unwrap();
5091 let mut stale = queue.get(¤t.id).unwrap();
5092 current.succeed(completion(¤t));
5093 queue.put(&mut current).unwrap();
5094 let original = current.completion_history[0].clone();
5095 stale.last_error = Some("stale control state".into());
5096 queue.put(&mut stale).unwrap();
5097 assert_eq!(stale.status, TaskStatus::Done);
5098 assert_eq!(stale.completion_history, vec![original.clone()]);
5099 let mut context = completion(¤t);
5100 context.reason = Some("not actually finished".into());
5101 current.reopen(context).unwrap();
5102 queue.put(&mut current).unwrap();
5103 stale.completion_history[0].actor = CompletionActor::Web;
5104 stale.completion_history[0].reason = Some("rewritten evidence".into());
5105 queue.put(&mut stale).unwrap();
5106 assert_eq!(stale.status, TaskStatus::Held);
5107 assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
5108 assert_eq!(stale.completion_history[0], original);
5109 assert_eq!(stale.completion_history, current.completion_history);
5110 }
5111
5112 #[test]
5113 fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
5114 let (_dir, q) = queue();
5115 let mut current = task("durable receipts");
5116 q.put(&mut current).unwrap();
5117 let mut stale = current.clone();
5118 let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
5119 "request": {
5120 "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
5121 "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
5122 },
5123 "at": stale.updated_at, "contract": "old-contract"
5124 }))
5125 .unwrap();
5126 stale.release_operator("triage", Some("triage-question"));
5127 stale.queue_repair(&grant);
5128 let reconciliation: crate::repair_budget::reconcile::Receipt =
5129 serde_json::from_value(serde_json::json!({
5130 "request": {
5131 "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
5132 "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
5133 "request": "reconciliation", "reason": "retain the answer"
5134 },
5135 "grant": grant, "source": "answer", "application": "release",
5136 "decision": grant.at, "superseded_questions": []
5137 }))
5138 .unwrap();
5139 stale.repair_reconciliations.push(reconciliation.clone());
5140 stale.triage_applied.push("triage-question".into());
5141 stale.actions_applied.push("choice".into());
5142 stale.base_recovery_requests.push("base-request".into());
5143 stale.chat_notices.push("delivery".into());
5144 stale.chat_notice = Some(ChatNotice {
5145 key: "other-delivery".into(),
5146 at: grant.at,
5147 outcome: ChatNoticeOutcome::Posted,
5148 });
5149 for ledger in [
5150 &mut stale.decision_effects,
5151 &mut stale.dispatched_resumes,
5152 &mut stale.superseded_resumes,
5153 ] {
5154 ledger.insert("shared".into(), "stale".into());
5155 ledger.insert("only-stale".into(), "receipt".into());
5156 }
5157
5158 let mut latest_grant = grant.clone();
5159 latest_grant.request.request = "new-grant".into();
5160 current.queue_repair(&latest_grant);
5161 for ledger in [
5162 &mut current.decision_effects,
5163 &mut current.dispatched_resumes,
5164 &mut current.superseded_resumes,
5165 ] {
5166 ledger.insert("shared".into(), "committed".into());
5167 }
5168 current.succeed(completion(¤t));
5169 let mut context = completion(¤t);
5170 context.reason = Some("inspect again".into());
5171 current.reopen(context).unwrap();
5172 q.put(&mut current).unwrap();
5173
5174 for _ in 0..2 {
5175 q.put(&mut stale.clone()).unwrap();
5176 let saved = q.get(¤t.id).unwrap();
5177 assert_eq!(saved.status, TaskStatus::Held);
5178 assert_eq!(saved.hold_reason, current.hold_reason);
5179 assert_eq!(saved.operator_decided_at, current.operator_decided_at);
5180 assert_eq!(saved.completion_history, current.completion_history);
5181 assert!(saved.resume_override.is_none());
5182 assert!(saved.resumption.is_none());
5183 assert_eq!(
5184 saved.resumption_history,
5185 [stale.resumption.clone().unwrap()]
5186 );
5187 assert_eq!(saved.triage_applied, ["triage-question"]);
5188 assert_eq!(saved.actions_applied, ["choice"]);
5189 assert_eq!(saved.base_recovery_requests, ["base-request"]);
5190 assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
5191 assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
5192 assert_eq!(
5193 saved.repair_reconciliations,
5194 std::slice::from_ref(&reconciliation)
5195 );
5196 for ledger in [
5197 saved.decision_effects,
5198 saved.dispatched_resumes,
5199 saved.superseded_resumes,
5200 ] {
5201 assert_eq!(ledger["shared"], "committed");
5202 assert_eq!(ledger["only-stale"], "receipt");
5203 }
5204 }
5205 }
5206
5207 #[test]
5208 fn repeated_completion_only_notifies_for_new_occurrences() {
5209 let mut task = chat_task();
5210 task.succeed(completion(&task));
5211 let first = task.chat_notice_key().unwrap();
5212 task.chat_notices.push(first.clone());
5213 task.succeed(completion(&task));
5214 assert_eq!(task.completion_history.len(), 1, "idempotent while done");
5215 assert_eq!(task.chat_notice_due(), None);
5216 let mut context = completion(&task);
5217 context.reason = Some("inspect".into());
5218 task.reopen(context).unwrap();
5219 task.succeed(completion(&task));
5220 let second = task.chat_notice_key().unwrap();
5221 assert_ne!(first, second);
5222 assert_eq!(task.chat_notice_due(), Some(second));
5223 assert_eq!(task.completion_history.len(), 3);
5224 }
5225
5226 #[test]
5227 fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
5228 let mut task = task("legacy");
5229 task.status = TaskStatus::Done;
5230 let mut value = serde_json::to_value(&task).unwrap();
5231 value.as_object_mut().unwrap().remove("completion_history");
5232 let task: Task = serde_json::from_value(value).unwrap();
5233 assert!(task.completion_history.is_empty());
5234 assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
5235 }
5236
5237 #[test]
5238 fn triage_applied_survives_release_and_old_records_read_as_empty() {
5239 let mut t = Task::new(
5240 "t".to_owned(),
5241 "i".to_owned(),
5242 PathBuf::from("r"),
5243 Source::Human,
5244 );
5245 t.mark_triage_applied("q1");
5246 t.mark_triage_applied("q1");
5247 t.hold_machine(Some("x".to_owned()));
5248 t.release();
5249 assert_eq!(t.triage_applied, ["q1"]);
5250 assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
5251
5252 let mut v = serde_json::to_value(&t).unwrap();
5253 v.as_object_mut().unwrap().remove("triage_applied");
5254 let old: Task = serde_json::from_value(v).unwrap();
5255 assert!(old.triage_applied.is_empty());
5256 }
5257
5258 #[test]
5259 fn task_counts_of_empty_is_all_zero() {
5260 assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
5261 }
5262
5263 #[test]
5264 fn task_counts_of_tallies_every_status() {
5265 let mut queued = Task::new(
5266 "q".to_owned(),
5267 "i".to_owned(),
5268 PathBuf::from("."),
5269 Source::Human,
5270 );
5271 queued.status = TaskStatus::Queued;
5272 let mut running = queued.clone();
5273 running.status = TaskStatus::Running;
5274 let mut done = queued.clone();
5275 done.status = TaskStatus::Done;
5276 let mut failed = queued.clone();
5277 failed.status = TaskStatus::Failed;
5278 let mut held = queued.clone();
5279 held.status = TaskStatus::Held;
5280 let mut blocked = queued.clone();
5281 blocked.status = TaskStatus::Blocked;
5282
5283 let mut parked = queued.clone();
5284 parked.status = TaskStatus::Parked;
5285
5286 let counts = TaskCounts::of(&[
5287 queued,
5288 running,
5289 done.clone(),
5290 done,
5291 failed,
5292 held,
5293 blocked,
5294 parked,
5295 ]);
5296 assert_eq!(
5297 counts,
5298 TaskCounts {
5299 queued: 1,
5300 running: 1,
5301 done: 2,
5302 failed: 1,
5303 held: 1,
5304 blocked: 1,
5305 parked: 1,
5306 }
5307 );
5308 }
5309
5310 #[test]
5311 fn task_implementers_persist_normalized_without_losing_history() {
5312 let (_dir, q) = queue();
5313 let mut t = task("keep me");
5314 t.hold_manual(Some("waiting".into()));
5315 t.runs.push("earlier-run".into());
5316 t.attachments.push("reference.txt".into());
5317 let cfg: crate::config::Config =
5318 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5319 .unwrap();
5320 q.put(&mut t).unwrap();
5321 let original = serde_json::to_value(&t).unwrap();
5322 for n in [2, 1, 2] {
5323 t.set_implementers(n, &cfg).unwrap();
5324 q.put(&mut t).unwrap();
5325 t = q.get(&t.id).unwrap();
5326 assert_eq!(t.implementers(), Some(usize::from(n)));
5327 assert_eq!(t.solo, n == 1);
5328 if n == 1 {
5329 assert!(t.overrides.is_none());
5330 }
5331 let mut actual = serde_json::to_value(&t).unwrap();
5332 for field in ["solo", "overrides", "updated_at"] {
5333 actual[field] = original[field].clone();
5334 }
5335 assert_eq!(actual, original);
5336 }
5337 t.overrides.as_mut().unwrap().judges = Some(2);
5338 t.set_implementers(1, &cfg).unwrap();
5339 assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5340 assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5341 }
5342
5343 #[test]
5344 fn task_implementers_old_records_keep_inheritance_until_changed() {
5345 let mut value = serde_json::to_value(task("old task")).unwrap();
5346 value.as_object_mut().unwrap().remove("solo");
5347 value.as_object_mut().unwrap().remove("overrides");
5348 let mut old: Task = serde_json::from_value(value).unwrap();
5349 assert_eq!(old.implementers(), None);
5350 old.set_implementers(1, &crate::config::Config::default())
5351 .unwrap();
5352 assert!(old.solo);
5353 assert!(old.overrides.is_none());
5354 }
5355
5356 #[test]
5357 fn task_implementers_reject_invalid_counts_and_states() {
5358 let cfg = crate::config::Config::default();
5359 let mut t = task("unchanged");
5360 for n in [0, 4, 255] {
5361 assert!(t.set_implementers(n, &cfg).is_err());
5362 }
5363 for status in [
5364 TaskStatus::Running,
5365 TaskStatus::Done,
5366 TaskStatus::Failed,
5367 TaskStatus::Blocked,
5368 TaskStatus::Parked,
5369 ] {
5370 t.status = status;
5371 let before = serde_json::to_value(&t).unwrap();
5372 assert!(t.set_implementers(1, &cfg).is_err());
5373 assert_eq!(serde_json::to_value(&t).unwrap(), before);
5374 }
5375 }
5376
5377 fn queue() -> (tempfile::TempDir, Queue) {
5380 let dir = tempfile::tempdir().unwrap();
5381 let q = Queue::at(dir.path().join("queue"));
5382 (dir, q)
5383 }
5384
5385 #[test]
5386 fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5387 let (_dir, q) = queue();
5388 let mut original = task("base recovery");
5389 original
5390 .decision_effects
5391 .insert("old-effect".into(), "receipt".into());
5392 original
5393 .dispatched_resumes
5394 .insert("dispatched".into(), "prior-run".into());
5395 original.resume_override = Some(OperatorResume {
5396 question_id: "prior-decision".into(),
5397 at: Timestamp::now(),
5398 conductor_rehold: None,
5399 forced: true,
5400 pinned_run: Some("retained-run".into()),
5401 });
5402 q.put(&mut original).unwrap();
5403 let expected = serde_json::to_value(&original).unwrap();
5404 let mut recovered = original.clone();
5405 recovered.base_recovery_requests.push("chat/request".into());
5406 recovered
5407 .resume_override
5408 .as_mut()
5409 .unwrap()
5410 .question_id
5411 .clear();
5412 q.commit_base_recovery(&mut recovered, &expected).unwrap();
5413 let saved = q.get(&original.id).unwrap();
5414 assert_eq!(saved.decision_effects, original.decision_effects);
5415 assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5416 assert_eq!(
5417 saved
5418 .superseded_resumes
5419 .get("prior-decision")
5420 .map(String::as_str),
5421 Some("retained-run")
5422 );
5423 assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5424 assert!(saved.resume_override.unwrap().question_id.is_empty());
5425 assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5426 }
5427
5428 #[test]
5429 fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5430 let (_dir, q) = queue();
5431 let mut stale = task("chat");
5432 q.put(&mut stale).unwrap();
5433 let mut fresh = q.get(&stale.id).unwrap();
5434 fresh.chat = Some("talk-1".to_owned());
5435 q.put(&mut fresh).unwrap();
5436 q.put(&mut stale).unwrap();
5437 assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5438 }
5439
5440 #[test]
5441 fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5442 let dir = tempfile::tempdir().unwrap();
5443 let q = Queue::at(dir.path().join("queue"));
5444 let mut t = task("held");
5445 q.put(&mut t).unwrap();
5446 assert_eq!(
5447 crate::notices::Notices::at(dir.path().join("notifications"))
5448 .list()
5449 .len(),
5450 0
5451 );
5452 t.hold_machine(Some("out of attempts".to_owned()));
5453 q.put(&mut t).unwrap();
5454 let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5455 assert_eq!(listed.len(), 1);
5456 assert!(listed[0].message.contains("out of attempts"));
5457 }
5458
5459 #[test]
5460 fn start_consumes_the_disk_resume_pin() {
5461 let mut t = task("pin");
5462 t.disk_resume_run = Some("run-1".into());
5463 t.start("run-1".into());
5464 assert!(t.disk_resume_run.is_none());
5465 }
5466
5467 fn task(title: &str) -> Task {
5468 Task::new(
5469 title.to_owned(),
5470 format!("do {title}"),
5471 PathBuf::from("."),
5472 Source::Human,
5473 )
5474 }
5475
5476 #[test]
5477 fn issue_provenance_survives_queue_round_trip_without_inventing_chat() {
5478 let dir = tempfile::tempdir().unwrap();
5479 let q = Queue::at(dir.path().to_path_buf());
5480 let issue = IssueRef {
5481 number: 42,
5482 repo: "owner/repo".into(),
5483 };
5484 for source in [
5485 Source::Human,
5486 Source::Agent {
5487 run: "20260101-010101-abcd".into(),
5488 node: CHAT_NODE.into(),
5489 },
5490 ] {
5491 let mut t = task("issue");
5492 t.source = source;
5493 t.issue = Some(issue.clone());
5494 q.put(&mut t).unwrap();
5495 let saved = q.get(&t.id).unwrap();
5496 assert_eq!(saved.issue_ref(), Some(issue.clone()));
5497 assert_eq!(saved.source, t.source);
5498 assert_eq!(saved.filed_by_chat(), t.filed_by_chat());
5499 assert_eq!(saved.chat_talk(), t.filed_by_chat());
5500 if saved.source == Source::Human {
5501 assert_eq!(saved.source_label(), "issue #42");
5502 } else {
5503 assert!(saved.source_label().contains("issue #42"));
5504 }
5505 let mut stale = saved;
5506 stale.issue = None;
5507 q.put(&mut stale).unwrap();
5508 assert_eq!(q.get(&t.id).unwrap().issue_ref(), Some(issue.clone()));
5509 }
5510 let mut old = serde_json::to_value(task("legacy")).unwrap();
5511 old["schema"] = serde_json::json!(26);
5512 old["source"] = serde_json::json!({"kind":"issue","number":42,"repo":"owner/repo"});
5513 let legacy: Task = serde_json::from_value(old).unwrap();
5514 assert_eq!(legacy.issue_ref(), Some(issue));
5515 assert_eq!(legacy.filed_by_chat(), None);
5516 assert_eq!(legacy.chat_talk(), None);
5517 assert_eq!(legacy.source_label(), "issue #42");
5518 }
5519
5520 #[test]
5521 fn attempt_limit_inherits_old_records_and_controls_failure() {
5522 let mut t = task("budget");
5523 let mut old = serde_json::to_value(&t).unwrap();
5524 old.as_object_mut().unwrap().remove("attempt_limit");
5525 old["schema"] = serde_json::json!(15);
5526 let legacy: Task = serde_json::from_value(old).unwrap();
5527 assert_eq!(legacy.attempt_limit, None);
5528 assert_eq!(legacy.effective_attempt_limit(2), 2);
5529 t.attempts = 2;
5530 t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5531 t.fail("retry", 1);
5532 assert_eq!(t.status, TaskStatus::Failed);
5533 t.attempts = 3;
5534 t.fail("stop", 10);
5535 assert_eq!(t.status, TaskStatus::Held);
5536 t.change_attempt_limit(None).unwrap();
5537 assert_eq!(t.status, TaskStatus::Held);
5538 assert_eq!(t.attempts, 3);
5539 t.fail("inherit", 4);
5540 assert_eq!(t.status, TaskStatus::Failed);
5541 for status in [
5542 TaskStatus::Running,
5543 TaskStatus::Done,
5544 TaskStatus::Failed,
5545 TaskStatus::Blocked,
5546 TaskStatus::Parked,
5547 ] {
5548 t.status = status;
5549 assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5550 assert_eq!(t.attempt_limit, None);
5551 }
5552 }
5553
5554 #[test]
5555 fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5556 let mut t = task("retried");
5557 assert!(
5558 t.earlier_attempts().is_empty(),
5559 "a first attempt takes nothing over"
5560 );
5561 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5562 assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5563 assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5565 assert_eq!(t.successor_of("bbbb"), None);
5566 assert_eq!(t.successor_of("zzzz"), None);
5567 }
5568
5569 #[test]
5570 fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5571 let (_dir, q) = queue();
5572 let mut t = task("resumed");
5573 for (runs, successor) in [
5574 (vec!["aaaa", "aaaa"], None),
5575 (vec!["aaaa", "bbbb", "aaaa"], None),
5576 (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5577 (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5578 ] {
5579 t.runs = runs.into_iter().map(str::to_owned).collect();
5580 q.put(&mut t).unwrap();
5581
5582 assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5583 assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5584 assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5585 }
5586 }
5587
5588 #[test]
5589 fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5590 let (_dir, q) = queue();
5591 let mut t = task("retried");
5592 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5593 q.put(&mut t).unwrap();
5594
5595 assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5596 assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5597 assert_eq!(
5598 q.superseded_by("cccc"),
5599 None,
5600 "the latest attempt replaces nothing"
5601 );
5602 assert_eq!(
5603 q.superseded_by("never-heard-of-it"),
5604 None,
5605 "a run belonging to no task on this queue is not superseded"
5606 );
5607
5608 let mut by = HashMap::new();
5609 by.insert("aaaa".to_owned(), "bbbb".to_owned());
5610 by.insert("bbbb".to_owned(), "cccc".to_owned());
5611 assert_eq!(
5612 q.superseded(),
5613 by,
5614 "the whole-map and single-run forms must agree"
5615 );
5616 }
5617
5618 #[test]
5619 fn superseded_attempts_is_empty_until_the_task_is_done() {
5620 let mut t = task("retried");
5621 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5622 t.status = TaskStatus::Failed;
5623 assert_eq!(
5624 t.superseded_attempts(true),
5625 &[] as &[String],
5626 "a task still retrying has no attempt yet that a later one made moot"
5627 );
5628
5629 t.status = TaskStatus::Running;
5630 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5631 }
5632
5633 #[test]
5634 fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5635 let mut t = task("retried");
5636 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5637 t.status = TaskStatus::Done;
5638 assert_eq!(
5639 t.superseded_attempts(true),
5640 &["aaaa".to_owned(), "bbbb".to_owned()],
5641 "cccc is the attempt whose success made the task done, and stays out"
5642 );
5643 }
5644
5645 #[test]
5646 fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5647 let mut t = task("first try landed");
5648 t.runs = vec!["aaaa".to_owned()];
5649 t.status = TaskStatus::Done;
5650 assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5651 }
5652
5653 #[test]
5654 fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5655 let mut t = task("closed by hand after a manual merge");
5662 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5663 t.status = TaskStatus::Done;
5664 assert_eq!(
5665 t.superseded_attempts(false),
5666 &[] as &[String],
5667 "nothing here is provably why the task is done, so nothing is superseded"
5668 );
5669 }
5670
5671 #[test]
5672 fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5673 let (_dir, q) = queue();
5674 let mut t = task("retried twice");
5675 t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5676 q.put(&mut t).unwrap();
5677
5678 assert_eq!(
5679 q.latest_attempt("aaaa"),
5680 Some("cccc".to_owned()),
5681 "an old attempt points straight at the chain's current head, not the \
5682 next attempt in the middle of it"
5683 );
5684 assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5685 assert_eq!(
5686 q.latest_attempt("cccc"),
5687 None,
5688 "the latest attempt is not superseded by anything"
5689 );
5690 assert_eq!(
5691 q.latest_attempt("never-heard-of-it"),
5692 None,
5693 "a run belonging to no task on this queue is not superseded"
5694 );
5695 }
5696
5697 #[test]
5698 fn a_markdown_heading_is_the_title_not_decoration() {
5699 assert_eq!(
5704 title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5705 "Rework the config loader"
5706 );
5707 assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5708 assert_eq!(title_from("> quoted task", 40), "quoted task");
5709 assert_eq!(title_from(" \n\n", 40), "(empty task)");
5711 assert_eq!(title_from("###\n", 40), "(empty task)");
5712 }
5713
5714 #[test]
5715 fn a_long_title_is_elided_by_characters_not_bytes() {
5716 let long = "課題".repeat(30);
5718 let title = title_from(&long, 10);
5719 assert_eq!(title.chars().count(), 10);
5720 assert!(title.ends_with('…'));
5721 }
5722
5723 #[test]
5724 fn priority_wins_and_ties_break_oldest_first() {
5725 let (_dir, q) = queue();
5726 let mut a = task("first");
5727 let mut b = task("second");
5728 let mut c = task("urgent");
5729 a.id = "20260101-000001-aaaa".to_owned();
5731 b.id = "20260101-000002-bbbb".to_owned();
5732 c.id = "20260101-000003-cccc".to_owned();
5733 c.priority = 5;
5734 for t in [&mut a, &mut b, &mut c] {
5735 q.put(t).unwrap();
5736 }
5737
5738 assert_eq!(q.next_runnable().unwrap().id, c.id);
5740 c.hold_machine(None);
5741 q.put(&mut c).unwrap();
5742 assert_eq!(q.next_runnable().unwrap().id, a.id);
5744 assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5745 }
5746
5747 #[test]
5748 fn a_blocked_task_never_starves_another_runnable_one() {
5749 let (_dir, q) = queue();
5750 let mut blocked = task("blocked");
5751 blocked.block(vec!["something".to_owned()], None);
5752 q.put(&mut blocked).unwrap();
5753
5754 let mut runnable = task("free to go");
5755 q.put(&mut runnable).unwrap();
5756
5757 let next = q.next_runnable().expect("a runnable task is still offered");
5758 assert_eq!(next.id, runnable.id);
5759 }
5760
5761 #[test]
5762 fn a_held_task_is_never_offered_to_the_loop() {
5763 let (_dir, q) = queue();
5764 let mut t = task("held");
5765 q.put(&mut t).unwrap();
5766 assert!(q.next_runnable().is_some());
5767
5768 t.hold_machine(None);
5769 q.put(&mut t).unwrap();
5770 assert!(
5771 q.next_runnable().is_none(),
5772 "a held task must wait for a human"
5773 );
5774
5775 t.status = TaskStatus::Failed;
5777 q.put(&mut t).unwrap();
5778 assert!(q.next_runnable().is_some());
5779 }
5780
5781 #[test]
5782 fn attempts_are_capped_and_then_the_task_is_held() {
5783 let mut t = task("doomed");
5784
5785 t.start("run-1".to_owned());
5786 t.fail("gate red", 2);
5787 assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5788
5789 t.start("run-2".to_owned());
5790 t.fail("gate red", 2);
5791 assert_eq!(
5792 t.status,
5793 TaskStatus::Held,
5794 "out of attempts: stop spending money on it"
5795 );
5796 assert_eq!(t.runs, ["run-1", "run-2"]);
5797 assert_eq!(t.last_error.as_deref(), Some("gate red"));
5798 assert_eq!(
5799 t.hold_reason.as_deref(),
5800 Some("gate red"),
5801 "the hold must say why, not leave hold_reason null next to a \
5802 populated last_error"
5803 );
5804 }
5805
5806 #[test]
5807 fn handing_off_a_task_records_a_hold_reason_too() {
5808 let mut t = task("left a pull request");
5809 t.start("run-1".to_owned());
5810 t.handed_off("run ended with a pull request open [run run-1]");
5811 assert_eq!(t.status, TaskStatus::Held);
5812 assert_eq!(t.hold_source, Some(HoldSource::Machine));
5813 assert_eq!(
5814 t.hold_reason.as_deref(),
5815 Some("run ended with a pull request open [run run-1]")
5816 );
5817 assert_eq!(t.hold_reason, t.last_error);
5818 }
5819
5820 #[test]
5821 fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5822 let mut t = task("stalled by quota");
5823
5824 t.start("run-1".to_owned());
5825 assert_eq!(t.attempts, 1);
5826 t.stall("judge-1, judge-2 out of quota");
5827 assert_eq!(
5828 t.attempts, 0,
5829 "a closed quota window must not spend the task's retry budget"
5830 );
5831 assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5832 assert_eq!(
5833 t.last_error.as_deref(),
5834 Some("judge-1, judge-2 out of quota")
5835 );
5836
5837 for _ in 0..20 {
5840 t.start("run-n".to_owned());
5841 t.stall("still out of quota");
5842 }
5843 t.start("run-real".to_owned());
5844 t.fail("gate red", 2);
5845 assert_eq!(
5846 t.status,
5847 TaskStatus::Failed,
5848 "the first attempt that was really judged is attempt one"
5849 );
5850 }
5851
5852 #[test]
5853 fn releasing_a_held_task_gives_it_a_real_second_chance() {
5854 let mut t = task("retry me");
5855 t.start("run-1".to_owned());
5856 t.fail("gate red", 1);
5857 assert_eq!(t.status, TaskStatus::Held);
5858
5859 t.release();
5860 assert_eq!(t.status, TaskStatus::Queued);
5861 assert_eq!(t.attempts, 0);
5864 assert!(t.last_error.is_none());
5865 assert_eq!(
5866 t.runs.len(),
5867 1,
5868 "history is kept: attempts reset, evidence does not"
5869 );
5870 }
5871
5872 #[test]
5873 fn a_hold_reason_survives_and_a_release_clears_it() {
5874 let mut t = task("waiting on something else");
5875 t.hold_manual(Some(
5876 "waiting for 20260101-000000-aaaa to land first".to_owned(),
5877 ));
5878 assert_eq!(t.status, TaskStatus::Held);
5879 assert_eq!(
5880 t.hold_reason.as_deref(),
5881 Some("waiting for 20260101-000000-aaaa to land first")
5882 );
5883
5884 t.hold_manual(None);
5886 assert_eq!(
5887 t.hold_reason.as_deref(),
5888 Some("waiting for 20260101-000000-aaaa to land first"),
5889 "a bare re-hold keeps whatever a human already wrote down"
5890 );
5891
5892 let mut plain = task("no reason given");
5894 plain.hold_manual(None);
5895 assert_eq!(plain.status, TaskStatus::Held);
5896 assert!(plain.hold_reason.is_none());
5897
5898 t.release();
5899 assert_eq!(t.status, TaskStatus::Queued);
5900 assert!(
5901 t.hold_reason.is_none(),
5902 "a stale reason must not greet the next person who holds this task"
5903 );
5904 }
5905
5906 #[test]
5907 fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5908 let mut t = task("landed by hand while held");
5913 t.hold_manual(Some("waiting on 3ed9".to_owned()));
5914 assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5915
5916 t.succeed(completion(&t));
5917 assert_eq!(t.status, TaskStatus::Done);
5918 assert!(
5919 t.hold_reason.is_none(),
5920 "a done task cannot still be waiting on something"
5921 );
5922 }
5923
5924 #[test]
5925 fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5926 let mut held = task("held straight out of blocked");
5933 held.block(
5934 vec!["20260101-000000-dead".to_owned()],
5935 Some("waiting on the migration script".to_owned()),
5936 );
5937 assert_eq!(held.status, TaskStatus::Blocked);
5938
5939 held.hold_manual(None);
5940 assert_eq!(held.status, TaskStatus::Held);
5941 assert!(
5942 held.blocked_by.is_empty(),
5943 "hold overrides the wait, same as release"
5944 );
5945 assert!(held.block_reason.is_none());
5946
5947 let mut done = task("closed straight out of blocked");
5948 done.block(
5949 vec!["20260101-000000-dead".to_owned()],
5950 Some("waiting on the migration script".to_owned()),
5951 );
5952 done.succeed(completion(&done));
5953 assert_eq!(done.status, TaskStatus::Done);
5954 assert!(
5955 done.blocked_by.is_empty(),
5956 "a done task cannot still be waiting on a dependency"
5957 );
5958 assert!(done.block_reason.is_none());
5959 }
5960
5961 #[test]
5962 fn a_blocked_task_is_never_offered_to_the_loop() {
5963 let mut t = task("blocked");
5964 assert!(t.status.runnable());
5965 t.block(
5966 vec!["dep-id".to_owned()],
5967 Some("waits on dep-id".to_owned()),
5968 );
5969 assert_eq!(t.status, TaskStatus::Blocked);
5970 assert!(!t.status.runnable());
5971 assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5972 }
5973
5974 #[test]
5975 fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5976 let mut t = task("blocked on two");
5977 t.block(
5978 vec!["a".to_owned(), "b".to_owned()],
5979 Some("waits on a and b".to_owned()),
5980 );
5981
5982 t.unblock("a");
5983 assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5984 assert_eq!(t.blocked_by, ["b"]);
5985
5986 t.unblock("b");
5987 assert_eq!(t.status, TaskStatus::Queued);
5988 assert!(t.blocked_by.is_empty());
5989 assert!(t.block_reason.is_none());
5990 }
5991
5992 #[test]
5993 fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5994 let mut t = task("never blocked");
5995 t.unblock("whatever");
5996 assert_eq!(t.status, TaskStatus::Queued);
5997 }
5998
5999 #[test]
6000 fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
6001 let mut t = task("held, then asked about");
6006 t.hold_machine(Some("out of attempts".to_owned()));
6007 assert_eq!(t.status, TaskStatus::Held);
6008
6009 t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
6010 assert_eq!(t.status, TaskStatus::Blocked);
6011
6012 t.record_answer("what now?".to_owned(), "leave it held".to_owned());
6013 t.unblock("q1");
6014 assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
6015 assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
6016 assert_eq!(t.hold_source, Some(HoldSource::Machine));
6017 assert!(t.blocked_from.is_none(), "consumed once restored");
6018 }
6019
6020 #[test]
6021 fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
6022 let mut t = task("manually held, then asked about");
6023 t.hold_manual(Some("waiting on a dependency".to_owned()));
6024
6025 t.block(vec!["q1".to_owned()], None);
6026 t.unblock("q1");
6027
6028 assert_eq!(t.status, TaskStatus::Held);
6029 assert_eq!(t.hold_source, Some(HoldSource::Manual));
6030 }
6031
6032 #[test]
6033 fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
6034 let mut t = task("held, blocked twice");
6038 t.hold_machine(None);
6039 t.block(vec!["q1".to_owned()], Some("first".to_owned()));
6040 t.block(
6041 vec!["q1".to_owned(), "q2".to_owned()],
6042 Some("second".to_owned()),
6043 );
6044
6045 t.unblock("q1");
6046 assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
6047 t.unblock("q2");
6048 assert_eq!(t.status, TaskStatus::Held);
6049 }
6050
6051 #[test]
6052 fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
6053 let mut t = task("blocked mid-run");
6057 t.start("run-1".to_owned());
6058 assert_eq!(t.status, TaskStatus::Running);
6059
6060 t.block(vec!["q1".to_owned()], None);
6061 t.unblock("q1");
6062 assert_eq!(t.status, TaskStatus::Queued);
6063 }
6064
6065 #[test]
6066 fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
6067 let mut t = task("legacy record, held before it was blocked");
6073 t.hold_source = Some(HoldSource::Machine);
6074 t.hold_reason = Some("legacy hold reason".to_owned());
6075 t.status = TaskStatus::Blocked;
6076 t.blocked_by = vec!["q1".to_owned()];
6077 t.blocked_from = None;
6078
6079 t.unblock("q1");
6080 assert_eq!(t.status, TaskStatus::Held);
6081 }
6082
6083 #[test]
6084 fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
6085 let mut t = task("legacy record, ordinary dependency block");
6086 t.status = TaskStatus::Blocked;
6087 t.blocked_by = vec!["dep".to_owned()];
6088 t.blocked_from = None;
6089
6090 t.unblock("dep");
6091 assert_eq!(t.status, TaskStatus::Queued);
6092 }
6093
6094 #[test]
6095 fn answering_a_question_is_recorded_and_survives_a_release() {
6096 let mut t = task("asked something");
6097 t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
6098 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6099 t.unblock("q1");
6100 assert_eq!(t.status, TaskStatus::Queued);
6101 assert_eq!(t.answers.len(), 1);
6102 assert_eq!(t.answers[0].answer, "SQLite");
6103
6104 t.release();
6108 assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
6109 }
6110
6111 #[test]
6112 fn resumption_review_branch_requires_unchanged_authored_criteria() {
6113 for source in ["cli", "web"] {
6114 let mut t = task("review old candidate");
6115 t.request_review("candidate-A".into());
6116 t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
6117 let mut unchanged = t.clone();
6118 unchanged.release_operator(source, None);
6119 assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
6120 t.edit(
6121 "review approved head".into(),
6122 "Reuse measured PR head B; fix Clippy; review".into(),
6123 )
6124 .unwrap();
6125 t.release_operator(source, None);
6126 assert!(t.review_branch.is_none());
6127 assert!(t.review_instruction.is_none());
6128 let mut legacy = unchanged;
6130 legacy.review_instruction = None;
6131 legacy.hold_for_handover(None, "still checked out".into());
6132 legacy
6133 .edit("new plan".into(), "Reuse measured PR head B".into())
6134 .unwrap();
6135 legacy.release_operator(source, None);
6136 assert!(legacy.review_branch.is_none());
6137 }
6138 }
6139
6140 #[test]
6141 fn a_refused_handover_keeps_the_review_branch_across_release() {
6142 let mut t = task("refused takeover");
6143 t.start("run-1".to_owned());
6144 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
6145 assert_eq!(t.status, TaskStatus::Held);
6146 assert_eq!(t.attempts, 1);
6147 t.release();
6148 assert_eq!(t.status, TaskStatus::Queued);
6149 assert_eq!(t.attempts, 0);
6150 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6151
6152 t.hold_for_handover(None, "again".to_owned());
6154 t.requeue();
6155 assert!(t.review_branch.is_none());
6156
6157 let mut m = task("manual");
6159 m.review_branch = Some("magi/x/A".to_owned());
6160 m.hold_manual(None);
6161 m.release();
6162 assert!(m.review_branch.is_none());
6163 }
6164
6165 #[test]
6166 fn requesting_review_requeues_the_task_and_remembers_the_branch() {
6167 let mut t = task("blocked run with a surviving branch");
6168 t.start("run-1".to_owned());
6169 t.fail("blocked with major findings", 5);
6170 assert_eq!(t.status, TaskStatus::Failed);
6171
6172 t.request_review("magi/eba2/A".to_owned());
6173 assert_eq!(t.status, TaskStatus::Queued);
6174 assert_eq!(t.attempts, 0);
6175 assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6176
6177 t.release();
6179 assert!(t.review_branch.is_none());
6180 }
6181
6182 #[test]
6183 fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
6184 let mut t = task("retry");
6185 t.start("run-1".to_owned());
6186 t.requeue();
6187 assert!(t.fresh_start);
6188
6189 t.release();
6190 assert!(!t.fresh_start);
6191 }
6192
6193 #[test]
6194 fn urgent_only_changes_queued_or_held_and_preserves_settings() {
6195 for status in [
6196 TaskStatus::Queued,
6197 TaskStatus::Held,
6198 TaskStatus::Running,
6199 TaskStatus::Done,
6200 TaskStatus::Failed,
6201 TaskStatus::Blocked,
6202 TaskStatus::Parked,
6203 ] {
6204 let mut t = task("urgent settings");
6205 t.status = status;
6206 t.attempts = 2;
6207 t.hold_reason = Some("waiting".into());
6208 t.priority = 7;
6209 t.interrupt = true;
6210 let before = serde_json::to_value(&t).unwrap();
6211 for urgent in [true, true, false, false] {
6212 let result = t.set_urgent(urgent);
6213 let mut expected = before.clone();
6214 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6215 result.unwrap();
6216 expected["urgent"] = urgent.into();
6217 } else {
6218 let error = result.unwrap_err().to_string();
6219 assert!(error.contains(status.as_str()), "{error}");
6220 assert!(error.contains("queued or held"), "{error}");
6221 }
6222 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6223 }
6224 }
6225 }
6226
6227 #[test]
6228 fn immediate_only_changes_queued_or_held_and_preserves_settings() {
6229 for status in [
6230 TaskStatus::Queued,
6231 TaskStatus::Held,
6232 TaskStatus::Running,
6233 TaskStatus::Done,
6234 TaskStatus::Failed,
6235 TaskStatus::Blocked,
6236 TaskStatus::Parked,
6237 ] {
6238 let mut t = task("immediate settings");
6239 t.status = status;
6240 t.attempts = 2;
6241 t.hold_reason = Some("waiting".into());
6242 t.priority = 7;
6243 t.interrupt = true;
6244 t.urgent = true;
6245 let before = serde_json::to_value(&t).unwrap();
6246 for immediate in [true, true, false, false] {
6247 let result = t.set_immediate(immediate);
6248 let mut expected = before.clone();
6249 if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6250 result.unwrap();
6251 expected["immediate"] = immediate.into();
6252 } else {
6253 let error = result.unwrap_err().to_string();
6254 assert!(error.contains(status.as_str()), "{error}");
6255 assert!(error.contains("queued or held"), "{error}");
6256 }
6257 assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6258 assert!(t.urgent, "changing immediate must preserve saved urgent");
6259 }
6260 }
6261 }
6262
6263 #[test]
6264 fn a_task_recorded_without_an_immediate_field_still_reads_as_not_immediate() {
6265 let (_dir, q) = queue();
6266 let path = q.path_of("20260101-000000-imm0");
6267 std::fs::create_dir_all(q.root()).unwrap();
6268 std::fs::write(
6269 &path,
6270 serde_json::json!({
6271 "schema": SCHEMA,
6272 "id": "20260101-000000-imm0",
6273 "title": "from before immediate existed",
6274 "instruction": "from before immediate existed",
6275 "repo": ".",
6276 "source": { "kind": "human" },
6277 "status": "queued",
6278 "urgent": true,
6279 "created_at": Timestamp::now().to_string(),
6280 "updated_at": Timestamp::now().to_string(),
6281 })
6282 .to_string(),
6283 )
6284 .unwrap();
6285
6286 let task = q.get("20260101-000000-imm0").expect("must still read");
6287 assert!(!task.immediate);
6288 assert!(task.urgent);
6289 }
6290
6291 #[test]
6292 fn immediate_reuses_urgent_isolation_and_explicit_cache_wins() {
6293 let mut cfg = crate::config::Config::default();
6294 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test".into()];
6295 let mut t = task("immediate cache");
6296
6297 t.set_immediate(true).unwrap();
6298 assert_eq!(
6299 t.build_cache_override(&cfg),
6300 Some((BuildCache::Isolated, "immediate"))
6301 );
6302
6303 t.set_urgent(true).unwrap();
6305 assert_eq!(
6306 t.build_cache_override(&cfg),
6307 Some((BuildCache::Isolated, "immediate"))
6308 );
6309
6310 t.change_build_cache(Some(BuildCache::Shared)).unwrap();
6312 assert_eq!(
6313 t.build_cache_override(&cfg),
6314 Some((BuildCache::Shared, "task-override"))
6315 );
6316
6317 t.change_build_cache(None).unwrap();
6319 assert_eq!(
6320 t.build_cache_override(&cfg),
6321 Some((BuildCache::Isolated, "immediate"))
6322 );
6323 t.set_immediate(false).unwrap();
6324 assert_eq!(
6325 t.build_cache_override(&cfg),
6326 Some((BuildCache::Isolated, "urgent"))
6327 );
6328
6329 t.set_immediate(true).unwrap();
6331 cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log".into()];
6332 assert_eq!(t.build_cache_override(&cfg), None);
6333 }
6334
6335 #[test]
6336 fn priority_can_be_changed_while_queued_but_not_while_running() {
6337 let mut t = task("reprioritise me");
6338 t.set_priority(5).unwrap();
6339 assert_eq!(t.priority, 5);
6340
6341 t.start("run-1".to_owned());
6342 let err = t.set_priority(9).unwrap_err().to_string();
6343 assert!(err.contains("running"), "{err}");
6344 assert_eq!(t.priority, 5, "the rejected write must not partially apply");
6345 }
6346
6347 #[test]
6348 fn interrupt_can_be_marked_while_queued_but_not_while_running() {
6349 let mut t = task("interrupt me");
6350 assert!(!t.interrupt, "off unless asked, same as any other task");
6351
6352 t.set_interrupt(true).unwrap();
6353 assert!(t.interrupt);
6354
6355 t.start("run-1".to_owned());
6356 assert!(
6357 !t.interrupt,
6358 "the mark is one-shot: dispatching the task fulfils it, \
6359 whatever the run that follows ends up doing"
6360 );
6361 let err = t.set_interrupt(true).unwrap_err().to_string();
6362 assert!(err.contains("running"), "{err}");
6363 t.set_interrupt(false).unwrap();
6366 assert!(!t.interrupt);
6367 }
6368
6369 #[test]
6373 fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
6374 let mut t = task("interrupt me");
6375 t.set_interrupt(true).unwrap();
6376 t.start("run-1".to_owned());
6377 t.fail("mock failure", 5);
6378 assert_eq!(t.status, TaskStatus::Failed);
6379 assert!(
6380 !t.interrupt,
6381 "one attempt already spent the mark; a retry is an ordinary \
6382 requeue, not a fresh interrupt request"
6383 );
6384 }
6385
6386 #[test]
6387 fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
6388 let (_dir, q) = queue();
6389 let mut a = task("first filed");
6390 let mut b = task("second filed");
6391 a.id = "20260101-000001-aaaa".to_owned();
6392 b.id = "20260101-000002-bbbb".to_owned();
6393 q.put(&mut a).unwrap();
6394 q.put(&mut b).unwrap();
6395
6396 assert_eq!(
6397 q.next_runnable().unwrap().id,
6398 a.id,
6399 "with equal priority the older task goes first, so a burst of \
6400 new work cannot starve it"
6401 );
6402 assert_eq!(
6403 q.list()[0].id,
6404 b.id,
6405 "but the list an operator reads is newest first, the same as \
6406 before priority existed - a's turn to run does not make it the \
6407 newest task"
6408 );
6409
6410 let mut a = q.get(&a.id).unwrap();
6411 a.set_priority(10).unwrap();
6412 q.put(&mut a).unwrap();
6413
6414 assert_eq!(
6415 q.next_runnable().unwrap().id,
6416 a.id,
6417 "a raised priority must be reflected the moment it is saved"
6418 );
6419 assert_eq!(
6423 q.list()[0].id,
6424 a.id,
6425 "the raised task must sort first in the list an operator reads, \
6426 not only in next_runnable's own ordering"
6427 );
6428 }
6429
6430 #[test]
6431 fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
6432 let mut t = Task::new(
6433 "old title".to_owned(),
6434 "old instruction".to_owned(),
6435 PathBuf::from("/repo"),
6436 Source::Agent {
6437 run: "20260101-000000-beef".to_owned(),
6438 node: "implement".to_owned(),
6439 },
6440 );
6441 let id = t.id.clone();
6442 let created_at = t.created_at;
6443 t.runs.push("20260101-000000-beef".to_owned());
6444
6445 t.edit("new title".to_owned(), "new instruction".to_owned())
6446 .unwrap();
6447
6448 assert_eq!(t.title, "new title");
6449 assert_eq!(t.instruction, "new instruction");
6450 assert_eq!(t.id, id, "editing must not mint a new id");
6451 assert_eq!(t.created_at, created_at);
6452 assert_eq!(
6453 t.source,
6454 Source::Agent {
6455 run: "20260101-000000-beef".to_owned(),
6456 node: "implement".to_owned(),
6457 },
6458 "editing must not turn agent attribution into human"
6459 );
6460 assert_eq!(t.runs, ["20260101-000000-beef"]);
6461 }
6462
6463 #[test]
6464 fn editing_is_refused_once_a_task_is_running_or_finished() {
6465 let mut running = task("in flight");
6466 running.start("run-1".to_owned());
6467 let err = running
6468 .edit("x".to_owned(), "y".to_owned())
6469 .unwrap_err()
6470 .to_string();
6471 assert!(err.contains("running"), "{err}");
6472
6473 let mut done = task("finished");
6474 done.succeed(completion(&done));
6475 let err = done
6476 .edit("x".to_owned(), "y".to_owned())
6477 .unwrap_err()
6478 .to_string();
6479 assert!(err.contains("done"), "{err}");
6480
6481 let mut queued = task("waiting");
6483 queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6484 let mut held = task("parked");
6485 held.hold_machine(None);
6486 held.edit("x".to_owned(), "y".to_owned()).unwrap();
6487 }
6488
6489 #[test]
6490 fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6491 let (_dir, q) = queue();
6492 let path = q.path_of("20260101-000000-aaaa");
6493 std::fs::create_dir_all(q.root()).unwrap();
6494 std::fs::write(
6495 &path,
6496 serde_json::json!({
6497 "schema": SCHEMA,
6498 "id": "20260101-000000-aaaa",
6499 "title": "from before hold reasons existed",
6500 "instruction": "from before hold reasons existed",
6501 "repo": ".",
6502 "source": { "kind": "human" },
6503 "status": "held",
6504 "created_at": Timestamp::now().to_string(),
6505 "updated_at": Timestamp::now().to_string(),
6506 })
6507 .to_string(),
6508 )
6509 .unwrap();
6510
6511 let task = q.get("20260101-000000-aaaa").expect("must still read");
6512 assert!(task.hold_reason.is_none());
6513 assert!(task.operator_held());
6514 }
6515
6516 #[test]
6517 fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6518 let (_dir, q) = queue();
6519 let path = q.path_of("20260101-000000-bbbb");
6520 std::fs::create_dir_all(q.root()).unwrap();
6521 std::fs::write(
6522 &path,
6523 serde_json::json!({
6524 "schema": 2,
6525 "id": "20260101-000000-bbbb",
6526 "title": "old manual recovery",
6527 "instruction": "old manual recovery",
6528 "repo": ".",
6529 "source": { "kind": "human" },
6530 "status": "held",
6531 "hold_reason": "active manual recovery run20260912-224242-daf5",
6532 "created_at": Timestamp::now().to_string(),
6533 "updated_at": Timestamp::now().to_string(),
6534 })
6535 .to_string(),
6536 )
6537 .unwrap();
6538
6539 let task = q.get("20260101-000000-bbbb").expect("must still read");
6540 assert_eq!(task.hold_source, None);
6541 assert!(task.operator_held());
6542 }
6543
6544 #[test]
6545 fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6546 let (_dir, q) = queue();
6547 let path = q.path_of("20260101-000000-aaaa");
6548 std::fs::create_dir_all(q.root()).unwrap();
6549 std::fs::write(
6550 &path,
6551 serde_json::json!({
6552 "schema": SCHEMA,
6553 "id": "20260101-000000-aaaa",
6554 "title": "from before diagnostics existed",
6555 "instruction": "from before diagnostics existed",
6556 "repo": ".",
6557 "source": { "kind": "human" },
6558 "status": "held",
6559 "created_at": Timestamp::now().to_string(),
6560 "updated_at": Timestamp::now().to_string(),
6561 })
6562 .to_string(),
6563 )
6564 .unwrap();
6565
6566 let task = q.get("20260101-000000-aaaa").expect("must still read");
6567 assert!(task.diagnostic.is_none());
6568 }
6569
6570 #[test]
6571 fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6572 let (_dir, q) = queue();
6576 let path = q.path_of("20260101-000000-aaaa");
6577 std::fs::create_dir_all(q.root()).unwrap();
6578 std::fs::write(
6579 &path,
6580 serde_json::json!({
6581 "schema": 1,
6582 "id": "20260101-000000-aaaa",
6583 "title": "from before blocking existed",
6584 "instruction": "from before blocking existed",
6585 "repo": ".",
6586 "source": { "kind": "human" },
6587 "status": "queued",
6588 "created_at": Timestamp::now().to_string(),
6589 "updated_at": Timestamp::now().to_string(),
6590 })
6591 .to_string(),
6592 )
6593 .unwrap();
6594
6595 let task = q.get("20260101-000000-aaaa").expect("must still read");
6596 assert!(task.blocked_by.is_empty());
6597 assert!(task.block_reason.is_none());
6598 assert!(task.answers.is_empty());
6599 assert!(task.review_branch.is_none());
6600 }
6601
6602 #[test]
6603 fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6604 let mut held = task("diagnosed");
6609 held.start("run-1".to_owned());
6610 held.fail("gate red", 1);
6611 held.diagnostic = Some("cargo test failed: ...".to_owned());
6612 assert_eq!(held.status, TaskStatus::Held);
6613
6614 held.release();
6615 assert!(held.diagnostic.is_none());
6616
6617 held.diagnostic = Some("cargo test failed: ...".to_owned());
6618 held.succeed(completion(&held));
6619 assert!(held.diagnostic.is_none());
6620 }
6621
6622 #[test]
6623 fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6624 let mut t = task("retried");
6625 t.start("run-1".to_owned());
6626 t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6627 t.fail("unrelated config error", 5);
6628 assert_eq!(t.status, TaskStatus::Failed);
6629 assert!(
6630 t.diagnostic.is_none(),
6631 "fail() must not let an old diagnostic outlive the run that produced it"
6632 );
6633 }
6634
6635 #[test]
6636 fn a_claim_is_exclusive_and_releases_on_drop() {
6637 let (_dir, q) = queue();
6638 let mut t = task("contended");
6639 q.put(&mut t).unwrap();
6640
6641 let held = q.claim(&t.id).unwrap();
6642 assert!(
6643 q.claim(&t.id).is_err(),
6644 "two daemons must not drive one task into two runs"
6645 );
6646 drop(held);
6647 assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6648 }
6649
6650 #[test]
6651 fn a_round_trip_survives_disk() {
6652 let (_dir, q) = queue();
6653 let mut t = Task::new(
6654 "titled".to_owned(),
6655 "body".to_owned(),
6656 PathBuf::from("/repo"),
6657 Source::Agent {
6658 run: "20260101-000000-beef".to_owned(),
6659 node: "implement".to_owned(),
6660 },
6661 );
6662 t.priority = 3;
6663 q.put(&mut t).unwrap();
6664
6665 let back = q.get(&t.id).unwrap();
6666 assert_eq!(back.id, t.id);
6667 assert_eq!(back.priority, 3);
6668 assert_eq!(back.source.label(), "implement@beef");
6669 assert_eq!(q.get(t.short()).unwrap().id, t.id);
6671 }
6672
6673 #[test]
6674 fn an_unreadable_task_does_not_take_the_queue_down() {
6675 let (_dir, q) = queue();
6676 let mut t = task("fine");
6677 q.put(&mut t).unwrap();
6678 std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6679
6680 let listed = q.list();
6681 assert_eq!(listed.len(), 1, "the readable task still lists");
6682 assert_eq!(listed[0].id, t.id);
6683 }
6684
6685 #[test]
6686 fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6687 let (_dir, q) = queue();
6688 let path = q.path_of("20260101-000000-aaaa");
6689 std::fs::create_dir_all(q.root()).unwrap();
6690 std::fs::write(
6691 &path,
6692 serde_json::json!({
6693 "schema": SCHEMA,
6694 "id": "20260101-000000-aaaa",
6695 "title": "from before solo existed",
6696 "instruction": "from before solo existed",
6697 "repo": ".",
6698 "source": { "kind": "human" },
6699 "status": "queued",
6700 "created_at": Timestamp::now().to_string(),
6701 "updated_at": Timestamp::now().to_string(),
6702 })
6703 .to_string(),
6704 )
6705 .unwrap();
6706
6707 let task = q.get("20260101-000000-aaaa").expect("must still read");
6708 assert!(!task.solo, "a queue file with no `solo` field means false");
6709 }
6710
6711 #[test]
6712 fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6713 let (_dir, q) = queue();
6714 let path = q.path_of("20260101-000000-bbbb");
6715 std::fs::create_dir_all(q.root()).unwrap();
6716 std::fs::write(
6717 &path,
6718 serde_json::json!({
6719 "schema": SCHEMA,
6720 "id": "20260101-000000-bbbb",
6721 "title": "from before urgent existed",
6722 "instruction": "from before urgent existed",
6723 "repo": ".",
6724 "source": { "kind": "human" },
6725 "status": "queued",
6726 "created_at": Timestamp::now().to_string(),
6727 "updated_at": Timestamp::now().to_string(),
6728 })
6729 .to_string(),
6730 )
6731 .unwrap();
6732
6733 let task = q.get("20260101-000000-bbbb").expect("must still read");
6734 assert!(
6735 !task.urgent,
6736 "a queue file with no `urgent` field means false, same as `solo`"
6737 );
6738 }
6739
6740 #[test]
6741 fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6742 let (_dir, q) = queue();
6743 let mut t = task("from the future");
6744 q.put(&mut t).unwrap();
6745 let path = q.path_of(&t.id);
6746 let body = std::fs::read_to_string(&path)
6747 .unwrap()
6748 .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6749 std::fs::write(&path, body).unwrap();
6750
6751 let err = q.get(&t.id).unwrap_err().to_string();
6752 assert!(err.contains("schema 99"), "{err}");
6753 }
6754
6755 #[test]
6756 fn revision_moves_when_the_queue_changes() {
6757 let (_dir, q) = queue();
6758 assert_eq!(q.revision(), 0, "an empty queue has no revision");
6759 let mut t = task("first");
6760 q.put(&mut t).unwrap();
6761 assert!(q.revision() > 0, "a written task moves the revision");
6762 }
6763
6764 #[test]
6765 fn revision_moves_when_deleting_an_older_task() {
6766 let (dir, q) = queue();
6767 let questions = Questions::at(dir.path().join("questions"));
6768 let mut t1 = task("older");
6769 q.put(&mut t1).unwrap();
6770 std::thread::sleep(std::time::Duration::from_millis(10));
6772 let mut t2 = task("newer");
6773 q.put(&mut t2).unwrap();
6774
6775 let rev_before = q.revision();
6776 q.remove(&t1.id, false, &questions).unwrap();
6777 let rev_after = q.revision();
6778
6779 assert_ne!(
6780 rev_before, rev_after,
6781 "deleting an older task must change the revision so other clients see the deletion"
6782 );
6783 }
6784
6785 #[test]
6786 fn removing_a_task_takes_it_out_of_the_listing() {
6787 let (dir, q) = queue();
6788 let questions = Questions::at(dir.path().join("questions"));
6789 let mut t = task("delete me");
6790 q.put(&mut t).unwrap();
6791 let removed = q.remove(t.short(), false, &questions).unwrap();
6792 assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6793 assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6794 assert!(q.list().is_empty());
6795 assert!(
6796 q.remove(&t.id, false, &questions).is_err(),
6797 "removing twice is an error"
6798 );
6799 }
6800
6801 #[test]
6802 fn removing_a_task_takes_its_stale_lock_with_it() {
6803 let (dir, q) = queue();
6804 let questions = Questions::at(dir.path().join("questions"));
6805 let mut t = task("interrupted");
6806 q.put(&mut t).unwrap();
6807
6808 let claim = q.claim(&t.id).unwrap();
6811 std::mem::forget(claim);
6812 assert!(
6813 q.claim(&t.id).is_err(),
6814 "the orphaned lock is what makes the task look claimed"
6815 );
6816
6817 let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6819 assert!(err.contains("live daemon"), "{err}");
6820 assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6821
6822 q.remove(&t.id, false, &questions).unwrap();
6824 assert!(q.list().is_empty());
6825 let mut again = task("interrupted");
6826 again.id = t.id.clone();
6827 q.put(&mut again).unwrap();
6828 assert!(
6829 q.claim(&t.id).is_ok(),
6830 "a task that comes back must be claimable, which a left-behind lock would prevent"
6831 );
6832 }
6833
6834 fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6835 crate::notices::Notices::at(dir.join("notifications")).list()
6836 }
6837
6838 #[test]
6839 fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6840 let (dir, q) = queue();
6841 let questions = Questions::at(dir.path().join("questions"));
6842 let mut dep = task("dependency");
6843 q.put(&mut dep).unwrap();
6844 let mut blocked = task("waiting");
6845 blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6846 q.put(&mut blocked).unwrap();
6847
6848 let removed = q.remove(&dep.id, false, &questions).unwrap();
6849 assert_eq!(removed.released, [blocked.id.clone()]);
6850 assert!(removed.still_blocked.is_empty());
6851
6852 let after = q.get(&blocked.id).unwrap();
6853 assert_eq!(after.status, TaskStatus::Queued);
6854 assert!(after.blocked_by.is_empty());
6855 assert!(after.block_reason.is_none());
6856 let notes = notices_of(dir.path());
6857 assert_eq!(notes.len(), 1, "{notes:?}");
6858 assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6859 assert_eq!(
6860 notes[0].link,
6861 Some(crate::notices::Link::Task {
6862 id: blocked.id.clone(),
6863 })
6864 );
6865 }
6866
6867 #[test]
6868 fn removing_one_of_two_dependencies_keeps_the_other() {
6869 let (dir, q) = queue();
6870 let questions = Questions::at(dir.path().join("questions"));
6871 let mut dep = task("dependency");
6872 q.put(&mut dep).unwrap();
6873 let mut other = task("other");
6874 q.put(&mut other).unwrap();
6875 let mut blocked = task("waiting");
6876 blocked.block(
6877 vec![dep.id.clone(), other.id.clone()],
6878 Some("waits on both".to_owned()),
6879 );
6880 q.put(&mut blocked).unwrap();
6881
6882 let removed = q.remove(&dep.id, false, &questions).unwrap();
6883 assert!(removed.released.is_empty());
6884 assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6885
6886 let after = q.get(&blocked.id).unwrap();
6887 assert_eq!(after.status, TaskStatus::Blocked);
6888 assert_eq!(after.blocked_by, [other.id.clone()]);
6889 assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6892 }
6893
6894 #[test]
6895 fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6896 let (dir, q) = queue();
6897 let questions = Questions::at(dir.path().join("questions"));
6898 let mut dep = task("dependency");
6899 q.put(&mut dep).unwrap();
6900 let mut blocked = task("waiting");
6901 blocked.block(vec![dep.id.clone()], None);
6902 q.put(&mut blocked).unwrap();
6903
6904 let claim = q.claim(&blocked.id).unwrap();
6906 let removed = q.remove(&dep.id, false, &questions).unwrap();
6907 assert!(removed.released.is_empty());
6908 drop(claim);
6909
6910 let mut task = q.get(&blocked.id).unwrap();
6911 assert_eq!(task.status, TaskStatus::Blocked);
6912 assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6913 assert_eq!(
6914 q.apply_deleted_blockers(&mut task, &questions),
6915 [dep.id.clone()]
6916 );
6917 assert_eq!(task.status, TaskStatus::Queued);
6918 }
6919
6920 #[test]
6921 fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6922 let (dir, q) = queue();
6923 let questions = Questions::at(dir.path().join("questions"));
6924 let mut dep = task("dependency");
6925 dep.id = "20261013-193611-ca5b".into();
6926 q.put(&mut dep).unwrap();
6927 let mut waiting = task("waiting");
6928 waiting.block(vec!["ca5b".into()], None);
6929 q.put(&mut waiting).unwrap();
6930 q.remove(&dep.id, false, &questions).unwrap();
6931 assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6932 assert_eq!(
6933 dependency(&q, &questions, "ca5b"),
6934 Dependency::Deleted(dep.id)
6935 );
6936 }
6937
6938 #[test]
6939 fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6940 let (dir, queue) = queue();
6941 let questions = Questions::at(dir.path().join("questions"));
6942 let mut dep = task("dependency");
6943 dep.id = "20261013-193611-ca5b".into();
6944 queue.put(&mut dep).unwrap();
6945 std::fs::create_dir_all(questions.root()).unwrap();
6946 let question_id = "20261014-193611-ca5b";
6947 std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6948 assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6949 assert_eq!(
6950 dependency(&queue, &questions, "ca5b"),
6951 Dependency::Ambiguous
6952 );
6953 assert_eq!(
6954 dependency(&queue, &questions, &dep.id),
6955 Dependency::Task(dep.id)
6956 );
6957 assert_eq!(
6958 dependency(&queue, &questions, question_id),
6959 Dependency::Question(question_id.into())
6960 );
6961 assert_eq!(
6962 dependency(&queue, &questions, "missing"),
6963 Dependency::Missing
6964 );
6965 }
6966
6967 #[test]
6968 fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6969 let dir = tempfile::tempdir().unwrap();
6970 let q = Queue::at(dir.path().join("not-a-directory"));
6971 std::fs::write(q.root(), "file").unwrap();
6972 let questions = Questions::at(dir.path().join("questions"));
6973 assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6974 assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6975 }
6976
6977 #[test]
6978 fn a_dependency_without_a_tombstone_is_still_missing() {
6979 let (dir, q) = queue();
6980 let questions = Questions::at(dir.path().join("questions"));
6981 let mut dep = task("dependency");
6982 q.put(&mut dep).unwrap();
6983 std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6984 assert_eq!(
6985 missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6986 [dep.id.clone()]
6987 );
6988 assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6989 }
6990
6991 #[test]
6992 fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6993 let mut t = task("held");
6994 t.hold_machine(Some("because".to_owned()));
6995 t.blocked_by = vec!["gone".to_owned()];
6996 assert!(!t.dependency_deleted("gone"));
6997 assert_eq!(t.status, TaskStatus::Held);
6998 }
6999
7000 #[test]
7001 fn a_failed_record_removal_takes_the_tombstone_back() {
7002 let (_dir, q) = queue();
7003 let mut t = task("stays");
7004 q.put(&mut t).unwrap();
7005 q.write_tombstone(&t.id).unwrap();
7006 let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
7007 assert!(err.is_err());
7008 assert!(!q.was_deleted(&t.id));
7011 }
7012
7013 fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
7014 let p = dir.join(name);
7015 std::fs::write(&p, body).unwrap();
7016 p
7017 }
7018
7019 #[test]
7020 fn an_attachment_copy_survives_deleting_its_source() {
7021 let (dir, q) = queue();
7022 let src = source_file(dir.path(), "shot.png", "pixels");
7023 let mut t = task("with a picture");
7024 let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
7025 q.put(&mut t).unwrap();
7026 std::fs::remove_file(&src).unwrap();
7027 assert_eq!(names, ["shot.png"]);
7028 let loaded = q.get(&t.id).unwrap();
7029 let paths = q.attachment_paths(&loaded);
7030 assert_eq!(paths.len(), 1);
7031 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
7032 }
7033
7034 #[test]
7035 fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
7036 let (dir, q) = queue();
7037 let mut t = task("bad names");
7038 for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
7039 let src = source_file(dir.path(), name, "x");
7040 assert!(
7041 q.attach(&mut t, &[src]).is_err(),
7042 "`{name}` must be refused"
7043 );
7044 }
7045 assert!(!crate::ask::valid_asset_name("C:foo.png"));
7049 #[cfg(not(windows))]
7050 {
7051 let src = source_file(dir.path(), "C:foo.png", "x");
7052 assert!(q.attach(&mut t, &[src]).is_err());
7053 }
7054 let long = format!("{}.png", "a".repeat(70));
7055 let src = source_file(dir.path(), &long, "x");
7056 assert!(q.attach(&mut t, &[src]).is_err());
7057 assert!(t.attachments.is_empty());
7058 assert!(!q.attachments_dir(&t.id).exists());
7059 }
7060
7061 #[test]
7062 fn a_taken_attachment_name_is_numbered_not_overwritten() {
7063 let (dir, q) = queue();
7064 let a = source_file(dir.path(), "shot.png", "one");
7065 let sub = dir.path().join("other");
7066 std::fs::create_dir_all(&sub).unwrap();
7067 let b = source_file(&sub, "shot.png", "two");
7068 let mut t = task("collision");
7069 q.attach(&mut t, &[a]).unwrap();
7070 q.attach(&mut t, &[b]).unwrap();
7071 assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
7072 let paths = q.attachment_paths(&t);
7073 assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
7074 assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
7075 }
7076
7077 #[test]
7078 fn a_renumbered_name_stays_inside_the_length_bound() {
7079 let (dir, q) = queue();
7080 let name = format!("{}.png", "a".repeat(60));
7081 assert_eq!(name.len(), 64);
7082 let a = source_file(dir.path(), &name, "one");
7083 let sub = dir.path().join("other");
7084 std::fs::create_dir_all(&sub).unwrap();
7085 let b = source_file(&sub, &name, "two");
7086 let mut t = task("long");
7087 q.attach(&mut t, &[a, b]).unwrap();
7088 assert_eq!(t.attachments.len(), 2);
7089 assert!(
7090 t.attachments
7091 .iter()
7092 .all(|n| crate::ask::valid_asset_name(n))
7093 );
7094 assert!(t.attachments[1].ends_with("-2.png"));
7095 }
7096
7097 #[test]
7098 fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
7099 let (dir, q) = queue();
7100 let good = source_file(dir.path(), "good.png", "ok");
7101 let mut t = task("partial");
7102 q.attach(&mut t, &[good]).unwrap();
7103 let more = source_file(dir.path(), "more.png", "ok");
7104 let missing = dir.path().join("missing.png");
7105 assert!(q.attach(&mut t, &[more, missing]).is_err());
7106 assert_eq!(t.attachments, ["good.png"]);
7107 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7108 .unwrap()
7109 .flatten()
7110 .collect();
7111 assert_eq!(on_disk.len(), 1);
7112 }
7113
7114 fn block_put(q: &Queue, t: &Task) -> PathBuf {
7116 let tmp = q.path_of(&t.id).with_extension("json.tmp");
7117 std::fs::create_dir_all(&tmp).unwrap();
7118 tmp
7119 }
7120
7121 #[test]
7122 fn a_failed_put_leaves_no_new_attachment_directory() {
7123 let (dir, q) = queue();
7124 let mut t = task("fresh");
7125 let tmp = block_put(&q, &t);
7126 let src = source_file(dir.path(), "shot.png", "x");
7127 assert!(q.attach_and_put(&mut t, &[src]).is_err());
7128 assert!(t.attachments.is_empty());
7129 assert!(!q.attachments_dir(&t.id).exists());
7130 assert!(!q.path_of(&t.id).exists());
7131 std::fs::remove_dir(tmp).unwrap();
7132 }
7133
7134 #[test]
7135 fn a_failed_put_removes_only_the_copy_it_just_made() {
7136 let (dir, q) = queue();
7137 let mut t = task("edited");
7138 let first = source_file(dir.path(), "first.png", "1");
7139 q.attach_and_put(&mut t, &[first]).unwrap();
7140 block_put(&q, &t);
7141 let second = source_file(dir.path(), "second.png", "2");
7142 assert!(q.attach_and_put(&mut t, &[second]).is_err());
7143 assert_eq!(t.attachments, ["first.png"]);
7144 let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7145 .unwrap()
7146 .flatten()
7147 .map(|e| e.file_name().to_string_lossy().into_owned())
7148 .collect();
7149 assert_eq!(on_disk, ["first.png"]);
7150 assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
7151 }
7152
7153 #[test]
7154 fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
7155 let (dir, q) = queue();
7156 let questions = Questions::at(dir.path().join("questions"));
7157 let gone = task("gone");
7158 let mut other = task("other");
7159 let mut live = task("live");
7160 q.put(&mut other).unwrap();
7161 q.put(&mut live).unwrap();
7162 let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
7165 std::fs::create_dir_all(&orphan).unwrap();
7166 std::fs::write(orphan.join("shot.png"), "x").unwrap();
7167 let busy = q.root.join(format!("{}.attachments.removing", live.id));
7170 std::fs::create_dir_all(&busy).unwrap();
7171
7172 q.remove(&other.id, false, &questions).unwrap();
7173 assert!(!orphan.exists(), "an orphan is swept");
7174 assert!(busy.exists(), "a removal in progress is left alone");
7175 }
7176
7177 #[test]
7178 fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
7179 let (dir, q) = queue();
7180 let questions = Questions::at(dir.path().join("questions"));
7181 let mut t = task("stuck");
7182 let src = source_file(dir.path(), "shot.png", "x");
7183 q.attach_and_put(&mut t, &[src]).unwrap();
7184 let aside = q.root.join(format!("{}.attachments.removing", t.id));
7187 std::fs::create_dir_all(&aside).unwrap();
7188 std::fs::write(aside.join("old.png"), "o").unwrap();
7189 assert!(q.remove(&t.id, false, &questions).is_err());
7190 assert!(q.path_of(&t.id).exists());
7191 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7192 }
7193
7194 #[test]
7195 fn a_failed_record_removal_puts_the_attachments_back() {
7196 let (dir, q) = queue();
7197 let mut t = task("rollback");
7198 let src = source_file(dir.path(), "shot.png", "x");
7199 q.attach_and_put(&mut t, &[src]).unwrap();
7200 let err = q
7201 .remove_record_with_attachments(&t.id, |_| {
7202 Err(std::io::Error::other("injected failure"))
7203 })
7204 .unwrap_err();
7205 assert!(format!("{err:#}").contains("injected failure"));
7206 assert!(q.path_of(&t.id).exists());
7207 assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7208 assert!(
7209 !q.root
7210 .join(format!("{}.attachments.removing", t.id))
7211 .exists()
7212 );
7213 }
7214
7215 #[test]
7216 fn editing_a_task_keeps_its_attachments() {
7217 let (dir, q) = queue();
7218 let src = source_file(dir.path(), "shot.png", "x");
7219 let mut t = task("editable");
7220 q.attach(&mut t, &[src]).unwrap();
7221 t.edit("new".to_owned(), "new text".to_owned()).unwrap();
7222 q.put(&mut t).unwrap();
7223 assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
7224 }
7225
7226 #[test]
7227 fn removing_a_task_deletes_its_attachments() {
7228 let (dir, q) = queue();
7229 let questions = Questions::at(dir.path().join("questions"));
7230 let src = source_file(dir.path(), "shot.png", "x");
7231 let mut t = task("doomed");
7232 q.attach(&mut t, &[src]).unwrap();
7233 q.put(&mut t).unwrap();
7234 assert!(q.attachments_dir(&t.id).is_dir());
7235 q.remove(&t.id, false, &questions).unwrap();
7236 assert!(!q.attachments_dir(&t.id).exists());
7237 assert!(q.list().is_empty());
7238 }
7239
7240 #[test]
7241 fn a_task_written_before_attachments_still_reads() {
7242 let (_dir, q) = queue();
7243 let mut t = task("old");
7244 q.put(&mut t).unwrap();
7245 let path = q.path_of(&t.id);
7246 let mut v: serde_json::Value =
7247 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7248 v.as_object_mut().unwrap().remove("attachments");
7249 std::fs::write(&path, v.to_string()).unwrap();
7250 assert!(q.get(&t.id).unwrap().attachments.is_empty());
7251 }
7252
7253 #[test]
7254 fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
7255 let q = Queue::at(PathBuf::from("relative-queue"));
7256 let mut t = task("rel");
7257 t.attachments.push("shot.png".to_owned());
7258 let paths = q.attachment_paths(&t);
7259 assert!(paths[0].is_absolute(), "{}", paths[0].display());
7260 assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
7261 }
7262
7263 fn upgrade_parked(id: &str, started: &str) -> Task {
7264 let mut t = task(id);
7265 t.id = id.into();
7266 t.start(format!("run-{id}"));
7267 t.park("upgrade");
7268 t.record_pass_at(
7269 &format!("run-{id}"),
7270 0,
7271 Some(started.parse().unwrap()),
7272 1,
7273 Some(crate::run::ParkCause::Upgrade {
7274 from: "old".into(),
7275 to: None,
7276 }),
7277 );
7278 t
7279 }
7280
7281 #[test]
7282 fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
7283 let stamp = |id: &str, dispatched: &str, started: &str| {
7285 let mut t = task(id);
7286 t.id = id.into();
7287 t.start(format!("run-{id}"));
7288 t.park("upgrade");
7289 t.dispatched_at = Some(dispatched.parse().unwrap());
7290 t.record_pass_at(
7291 &format!("run-{id}"),
7292 0,
7293 Some(started.parse().unwrap()),
7294 1,
7295 Some(crate::run::ParkCause::Upgrade {
7296 from: "old".into(),
7297 to: None,
7298 }),
7299 );
7300 t
7301 };
7302 let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
7303 let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
7304 assert!(dispatch_order(&a, &b).is_lt());
7305 }
7306
7307 #[test]
7308 fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
7309 let (_dir, q) = queue();
7310 let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
7311 let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
7312 earlier.priority = -10;
7313 let mut fresh = task("fresh");
7314 fresh.id = "newer".into();
7315 fresh.priority = 100;
7316 for t in [&mut fresh, &mut later, &mut earlier] {
7317 q.put(t).unwrap();
7318 }
7319 let reloaded = Queue::at(q.root().to_owned());
7320 let mut tasks = reloaded.list();
7321 tasks.sort_unstable_by(dispatch_order);
7322 assert_eq!(
7323 tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7324 vec!["earlier", "later", "newer"]
7325 );
7326 assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
7327 assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
7328 }
7329
7330 #[test]
7331 fn upgrade_resume_legacy_order_uses_settlement_and_id() {
7332 let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
7333 let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
7334 for t in [&mut a, &mut b] {
7335 let mut value = serde_json::to_value(&*t).unwrap();
7336 value["passes"][0]
7337 .as_object_mut()
7338 .unwrap()
7339 .remove("started_at");
7340 *t = serde_json::from_value(value).unwrap();
7341 }
7342 assert!(dispatch_order(&a, &b).is_lt());
7343 b.passes[0].settled_at = a.passes[0].settled_at;
7344 assert!(dispatch_order(&a, &b).is_lt());
7345 }
7346
7347 #[test]
7348 fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
7349 let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
7350 assert!(original.upgrade_resume_key().is_some());
7351 for cause in [
7352 crate::run::ParkCause::Operator,
7353 crate::run::ParkCause::Question,
7354 crate::run::ParkCause::Interrupt {
7355 reason: "interrupt".into(),
7356 },
7357 crate::run::ParkCause::Unspecified,
7358 ] {
7359 let mut t = original.clone();
7360 t.passes[0].parked = Some(cause);
7361 assert!(t.upgrade_resume_key().is_none());
7362 let mut fresh = task("fresh");
7363 fresh.priority = 1;
7364 assert!(dispatch_order(&fresh, &t).is_lt());
7365 }
7366 let mut t = original.clone();
7367 t.release();
7368 assert!(t.upgrade_resume_key().is_none());
7369 t.edit("edited".into(), "new instruction".into()).unwrap();
7370 assert!(t.upgrade_resume_key().is_none());
7371 let mut t = original.clone();
7372 t.requeue();
7373 t.status = TaskStatus::Parked;
7374 assert!(t.upgrade_resume_key().is_none());
7375 let mut t = original.clone();
7376 t.start("different-run".into());
7377 t.park("no upgrade");
7378 assert!(t.upgrade_resume_key().is_none());
7379 }
7380
7381 #[test]
7382 fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
7383 let dir = tempfile::tempdir().unwrap();
7384 let q = Queue::at(dir.path().join("queue"));
7385 let mut t = task("resume");
7386 t.start("A".into());
7387 t.record_pass("A", 0, 1, None);
7388 t.start("B".into());
7389 q.put(&mut t).unwrap();
7390 assert_eq!(t.runs, vec!["A", "B"]);
7391 t.start("A".into());
7392 t.record_pass("A", 1, 3, None);
7393 q.put(&mut t).unwrap();
7394 let saved = q.get(&t.id).unwrap();
7395 assert_eq!(saved.runs, vec!["B", "A"]);
7396 assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
7397 assert_eq!(saved.attempts, 3);
7398 assert_eq!(saved.passes.len(), 2);
7399 assert_eq!(saved.passes[0].run, "A");
7400 assert_eq!(saved.passes[1].run, "A");
7401 }
7402
7403 #[test]
7404 fn repeated_start_records_one_run_and_separate_passes() {
7405 let mut t = task("resume");
7406 t.start("same-run".into());
7407 t.record_pass("same-run", 0, 1, None);
7408 t.start("same-run".into());
7409 t.record_pass("same-run", 1, 2, None);
7410 assert_eq!(t.runs, vec!["same-run"]);
7411 assert_eq!(t.attempts, 2);
7412 assert_eq!(t.passes.len(), 2);
7413 }
7414
7415 #[test]
7416 fn link_run_adds_a_run_once_and_touches_nothing_else() {
7417 let dir = tempfile::tempdir().unwrap();
7418 let queue = Queue::at(dir.path().join("queue"));
7419 let mut t = Task::new(
7420 "t".to_owned(),
7421 "do it".to_owned(),
7422 PathBuf::from("."),
7423 Source::Human,
7424 );
7425 queue.put(&mut t).unwrap();
7426 let before = queue.get(&t.id).unwrap();
7427
7428 let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
7429 assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
7430 assert_eq!(linked.status, before.status);
7431 assert_eq!(linked.attempts, before.attempts);
7432 assert_eq!(linked.interrupt, before.interrupt);
7433
7434 let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7435 assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
7436 assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
7437 assert!(queue.link_run("no-such-task", "r").is_err());
7438 }
7439
7440 #[test]
7441 fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7442 let dir = tempfile::tempdir().unwrap();
7443 let queue = Queue::at(dir.path().join("queue"));
7444 let mut t = Task::new(
7445 "t".to_owned(),
7446 "do it".to_owned(),
7447 PathBuf::from("."),
7448 Source::Human,
7449 );
7450 queue.put(&mut t).unwrap();
7451 let mut snapshot = queue.get(&t.id).unwrap();
7453 queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7454
7455 snapshot.start("20260930-000000-aaaa".to_owned());
7456 queue.put(&mut snapshot).unwrap();
7457
7458 let stored = queue.get(&t.id).unwrap();
7459 assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7460 assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7461 assert_eq!(stored.attempts, 1);
7462 }
7463
7464 #[test]
7465 fn concurrent_links_and_daemon_saves_lose_nothing() {
7466 let dir = tempfile::tempdir().unwrap();
7467 let queue = Queue::at(dir.path().join("queue"));
7468 let mut t = Task::new(
7469 "t".to_owned(),
7470 "do it".to_owned(),
7471 PathBuf::from("."),
7472 Source::Human,
7473 );
7474 queue.put(&mut t).unwrap();
7475 let id = t.id.clone();
7476
7477 let linkers: Vec<_> = (0..4)
7478 .map(|n| {
7479 let (queue, id) = (queue.clone(), id.clone());
7480 std::thread::spawn(move || {
7481 for k in 0..10 {
7482 queue
7483 .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7484 .unwrap();
7485 }
7486 })
7487 })
7488 .collect();
7489 let mut mine = queue.get(&id).unwrap();
7492 for k in 0..10 {
7493 mine.start(format!("20260930-000009-d{k:03}"));
7494 queue.put(&mut mine).unwrap();
7495 }
7496 for l in linkers {
7497 l.join().unwrap();
7498 }
7499
7500 let stored = queue.get(&id).unwrap();
7501 assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7502 assert_eq!(
7503 stored.attempts, 10,
7504 "linking never rewinds the daemon's work"
7505 );
7506 }
7507
7508 fn age_lock(path: &Path) {
7509 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7510 f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7511 .unwrap();
7512 }
7513
7514 #[test]
7515 fn concurrent_stale_takeover_yields_one_holder() {
7516 use std::sync::atomic::{AtomicUsize, Ordering};
7517 use std::sync::{Arc, Barrier};
7518 for _ in 0..5 {
7519 let dir = tempfile::tempdir().unwrap();
7520 let q = Queue::at(dir.path().to_path_buf());
7521 let lock = dir.path().join("t.write-lock");
7522 std::fs::write(&lock, "dead-0000").unwrap();
7523 age_lock(&lock);
7524 let n = 6;
7525 let barrier = Arc::new(Barrier::new(n));
7526 let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7527 let handles: Vec<_> = (0..n)
7528 .map(|_| {
7529 let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7530 std::thread::spawn(move || {
7531 b.wait();
7532 let g = q.lock_task("t").unwrap();
7533 let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7534 max.fetch_max(held, Ordering::SeqCst);
7535 std::thread::sleep(std::time::Duration::from_millis(20));
7536 now.fetch_sub(1, Ordering::SeqCst);
7537 drop(g);
7538 })
7539 })
7540 .collect();
7541 for h in handles {
7542 h.join().unwrap();
7543 }
7544 assert_eq!(max.load(Ordering::SeqCst), 1);
7545 assert!(!lock.exists());
7546 }
7547 }
7548
7549 #[test]
7550 fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7551 let dir = tempfile::tempdir().unwrap();
7552 let q = Queue::at(dir.path().to_path_buf());
7553 let lock = dir.path().join("t.write-lock");
7554 let a = q.lock_task("t").unwrap();
7555 let replacement = owner_token();
7558 std::fs::write(&lock, &replacement).unwrap();
7559 drop(a);
7560 assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7561 }
7562
7563 #[test]
7564 fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7565 let dir = tempfile::tempdir().unwrap();
7566 let q = Queue::at(dir.path().to_path_buf());
7567 let held = q.lock_task("t").unwrap();
7568 let path = dir.path().join("t.write-lock");
7569 age_lock(&path);
7570 assert!(!break_stale(&path, &held.token));
7571 let (started_tx, started_rx) = std::sync::mpsc::channel();
7572 let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7573 let updater = std::thread::spawn(move || {
7574 started_tx.send(()).unwrap();
7575 let _write = q.lock_task("t").unwrap();
7576 acquired_tx.send(()).unwrap();
7577 });
7578 started_rx.recv().unwrap();
7579 assert!(
7580 acquired_rx
7581 .recv_timeout(std::time::Duration::from_millis(100))
7582 .is_err()
7583 );
7584 assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7585 drop(held);
7586 acquired_rx
7587 .recv_timeout(std::time::Duration::from_secs(2))
7588 .unwrap();
7589 updater.join().unwrap();
7590 assert!(!path.exists());
7591 }
7592
7593 #[test]
7594 fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7595 let dir = tempfile::tempdir().unwrap();
7596 let lock = dir.path().join("t.write-lock");
7597 std::fs::write(&lock, "new-token").unwrap();
7598 assert!(!break_stale(&lock, "old-token"));
7599 assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7600 assert!(!break_stale(&lock, "new-token"));
7602 assert!(lock.exists());
7603 age_lock(&lock);
7604 assert!(break_stale(&lock, "new-token"));
7605 assert!(!lock.exists());
7606 }
7607
7608 #[test]
7609 fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7610 let dir = tempfile::tempdir().unwrap();
7611 let lock = dir.path().join("t.write-lock");
7612 std::fs::write(&lock, "dead-1").unwrap();
7613 age_lock(&lock);
7614 let marker = break_marker(&lock, "dead-1");
7615 std::fs::write(&marker, "crashed-remover").unwrap();
7616 assert!(!break_stale(&lock, "dead-1"));
7618 assert!(lock.exists());
7619 age_lock(&marker);
7621 assert!(break_stale(&lock, "dead-1"));
7622 assert!(!lock.exists());
7623 assert!(!marker.exists());
7624 }
7625
7626 fn chat_task() -> Task {
7627 Task::new(
7628 "t".to_owned(),
7629 "do t".to_owned(),
7630 PathBuf::from("."),
7631 Source::Agent {
7632 run: "20260902-000000-beef".to_owned(),
7633 node: CHAT_NODE.to_owned(),
7634 },
7635 )
7636 }
7637
7638 #[test]
7639 fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7640 let mut t = chat_task();
7641 t.hold_machine(Some("waiting".into()));
7642 let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7643 t.held_at = Some(old);
7644 t.block(vec!["decision".into()], None);
7645 t.hold_machine(Some("same waiting decision".into()));
7646 assert_eq!(t.held_at, Some(old));
7647 t.start("real-new-run".into());
7648 t.fail("new failure", 1);
7649 assert_ne!(
7650 t.held_at,
7651 Some(old),
7652 "old answers cannot approve a new hold"
7653 );
7654 }
7655
7656 #[test]
7657 fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7658 let (_dir, queue) = queue();
7659 let mut t = chat_task();
7660 t.start("old-run".into());
7661 t.hold_machine(Some("operator is considering recovery".into()));
7662 t.chat_notice = Some(ChatNotice {
7663 key: format!("held#{}", t.held_at.unwrap()),
7664 at: Timestamp::now(),
7665 outcome: ChatNoticeOutcome::Posted,
7666 });
7667 let mut raw = serde_json::to_value(&t).unwrap();
7668 raw.as_object_mut().unwrap().remove("chat_notices");
7669 raw.as_object_mut().unwrap().remove("hold_notice_cause");
7670 std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7671 std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7672 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7673 queue
7674 .modify(&t.id, |task| {
7675 task.requeue();
7676 task.link_run("unprepared-run");
7677 task.startup_notice_cause("startup-source");
7678 task.fail("same unresolved preflight", 0);
7679 true
7680 })
7681 .unwrap();
7682 assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7683 queue
7684 .modify(&t.id, |task| {
7685 task.succeed(completion(task));
7686 true
7687 })
7688 .unwrap();
7689 assert!(
7690 queue
7691 .get(&t.id)
7692 .unwrap()
7693 .chat_notice_due()
7694 .unwrap()
7695 .starts_with("done:")
7696 );
7697 }
7698
7699 #[test]
7700 fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7701 let mut t = chat_task();
7702 t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7703 let key = t.chat_notice_key().unwrap();
7704 t.chat_notices.push(key);
7705 t.release();
7706 t.block(
7707 vec!["b".into(), "a".into(), "a".into()],
7708 Some("still waiting on prerequisites".into()),
7709 );
7710 assert_eq!(t.chat_notice_due(), None);
7711 t.block(
7712 vec!["new-question".into()],
7713 Some("different decision".into()),
7714 );
7715 assert!(t.chat_notice_due().is_some());
7716 }
7717
7718 #[test]
7719 fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7720 let mut t = chat_task();
7721 t.start("existing-run".into());
7722 t.fail("implementation failed", 1);
7723 let failed = t.chat_notice_key().unwrap();
7724 t.chat_notices.push(failed.clone());
7725 t.release_operator("test", None);
7726 t.start("existing-run".into());
7727 t.fail_startup("startup-source", "same unresolved recovery source", 1);
7728 assert_eq!(
7729 t.chat_notice_due(),
7730 None,
7731 "no-progress recovery stays quiet"
7732 );
7733 t.release_operator("test", None);
7734 t.start("existing-run".into());
7735 t.fail_startup("startup-attachments", "attachment missing", 1);
7736 let attachments = t.chat_notice_due().expect("new attachment blocker");
7737 assert_ne!(attachments, failed);
7738 assert_eq!(
7739 t.hold_notice_cause.as_ref().unwrap().stage,
7740 "startup-attachments"
7741 );
7742 t.chat_notices.push(attachments);
7743 t.release_operator("test", None);
7744 t.start("existing-run".into());
7745 t.fail_startup(
7746 "startup-attachments",
7747 "same missing attachment, reworded",
7748 1,
7749 );
7750 assert_eq!(
7751 t.chat_notice_due(),
7752 None,
7753 "same stage after attempt counter reset"
7754 );
7755 t.release_operator("test", None);
7756 t.start("existing-run".into());
7757 t.fail_startup("startup-config", "different preflight stage", 1);
7758 assert!(t.chat_notice_due().is_some());
7759 assert_eq!(
7760 t.hold_notice_cause.as_ref().unwrap().stage,
7761 "startup-config"
7762 );
7763 }
7764
7765 #[test]
7766 fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7767 let mut t = chat_task();
7768 t.hold_machine(Some("startup source missing".into()));
7769 t.startup_notice_cause("startup-source");
7770 let first = t.chat_notice_key().unwrap();
7771 t.chat_notices.push(first.clone());
7772 t.release_operator("test", None);
7773 t.startup_notice_cause("startup-source");
7774 t.hold_machine(Some("same source cannot be read".into()));
7775 assert_eq!(t.chat_notice_due(), None);
7776 t.startup_notice_cause("startup-config");
7777 assert!(t.chat_notice_due().is_some(), "different startup stage");
7778 t.notice_cause("failed", Some("existing-run"), Some(0));
7779 let run_failure = t.chat_notice_key().unwrap();
7780 t.chat_notices.push(run_failure.clone());
7781 t.release_operator("test", None);
7782 t.startup_notice_cause("startup-source");
7783 t.hold_machine(Some("no new work happened".into()));
7784 assert_eq!(t.chat_notice_due(), None);
7785 t.notice_cause("failed", Some("existing-run"), Some(1));
7786 assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7787 assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7788 }
7789
7790 #[test]
7791 fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7792 let mut t = chat_task();
7793 t.hold_machine(Some("still waiting".into()));
7794 t.chat_notice = Some(ChatNotice {
7795 key: "held#2026-10-14T00:00:00Z".into(),
7796 at: Timestamp::now(),
7797 outcome: ChatNoticeOutcome::Posted,
7798 });
7799 assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7800 t.import_chat_notice();
7801 t.notice_cause("failed", Some("new-run"), Some(0));
7802 assert!(t.chat_notice_due().is_some(), "new producer evidence");
7803 t.succeed(completion(&t));
7804 assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7805 }
7806
7807 #[test]
7808 fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7809 let mut t = chat_task();
7810 assert_eq!(t.chat_notice_due(), None, "queued");
7811 t.start("r1".to_owned());
7812 assert_eq!(t.chat_notice_due(), None, "running");
7813 t.fail("boom", 3);
7814 assert_eq!(t.status, TaskStatus::Failed);
7815 assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7816 t.start("r2".to_owned());
7817 t.park("upgrade");
7818 assert_eq!(t.chat_notice_due(), None, "parked");
7819 t.fail("boom", 1);
7820 assert_eq!(t.status, TaskStatus::Held);
7821 let key = t
7822 .chat_notice_due()
7823 .expect("held on the last attempt is final");
7824 t.chat_notice = Some(ChatNotice {
7825 key,
7826 at: Timestamp::now(),
7827 outcome: ChatNoticeOutcome::Posted,
7828 });
7829 assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7830 t.release();
7831 assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7832 t.start("r3".to_owned());
7833 t.succeed(completion(&t));
7834 assert!(t.chat_notice_due().is_some(), "done is a new final state");
7835 }
7836
7837 #[test]
7838 fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7839 for key in ["done", "done#0", "done#1", "done#12"] {
7840 let mut t = chat_task();
7841 t.status = TaskStatus::Done;
7842 t.chat_notice = Some(ChatNotice {
7843 key: key.to_owned(),
7844 at: Timestamp::now(),
7845 outcome: ChatNoticeOutcome::Posted,
7846 });
7847 assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7848 assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7849 let mut context = completion(&t);
7850 context.reason = Some("inspect again".into());
7851 t.reopen(context).unwrap();
7852 t.start("r2".to_owned());
7853 t.succeed(completion(&t));
7854 assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7855 assert!(
7856 t.chat_notice_due().is_some(),
7857 "new occurrence, old receipt: {key}"
7858 );
7859 }
7860 }
7861
7862 #[test]
7863 fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7864 let mut t = chat_task();
7865 t.hold_manual(Some("wait".to_owned()));
7866 let first = t.chat_notice_due().expect("held");
7867 t.chat_notice = Some(ChatNotice {
7868 key: first.clone(),
7869 at: Timestamp::now(),
7870 outcome: ChatNoticeOutcome::Posted,
7871 });
7872 t.hold_manual(Some("still waiting".to_owned()));
7873 assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7874 t.release();
7875 std::thread::sleep(std::time::Duration::from_millis(5));
7876 t.hold_manual(None);
7877 assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7878 }
7879
7880 #[test]
7881 fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7882 let mut human = task("h");
7883 human.succeed(completion(&human));
7884 assert_eq!(human.chat_notice_due(), None);
7885 let mut inherited = task("i");
7887 inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7888 inherited.succeed(completion(&inherited));
7889 assert_eq!(inherited.chat_notice_due(), None);
7890 let mut old = chat_task();
7891 old.schema = 12;
7892 old.status = TaskStatus::Done;
7893 assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7894 let mut live = chat_task();
7895 live.schema = 12;
7896 live.start("r1".to_owned());
7897 live.succeed(completion(&live));
7898 assert!(live.chat_notice_due().is_some(), "started by this build");
7899 let mut held = chat_task();
7900 held.schema = 12;
7901 held.hold_machine(Some("config".to_owned()));
7902 assert!(held.chat_notice_due().is_some(), "held before any start");
7903 }
7904
7905 #[test]
7906 fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7907 let tmp = tempfile::tempdir().expect("tempdir");
7908 let q = Queue::at(tmp.path().join("queue"));
7909 let mut t = chat_task();
7910 t.succeed(completion(&t));
7911 q.put(&mut t).expect("put");
7912 let mut stale = q.get(&t.id).expect("get");
7913 let key = t.chat_notice_due().expect("due");
7914 q.modify(&t.id, |x| {
7915 x.chat_notice = Some(ChatNotice {
7916 key: key.clone(),
7917 at: Timestamp::now(),
7918 outcome: ChatNoticeOutcome::Posted,
7919 });
7920 true
7921 })
7922 .expect("modify");
7923 q.put(&mut stale).expect("stale put");
7924 assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7925 }
7926
7927 #[test]
7928 fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7929 let mut t = task("plain");
7932 let value = serde_json::to_value(&t).unwrap();
7933 assert!(value.get("sources").is_none(), "{value}");
7934 t.sources.pick_commits.push(crate::refs::Input {
7935 token: "abc1234".into(),
7936 sha: "a".repeat(40),
7937 provenance: crate::refs::Provenance::ExplicitCli,
7938 });
7939 let value = serde_json::to_value(&t).unwrap();
7940 assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7941 let restored: Task = serde_json::from_value(value).unwrap();
7942 assert_eq!(restored.sources, t.sources);
7943 }
7944
7945 fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7947 let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7948 let n = std::sync::atomic::AtomicUsize::new(0);
7949 Queue::at(dir.join("queue")).with_id_source(move || {
7950 let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7951 ids.get(i)
7952 .cloned()
7953 .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7954 })
7955 }
7956
7957 const TAKEN: &str = "20260101-000000-aaaa";
7958
7959 #[test]
7960 fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7961 let dir = tempfile::tempdir().unwrap();
7962 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7963 let mut first = task("first");
7964 first.start("run-1".into());
7965 first.succeed(completion(&first));
7966 q.put(&mut first).unwrap();
7967 assert_eq!(first.id, TAKEN);
7968 let stored_before = q.get(&first.id).unwrap();
7969 assert!(!stored_before.runs.is_empty());
7970
7971 let mut second = task("second");
7972 q.put(&mut second).unwrap();
7973
7974 assert_ne!(second.id, first.id);
7975 assert!(second.runs.is_empty());
7976 assert!(second.passes.is_empty());
7977 assert!(second.chat_notices.is_empty());
7978 assert!(second.chat_notice.is_none());
7979 assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7980 let a = q.get(&first.id).unwrap();
7981 let b = q.get(&second.id).unwrap();
7982 assert_eq!(a.title, "first");
7983 assert_eq!(a.runs, stored_before.runs);
7984 assert_eq!(a.passes, stored_before.passes);
7985 assert_eq!(a.chat_notices, stored_before.chat_notices);
7986 assert_eq!(a.chat_notice, stored_before.chat_notice);
7987 assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7988 assert_eq!(b.title, "second");
7989 assert!(b.runs.is_empty());
7990 assert!(b.passes.is_empty());
7991 assert!(b.chat_notice.is_none());
7992
7993 let mut again = q.get(&second.id).unwrap();
7995 again.title = "second, edited".into();
7996 q.put(&mut again).unwrap();
7997 assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7998 assert_eq!(q.list().len(), 2);
7999 }
8000
8001 #[test]
8002 fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
8003 let dir = tempfile::tempdir().unwrap();
8004 let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
8005 std::fs::create_dir_all(q.root()).unwrap();
8006 std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
8007 std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
8008 let mut t = task("t");
8009 q.put(&mut t).unwrap();
8010 assert_eq!(t.id, "free");
8011 }
8012
8013 #[test]
8014 fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
8015 let dir = tempfile::tempdir().unwrap();
8016 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8017 let mut first = task("first");
8018 q.put(&mut first).unwrap();
8019 let mut second = task("second");
8020 let claim = q.file_claimed(&mut second).unwrap();
8021 assert_ne!(second.id, first.id);
8022 assert!(q.claim(&second.id).is_err());
8023 assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
8024 drop(claim);
8025 }
8026
8027 #[test]
8028 fn an_attached_new_task_skips_a_taken_id() {
8029 let dir = tempfile::tempdir().unwrap();
8030 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8031 let mut first = task("first");
8032 q.put(&mut first).unwrap();
8033 let src = source_file(dir.path(), "shot.png", "x");
8034 let mut second = task("second");
8035 q.attach_and_put(&mut second, &[src]).unwrap();
8036 assert_ne!(second.id, first.id);
8037 assert!(!q.attachments_dir(&first.id).exists());
8038 assert_eq!(q.attachment_paths(&second).len(), 1);
8039 assert!(q.attachment_paths(&second)[0].is_file());
8040 }
8041
8042 #[test]
8043 fn attaching_before_putting_a_new_task_reserves_the_id() {
8044 let dir = tempfile::tempdir().unwrap();
8045 let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8046 let mut first = task("first");
8047 q.put(&mut first).unwrap();
8048 let src = source_file(dir.path(), "shot.png", "x");
8049 let mut second = task("second");
8050 q.attach(&mut second, &[src]).unwrap();
8051 assert_ne!(second.id, first.id);
8052 assert!(q.attachments_dir(&second.id).is_dir());
8053 q.put(&mut second).unwrap();
8054 assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
8055 assert_eq!(q.get(&first.id).unwrap().title, "first");
8056 assert!(q.get(&first.id).unwrap().attachments.is_empty());
8057 }
8058
8059 #[test]
8060 fn create_new_keeps_its_already_exists_meaning() {
8061 let dir = tempfile::tempdir().unwrap();
8062 let q = Queue::at(dir.path().join("queue"));
8063 let mut a = task("a");
8064 a.id = "fixed-id".into();
8065 assert!(q.create_new(&mut a).unwrap());
8066 let mut b = task("b");
8067 b.id = "fixed-id".into();
8068 assert!(!q.create_new(&mut b).unwrap());
8069 assert_eq!(q.get("fixed-id").unwrap().title, "a");
8070 }
8071
8072 #[test]
8073 fn filing_gives_up_when_no_id_is_ever_free() {
8074 let dir = tempfile::tempdir().unwrap();
8075 let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
8076 let mut first = task("first");
8077 q.put(&mut first).unwrap();
8078 let mut second = task("second");
8079 assert!(q.put(&mut second).is_err());
8080 assert_eq!(q.get(&first.id).unwrap().title, "first");
8081 }
8082}