Skip to main content

orch/engine/tick/
mod.rs

1//! Core tick loop phases.
2//!
3//! The engine ticks every ~10 seconds. Each tick runs six phases:
4//! 1. Poll tmux for finished sessions
5//! 2. Recover stuck in-progress tasks
6//! 3. Route and dispatch:
7//!    - 3a. Route new tasks to agents
8//!    - 3b. Dispatch routed tasks (spawn agents)
9//! 4. Unblock parents whose children are all done
10//! 5. Run cron job scheduler
11//!
12//! [`tick_all`] runs them for every project. Phases 1-2 and 3b-5 run for all projects at
13//! once; only routing is serial, because it holds the router write lock. Store-wide work
14//! (`tick_global_sweeps`, `reconcile_dependencies`) runs once per tick, not once per project.
15
16mod dispatch;
17mod recovery;
18
19use super::{EngineConfig, ProjectEngine};
20use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Status};
21use crate::channels::capture::CaptureService;
22use crate::channels::transport::Transport;
23use crate::engine;
24use crate::engine::cooldown::{github_circuit_remaining_secs, is_github_circuit_open};
25use crate::engine::dependencies;
26use crate::engine::jobs;
27use crate::engine::router::config as router_config;
28use crate::engine::router::{AllAgentsCooledError, Router, RouterConfig};
29use crate::engine::runner::{TaskRunner, WeightSignal};
30use crate::engine::sync;
31use crate::engine::tasks;
32use crate::engine::tasks::{TaskManager, is_internal_id};
33use crate::github::http;
34use crate::repo_context::REPO_CONTEXT;
35use crate::store;
36use crate::store::StoreRoute;
37use crate::store::Task;
38use crate::store::TaskStatus;
39use crate::store::TaskStore;
40use crate::store::WaitingOnDependency;
41use crate::store::{store_set_by_id, store_touch_updated_at};
42use crate::tmux::TmuxManager;
43use dashmap::{DashMap, DashSet};
44use dispatch::skips_agent;
45pub(crate) use dispatch::{
46    DispatchMode, dispatch_mode_from_router, dispatch_routed_tasks_global, tick_dispatch_tasks,
47};
48use futures::future;
49use recovery::{StuckTaskTiming, finalize_open_runs_for_recovery};
50pub(crate) use recovery::{
51    recover_untracked_repo_stuck_tasks, tick_detect_silent_agents, tick_recover_stuck_tasks,
52};
53use std::collections::HashMap;
54use std::collections::HashSet;
55use std::path::Path;
56use std::sync::Arc;
57use std::sync::OnceLock;
58use std::time::{Instant, SystemTime};
59use tokio::sync::RwLock;
60use tokio::sync::{Semaphore, mpsc};
61
62/// Per outer engine-loop quota for expensive routing calls.
63///
64/// Routing runs once per active project. Without a quota shared by all of them,
65/// `router.max_tasks_per_tick = 1` still permits one slow LLM routing call per
66/// project, multiplying 45s router timeouts into multi-minute watchdog stalls.
67pub(crate) struct RoutingTickQuota {
68    remaining: usize,
69}
70
71impl RoutingTickQuota {
72    pub(crate) fn new(max: usize) -> Self {
73        Self { remaining: max }
74    }
75
76    fn is_exhausted(&self) -> bool {
77        self.remaining == 0
78    }
79
80    fn remaining(&self) -> usize {
81        self.remaining
82    }
83
84    fn consume_one(&mut self) -> bool {
85        if self.remaining == 0 {
86            return false;
87        }
88        self.remaining -= 1;
89        true
90    }
91}
92
93/// Cleanup stale tmux sessions from previous engine runs.
94/// Called once from `serve()` before the main loop, never from a tick
95pub(crate) async fn startup_cleanup(tmux: &TmuxManager) {
96    let start_time = SystemTime::now()
97        .duration_since(SystemTime::UNIX_EPOCH)
98        .unwrap_or_default()
99        .as_secs();
100    tracing::info!(
101        start_time,
102        "running startup cleanup for stale tmux sessions"
103    );
104
105    match tmux.kill_stale_sessions(start_time).await {
106        Ok(killed) => {
107            if killed > 0 {
108                tracing::info!(killed, "startup cleanup killed stale sessions");
109            } else {
110                tracing::debug!("no stale tmux sessions found on startup");
111            }
112        }
113        Err(e) => {
114            tracing::warn!(error = %e, "failed to run startup cleanup");
115        }
116    }
117}
118
119async fn recover_routed_blocked_dispatch(
120    backend: &Arc<dyn ExternalBackend>,
121    store: &Arc<TaskStore>,
122    task_manager: &Arc<TaskManager>,
123    repo: &str,
124    task: &ExternalTask,
125    timing: &StuckTaskTiming,
126) {
127    tracing::warn!(
128        task_id = task.id.0,
129        age_mins = timing.age.num_minutes(),
130        threshold_mins = timing.threshold / 60,
131        "recovering routed task: dispatch blocked by stale tmux session → new"
132    );
133
134    let resolved_store_id = match store.resolve_task_id(repo, &task.id.0).await {
135        Ok(Some(id)) => Some(id),
136        Ok(None) => {
137            tracing::warn!(
138                task_id = %task.id.0,
139                repo,
140                "resolve_task_id returned None during routed-task recovery"
141            );
142            None
143        }
144        Err(e) => {
145            tracing::error!(
146                task_id = %task.id.0,
147                repo,
148                error = %e,
149                "resolve_task_id failed during routed-task recovery"
150            );
151            None
152        }
153    };
154
155    if let Some(store_id) = resolved_store_id {
156        if let Err(e) = store_set_by_id(
157            Some(store),
158            store_id,
159            &[
160                ("agent", serde_json::Value::Null),
161                ("model", serde_json::Value::Null),
162                ("route_attempts", serde_json::json!(0)),
163            ],
164        )
165        .await
166        {
167            tracing::warn!(
168                task_id = task.id.0,
169                ?e,
170                "failed to clear routing fields for routed stuck task — will retry next tick"
171            );
172            return;
173        }
174        finalize_open_runs_for_recovery(
175            store,
176            store_id,
177            "stuck-task recovery: stale session blocking dispatch killed",
178        )
179        .await;
180    }
181
182    if let Err(e) = task_manager.update_task_status(&task.id, Status::New).await {
183        tracing::warn!(
184            task_id = task.id.0,
185            ?e,
186            "failed to reset routed stuck task status"
187        );
188        return;
189    }
190
191    store::store_log_activity(
192        &Some(Arc::clone(store)),
193        repo,
194        &task.id.0,
195        "rerouted",
196        Some("routed"),
197        Some("new"),
198        None::<&str>,
199        None::<&str>,
200        Some(&serde_json::json!({
201            "failure_reason": "routed_blocked_by_existing_session",
202            "age_minutes": timing.age.num_minutes(),
203            "had_session": true,
204        })),
205    )
206    .await;
207
208    if !is_internal_id(&task.id.0) {
209        let backend_clone = Arc::clone(backend);
210        let task_id_clone = task.id.clone();
211        let body = format!(
212            "[{}] recovered: stuck routed task — existing tmux session blocked dispatch for {}m; cleared route for retry{}",
213            chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
214            timing.age.num_minutes(),
215            engine::orch_footer()
216        );
217        tokio::spawn(async move {
218            if let Err(e) = backend_clone.post_comment(&task_id_clone, &body).await {
219                tracing::warn!(
220                    task_id = task_id_clone.0,
221                    ?e,
222                    "failed to post routed-task recovery comment"
223                );
224            }
225        });
226    }
227}
228
229/// Phase 1 of tick: poll tmux for finished sessions and clean them up.
230pub(crate) async fn tick_check_session_completions(
231    tmux: &Arc<TmuxManager>,
232    repo: &str,
233    capture: &Arc<CaptureService>,
234    store: &Arc<TaskStore>,
235) -> anyhow::Result<()> {
236    let _span = tracing::info_span!("engine.tick.phase1.sessions").entered();
237    let session_snapshot = tmux.snapshot().await;
238    // Derive the short project name from repo (owner/repo -> repo), matching
239    // TmuxManager::session_name's derivation exactly (including the ".git" strip)
240    // so a repo configured with a ".git" suffix doesn't silently fail to match
241    // its own live sessions here — leaving stuck-task recovery as the only
242    // (later, coarser-grained) safety net for this repo's session completions.
243    let repo_name = repo
244        .rsplit('/')
245        .next()
246        .unwrap_or(repo)
247        .trim_end_matches(".git");
248    for (session, active) in session_snapshot {
249        // Only handle sessions that belong to this repo/project.
250        if session.project != repo_name {
251            continue;
252        }
253
254        if !active {
255            tracing::info!(
256                session = %session.name,
257                task_id = %session.task_id,
258                "session completed, collecting results"
259            );
260            // Touch the store.updated_at immediately when we observe a completed
261            // session so the stuck-task recovery phase doesn't incorrectly
262            // reclaim this task while the runner is still finishing
263            // post-processing (race: session observed dead → tick reclaim).
264            // Best-effort: no-ops if the task isn't present in the store.
265            //
266            // session.task_id uses hyphens (e.g. "internal-63714") because the
267            // tmux session name sanitizes colons to hyphens. resolve_task_id only
268            // handles "internal:" prefix, so we must convert back before touching.
269            // Review sessions carry a "-review" suffix tracked under the main task.
270            let store_task_id = {
271                let base = session
272                    .task_id
273                    .strip_suffix("-review")
274                    .unwrap_or(&session.task_id);
275                if let Some(n) = base.strip_prefix("internal-") {
276                    format!("internal:{n}")
277                } else {
278                    base.to_string()
279                }
280            };
281            store_touch_updated_at(&Some(Arc::clone(store)), repo, &store_task_id).await;
282            // Unregister from capture service using the task id the capture service
283            // was registered under (task id without project prefix).
284            capture.unregister_session(repo, &session.task_id).await;
285            // Kill the actual tmux session name we discovered (do not reconstruct)
286            if let Err(e) = tmux.kill_session(&session.name).await {
287                tracing::debug!(
288                    session = %session.name,
289                    ?e,
290                    "kill_session failed (session may already be gone)"
291                );
292            }
293        }
294    }
295    Ok(())
296}
297
298/// The tier whose run timeout the task runs with: the tier of its stored model, which differs from
299/// its own complexity when the model came from an adjacent tier
300fn run_tier(router: &RouterConfig, task: &Task) -> String {
301    match (task.agent.as_deref(), task.model.as_deref()) {
302        (Some(a), Some(m)) if !m.is_empty() => router.tier_of_model(a, m, &task.complexity),
303        _ => task.complexity.clone(),
304    }
305}
306
307/// The router config for this tick, loaded on first use. A full load re-reads the config and
308/// repeats its startup warnings, so one tick shares one load across every live run
309fn tick_router(
310    cell: &OnceLock<RouterConfig>,
311    load: impl FnOnce() -> RouterConfig,
312) -> &RouterConfig {
313    cell.get_or_init(load)
314}
315
316fn should_use_backend(task_id: &str) -> bool {
317    !is_internal_id(task_id)
318}
319
320/**
321 * The three store-wide recovery sweeps, run once per tick rather than once per project.
322 *
323 * Each one reads every repo, so a per-project call duplicates the work. The NeedsReview
324 * sweep also reads `needs_review_refires` and then increments it, so concurrent per-project
325 * passes all see the same count and four projects burn four of the five refire attempts in
326 * one tick (#3864)
327 **/
328pub(crate) async fn tick_global_sweeps(
329    task_manager: &Arc<TaskManager>,
330    store: &Arc<TaskStore>,
331    router: &Router,
332    dispatching: &Arc<DashMap<String, String>>,
333    auto_merge_in_flight: &Arc<DashSet<String>>,
334    active_repos: &HashSet<String>,
335) {
336    // Global sweep for CI-failure blocked tasks from inactive or removed projects.
337    // auto_unblock_blocked_tasks runs inside sync_tick and is scoped to the active repo.
338    // Tasks blocked for projects no longer in orch config are never processed there.
339    // This sweep covers all repos so stale CI-failure blocks are eventually resolved.
340    if let Err(e) = sync::auto_unblock_ci_failure_blocked_tasks_global(
341        task_manager,
342        store,
343        auto_merge_in_flight,
344    )
345    .await
346    {
347        tracing::warn!(err = %e, "global CI-failure blocked sweep failed");
348    }
349
350    // Re-fire stale NeedsReview tasks and escalate persistently-stuck ones to
351    // Blocked, across all repos
352    if let Err(e) = sync::refire_and_escalate_stale_needs_review_global(
353        task_manager,
354        store,
355        router,
356        dispatching,
357        active_repos,
358    )
359    .await
360    {
361        tracing::warn!(err = %e, "global NeedsReview refire/escalation sweep failed");
362    }
363
364    // Recover rebroadcast-blocked tasks once a review agent is routable, across
365    // all repos
366    if let Err(e) = sync::auto_recover_rebroadcast_blocked_tasks_global(
367        router,
368        task_manager,
369        store,
370        active_repos,
371    )
372    .await
373    {
374        tracing::warn!(err = %e, "global rebroadcast-blocked recovery sweep failed");
375    }
376}
377
378/// Phase 3a of tick: route status:new tasks to an agent and transition them to status:routed.
379pub(crate) async fn tick_route_tasks(
380    backend: &Arc<dyn ExternalBackend>,
381    task_manager: &Arc<TaskManager>,
382    router: &mut Router,
383    store: &Arc<TaskStore>,
384    repo: &str,
385    routing_quota: &mut RoutingTickQuota,
386) -> anyhow::Result<()> {
387    let _span = tracing::info_span!("engine.tick.phase3a.route").entered();
388    if let Err(err) = dependencies::apply_claim_gates(store).await {
389        tracing::warn!(err = %err, "dependency claim gate failed");
390    }
391    if routing_quota.is_exhausted() {
392        tracing::debug!("routing quota exhausted for this tick — skipping repo routing phase");
393        return Ok(());
394    }
395
396    // Global GitHub 5xx circuit breaker — skip routing during sustained GitHub outages
397    // to avoid routing-heavy retry storms. Tasks will remain in 'new' status and be
398    // retried when the circuit closes.
399    if is_github_circuit_open() {
400        let remaining = github_circuit_remaining_secs();
401        tracing::info!(
402            remaining_secs = remaining,
403            "GitHub 5xx circuit breaker open — skipping routing phase"
404        );
405        return Ok(());
406    }
407    let new_tasks = task_manager.list_routable().await?;
408    let routable: Vec<&ExternalTask> = new_tasks
409        .iter()
410        .filter(|t| !skips_agent(&t.labels))
411        .collect();
412
413    // Pre-emptive health check: refresh degraded-agent flags once per tick,
414    // not per-task (previously this ran inside route() causing N redundant
415    // DB queries when routing N tasks in the same tick).
416    if !routable.is_empty() {
417        let start = Instant::now();
418        router.refresh_health(store).await;
419        tracing::debug!(
420            duration_ms = start.elapsed().as_millis(),
421            "router.refresh_health completed"
422        );
423    }
424
425    // Limit routing to the remaining global quota for this outer engine tick.
426    for task in routable.into_iter().take(routing_quota.remaining()) {
427        if !routing_quota.consume_one() {
428            break;
429        }
430        let _task_span = tracing::info_span!("engine.route", task_id = %task.id.0).entered();
431
432        let task_start = Instant::now();
433        match router.route(task, store, repo).await {
434            Ok(result) => {
435                tracing::debug!(task_id = %task.id.0, duration_ms = task_start.elapsed().as_millis(), "route completed");
436                // Store route result in store
437                if let Err(e) = router
438                    .store_route_result(&task.id.0, &result, store, repo)
439                    .await
440                {
441                    tracing::warn!(
442                        task_id = task.id.0,
443                        ?e,
444                        "failed to store route result; skipping Routed transition"
445                    );
446                    continue;
447                }
448
449                if is_internal_id(&task.id.0) {
450                    // Internal tasks: update DB status, skip GitHub label ops.
451                    if let Err(e) = task_manager
452                        .update_task_status(&task.id, Status::Routed)
453                        .await
454                    {
455                        tracing::warn!(
456                            task_id = task.id.0,
457                            ?e,
458                            "failed to set internal status:routed"
459                        );
460                        continue;
461                    }
462                } else {
463                    // Fire-and-forget: label operations are cosmetic (routing already
464                    // persisted in DB). Spawning them prevents blocking the tick loop
465                    // on 6-9 sequential HTTP calls (~3-9s overhead per routed task).
466                    let backend_clone = Arc::clone(backend);
467                    let task_id_clone = task.id.clone();
468                    let task_labels: Vec<String> = task.labels.clone();
469                    let new_labels = {
470                        let mut labels = vec![
471                            format!("agent:{}", result.agent),
472                            format!("complexity:{}", result.complexity),
473                        ];
474                        if let Some(ref model) = result.model {
475                            labels.push(format!("model:{model}"));
476                        }
477                        labels
478                    };
479                    tokio::spawn(async move {
480                        // Remove old agent/complexity/model labels
481                        for label in &task_labels {
482                            if (label.starts_with("agent:")
483                                || label.starts_with("complexity:")
484                                || label.starts_with("model:"))
485                                && let Err(e) =
486                                    backend_clone.remove_label(&task_id_clone, label).await
487                            {
488                                tracing::warn!(task_id = task_id_clone.0, label, error = %e, "failed to remove stale routing label during re-route");
489                            }
490                        }
491                        // Add new labels
492                        if let Err(e) = backend_clone.set_labels(&task_id_clone, &new_labels).await
493                        {
494                            tracing::warn!(
495                                task_id = task_id_clone.0,
496                                ?e,
497                                "failed to set routing labels"
498                            );
499                        }
500                    });
501
502                    // Transition to routed
503                    if let Err(e) = task_manager
504                        .update_task_status(&task.id, Status::Routed)
505                        .await
506                    {
507                        tracing::warn!(task_id = task.id.0, ?e, "failed to set status:routed");
508                        continue;
509                    }
510                }
511
512                // Dual-write: upsert task + store route result in SQLite
513                match store.ensure_external_task(repo, task).await {
514                    Ok(store_id) => {
515                        let profile_json =
516                            serde_json::to_string(&result.profile).unwrap_or_default();
517                        if let Err(e) = store
518                            .store_route(&crate::store::StoreRoute {
519                                id: store_id,
520                                agent: &result.agent,
521                                model: result.model.as_deref(),
522                                complexity: &result.complexity,
523                                estimate: result.estimate,
524                                reason: &result.reason,
525                                profile: &profile_json,
526                            })
527                            .await
528                        {
529                            tracing::debug!(
530                                task_id = task.id.0,
531                                ?e,
532                                "dual-write: store_route failed"
533                            );
534                        }
535                        if let Err(e) = store.update_status(store_id, TaskStatus::Routed).await {
536                            tracing::debug!(
537                                task_id = task.id.0,
538                                ?e,
539                                "dual-write: update_status failed"
540                            );
541                        }
542                        // Sync the estimate to GitHub Projects if the router assigned one.
543                        // Fire-and-forget: do NOT await inline — GraphQL mutations can take
544                        // up to 30 s and would block the entire tick loop on every routed task.
545                        if result.estimate > 0 {
546                            let backend_clone = Arc::clone(backend);
547                            let task_id = task.id.clone();
548                            let estimate = result.estimate;
549                            tokio::spawn(async move {
550                                if let Err(e) = backend_clone
551                                    .sync_estimate_to_project(&task_id, estimate)
552                                    .await
553                                {
554                                    tracing::debug!(
555                                        task_id = task_id.0,
556                                        estimate,
557                                        err = %e,
558                                        "dual-write: estimate project sync failed"
559                                    );
560                                }
561                            });
562                        }
563                    }
564                    Err(e) => {
565                        tracing::debug!(
566                            task_id = task.id.0,
567                            ?e,
568                            "dual-write: ensure_external_task failed"
569                        );
570                    }
571                }
572
573                if let Some(ref warning) = result.warning {
574                    tracing::warn!(task_id = task.id.0, warning, "routing sanity warning");
575                }
576
577                tracing::info!(
578                    task_id = task.id.0,
579                    agent = %result.agent,
580                    complexity = %result.complexity,
581                    reason = %result.reason,
582                    "task routed"
583                );
584            }
585            Err(e) => {
586                if let Some(cooled) = e.downcast_ref::<AllAgentsCooledError>() {
587                    tracing::error!(
588                        task_id = %task.id.0,
589                        scope = %cooled.scope(),
590                        remaining_secs = ?cooled.remaining_secs(),
591                        degraded = ?cooled.degraded(),
592                        "ALL AGENTS COOLED — no agent available to route this task. \
593                         Task stays in 'new' and will be retried on every tick. \
594                         Check `orch cooldown list` to see what is blocking dispatch."
595                    );
596                    continue;
597                }
598                if let Some(waiting) = e.downcast_ref::<WaitingOnDependency>() {
599                    tracing::info!(
600                        task_id = %task.id.0,
601                        blockers = %waiting.blockers.join(", "),
602                        "task is waiting on a dependency"
603                    );
604                    continue;
605                }
606                tracing::error!(task_id = task.id.0, ?e, "routing failed, skipping task");
607            }
608        }
609    }
610    Ok(())
611}
612
613/// Global routing sweep: route status:new tasks from inactive or removed repos.
614///
615/// `tick_route_tasks` is scoped to the active repo per-tick and never processes
616/// tasks whose `repo` field differs from the current project. When a project is
617/// removed from the orch config, its tasks accumulate in `new` indefinitely
618/// because no tick ever runs for that repo. This sweep covers all repos so
619/// orphaned new tasks are eventually routed.
620///
621/// `active_repos` must be the full set of currently-configured project repos,
622/// not just the repo of the tick that called this — mirroring
623/// `dispatch_routed_tasks_global` (see its doc comment for the "racing the real
624/// per-repo dispatch" failure mode this guards against). Filtering on
625/// `t.repo != current_repo` alone (the previous behavior) made every *other*
626/// active repo's new tasks look "orphaned" too and routed them a tick early,
627/// through the wrong repo's tick.
628pub(crate) async fn route_new_tasks_global(
629    router: &mut Router,
630    store: &Arc<TaskStore>,
631    active_repos: &HashSet<String>,
632    routing_quota: &mut RoutingTickQuota,
633) -> anyhow::Result<()> {
634    if routing_quota.is_exhausted() {
635        tracing::debug!("routing quota exhausted for this tick — skipping global routing sweep");
636        return Ok(());
637    }
638
639    let all_new = store.list_all_by_status_global(TaskStatus::New).await?;
640    let orphaned: Vec<&Task> = all_new
641        .iter()
642        .filter(|t| !active_repos.contains(&t.repo))
643        .filter(|t| !skips_agent(&t.labels))
644        .collect();
645
646    if orphaned.is_empty() {
647        return Ok(());
648    }
649
650    tracing::info!(
651        count = orphaned.len(),
652        "global routing sweep: found new tasks from inactive repos"
653    );
654
655    router.refresh_health(store).await;
656
657    for task in orphaned.into_iter().take(routing_quota.remaining()) {
658        if !routing_quota.consume_one() {
659            break;
660        }
661        let ext_task = tasks::store_task_to_external(task);
662        let task_start = Instant::now();
663        match router.route(&ext_task, store, &task.repo).await {
664            Ok(result) => {
665                tracing::debug!(
666                    task_id = %ext_task.id.0,
667                    repo = %task.repo,
668                    duration_ms = task_start.elapsed().as_millis(),
669                    "global sweep: route completed"
670                );
671                let profile_json = serde_json::to_string(&result.profile).unwrap_or_default();
672                if let Err(e) = store
673                    .store_route(&StoreRoute {
674                        id: task.id,
675                        agent: &result.agent,
676                        model: result.model.as_deref(),
677                        complexity: &result.complexity,
678                        estimate: result.estimate,
679                        reason: &result.reason,
680                        profile: &profile_json,
681                    })
682                    .await
683                {
684                    tracing::warn!(
685                        task_id = %ext_task.id.0,
686                        repo = %task.repo,
687                        err = %e,
688                        "global sweep: failed to store route result; skipping status update"
689                    );
690                    continue;
691                }
692                match store.update_status(task.id, TaskStatus::Routed).await {
693                    Err(e) => {
694                        tracing::warn!(
695                            task_id = %ext_task.id.0,
696                            repo = %task.repo,
697                            err = %e,
698                            "global sweep: failed to set status:routed"
699                        );
700                    }
701                    _ => {
702                        tracing::info!(
703                            task_id = %ext_task.id.0,
704                            repo = %task.repo,
705                            agent = %result.agent,
706                            complexity = %result.complexity,
707                            "global sweep: task routed"
708                        );
709                    }
710                }
711                if let Some(ref warning) = result.warning {
712                    tracing::warn!(task_id = %ext_task.id.0, warning, "global sweep: routing sanity warning");
713                }
714            }
715            Err(e) => {
716                if let Some(cooled) = e.downcast_ref::<AllAgentsCooledError>() {
717                    tracing::error!(
718                        task_id = %ext_task.id.0,
719                        repo = %task.repo,
720                        scope = %cooled.scope(),
721                        remaining_secs = ?cooled.remaining_secs(),
722                        degraded = ?cooled.degraded(),
723                        "global sweep: ALL AGENTS COOLED — task stays in 'new'"
724                    );
725                    continue;
726                }
727                if let Some(waiting) = e.downcast_ref::<WaitingOnDependency>() {
728                    tracing::info!(
729                        task_id = %ext_task.id.0,
730                        repo = %task.repo,
731                        blockers = %waiting.blockers.join(", "),
732                        "global sweep: task is waiting on a dependency"
733                    );
734                    continue;
735                }
736                tracing::error!(
737                    task_id = %ext_task.id.0,
738                    repo = %task.repo,
739                    err = ?e,
740                    "global sweep: routing failed, skipping task"
741                );
742            }
743        }
744    }
745
746    Ok(())
747}
748
749/// Phase 4 of tick: unblock parent tasks whose sub-issues are all done.
750pub(crate) async fn tick_unblock_parents(
751    backend: &Arc<dyn ExternalBackend>,
752    task_manager: &Arc<TaskManager>,
753    store: &Arc<TaskStore>,
754    repo: &str,
755) -> anyhow::Result<()> {
756    let blocked = task_manager.list_all_by_status(Status::Blocked).await?;
757
758    // Pre-filter: skip tasks that are blocked for a known reason (e.g. CI failure,
759    // escalation). These are not waiting on children, so there is no point making
760    // a GraphQL call for them.
761    let store_blocked = store.list_by_status(repo, TaskStatus::Blocked).await?;
762    let has_block_reason: HashSet<String> = store_blocked
763        .iter()
764        .filter(|t| t.block_reason.is_some())
765        .filter_map(|t| t.external_id.clone())
766        .collect();
767
768    // Spawn a concurrent task for each candidate blocked task.
769    // Previously these ran sequentially; get_sub_issues is a GraphQL call taking 1-3 s each,
770    // and with 4 blocked tasks that was 4-12 s of sequential latency every tick.
771    let handles: Vec<_> = blocked
772        .into_iter()
773        .filter(|task| {
774            if has_block_reason.contains(&task.id.0) {
775                tracing::debug!(
776                    task_id = task.id.0,
777                    "skipping blocked task with known block_reason"
778                );
779                false
780            } else {
781                true
782            }
783        })
784        .map(|task| {
785            let backend_clone = Arc::clone(backend);
786            let task_manager_clone = Arc::clone(task_manager);
787            let store_clone = Arc::clone(store);
788            let repo_owned = repo.to_string();
789            tokio::spawn(async move {
790                let task_id = &task.id;
791
792                let mut children: Vec<ExternalId> = Vec::new();
793                let mut child_statuses: HashMap<
794                    String,
795                    TaskStatus,
796                > = HashMap::new();
797
798                match store_clone.resolve_task_id(&repo_owned, &task_id.0).await {
799                    Ok(Some(parent_store_id)) => {
800                        match store_clone.list_children(&repo_owned, parent_store_id).await {
801                            Ok(store_children) => {
802                                for child in store_children {
803                                    let Some(child_external_id) = child.external_id else {
804                                        continue;
805                                    };
806                                    child_statuses.insert(child_external_id.clone(), child.status);
807                                    children.push(ExternalId(child_external_id));
808                                }
809                            }
810                            Err(e) => {
811                                tracing::debug!(
812                                    task_id = task_id.0,
813                                    ?e,
814                                    "failed to list store-linked children"
815                                );
816                            }
817                        }
818                    }
819                    Ok(None) => {}
820                    Err(e) => {
821                        tracing::debug!(
822                            task_id = task_id.0,
823                            ?e,
824                            "failed to resolve blocked task in store for child lookup"
825                        );
826                    }
827                }
828
829                if !is_internal_id(&task_id.0) {
830                    match backend_clone.get_sub_issues(task_id).await {
831                        Ok(ids) => {
832                            let mut seen: HashSet<String> =
833                                children.iter().map(|child| child.0.clone()).collect();
834                            for id in ids {
835                                if seen.insert(id.0.clone()) {
836                                    children.push(id);
837                                }
838                            }
839                        }
840                        Err(e) => {
841                            tracing::debug!(task_id = task_id.0, ?e, "failed to get sub-issues");
842                        }
843                    }
844                }
845
846                // No children means nothing to wait on — skip (may be blocked for other reasons)
847                if children.is_empty() {
848                    return;
849                }
850
851                // Check if every child is done using the local store (batched) and
852                // fall back to the backend only for children not present in the store.
853                let mut all_done = true;
854                // Build owned strings for the batch lookup (needed for &str slices below)
855                let child_ext_strs: Vec<String> =
856                    children.iter().map(|c| c.0.clone()).collect();
857                let child_exts: Vec<&str> =
858                    child_ext_strs.iter().map(String::as_str).collect();
859                // Query store for statuses of any children present locally
860                match store_clone
861                    .get_statuses_by_external_ids(&repo_owned, &child_exts)
862                    .await
863                { Ok(map) => {
864                    for (k, v) in map {
865                        child_statuses.insert(k, v);
866                    }
867                } _ => {
868                    tracing::debug!(
869                        task_id = task_id.0,
870                        "failed to batch-query store for child statuses; falling back to per-child lookups"
871                    );
872                }}
873
874                for child_id in &children {
875                    // Check store first
876                    if let Some(status) = child_statuses.get(&child_id.0) {
877                        if *status != TaskStatus::Done {
878                            all_done = false;
879                            break;
880                        }
881                        continue;
882                    }
883
884                    // Not found in store — fall back to backend check
885                    match backend_clone.get_task(child_id).await {
886                        Ok(child) => {
887                            if !child.labels.iter().any(|l| l == Status::Done.as_label()) {
888                                all_done = false;
889                                break;
890                            }
891                        }
892                        Err(e) => {
893                            tracing::debug!(task_id = task_id.0, child = %child_id.0, ?e, "failed to fetch child task from backend — treating as not done");
894                            all_done = false;
895                            break;
896                        }
897                    }
898                }
899
900                if all_done {
901                    tracing::info!(
902                        task_id = task_id.0,
903                        children = children.len(),
904                        "all children done, unblocking parent"
905                    );
906                    if let Err(e) =
907                        task_manager_clone.update_task_status(task_id, Status::New).await
908                    {
909                        tracing::warn!(task_id = task_id.0, ?e, "failed to unblock parent");
910                    }
911                }
912            })
913        })
914        .collect();
915
916    for handle in handles {
917        if let Err(e) = handle.await {
918            tracing::warn!(?e, "phase 4 sub-issue check panicked");
919        }
920    }
921    Ok(())
922}
923
924/// Phase 5 of tick: run cron job matching and fire any due jobs.
925pub(crate) async fn tick_job_scheduler(
926    jobs_path: &Path,
927    backend: &Arc<dyn ExternalBackend>,
928    store: Option<&Arc<TaskStore>>,
929    repo: &str,
930    transport: Option<&Arc<Transport>>,
931) -> anyhow::Result<()> {
932    jobs::tick(jobs_path, backend, store, repo, transport).await
933}
934
935/// Core tick for one project, up to the routing phase.
936///
937/// Every phase here is scoped to one project, so all projects can run this at the same time:
938/// 1. `tick_check_session_completions` — poll tmux for finished sessions
939/// 2. `tick_detect_silent_agents`      — cooldown agents that produced no output
940/// 3. `tick_recover_stuck_tasks`       — reset in_progress/in_review tasks with no session
941///
942/// The store-wide work that used to sit in here runs once per tick in `tick_all`:
943/// `tick_global_sweeps` and `reconcile_dependencies`.
944#[expect(
945    clippy::too_many_arguments,
946    reason = "each argument is engine state the tick passes down"
947)]
948pub(crate) async fn tick_before_routing(
949    backend: &Arc<dyn ExternalBackend>,
950    tmux: &Arc<TmuxManager>,
951    repo: &str,
952    capture: &Arc<CaptureService>,
953    config: &EngineConfig,
954    task_manager: &Arc<TaskManager>,
955    dispatching: &Arc<DashMap<String, String>>,
956    store: &Arc<TaskStore>,
957    session_map: &HashMap<String, bool>,
958) {
959    let mut phases: Vec<(&str, u128)> = Vec::new();
960    let mut at = Instant::now();
961
962    if let Err(e) = tick_check_session_completions(tmux, repo, capture, store).await {
963        tracing::warn!(err = %e, "session completion phase failed");
964    }
965    phases.push(("sessions", at.elapsed().as_millis()));
966
967    // Every node tends its own sessions, only the leader decides. Followers dispatch once
968    // tasks are assigned to nodes
969    if !store.is_leader() {
970        super::log_phase_timings("tick.pre_routing", repo, &phases);
971        return;
972    }
973
974    at = Instant::now();
975    if let Err(e) =
976        tick_detect_silent_agents(tmux, repo, capture, backend, task_manager, config, store).await
977    {
978        tracing::warn!(err = %e, "silent-agent detection phase failed");
979    }
980    phases.push(("silent_agents", at.elapsed().as_millis()));
981
982    at = Instant::now();
983    if let Err(e) = tick_recover_stuck_tasks(
984        backend,
985        tmux,
986        repo,
987        task_manager,
988        config,
989        store,
990        session_map,
991        dispatching,
992    )
993    .await
994    {
995        tracing::warn!(err = %e, "stuck-task recovery phase failed");
996    }
997    phases.push(("stuck_tasks", at.elapsed().as_millis()));
998
999    super::log_phase_timings("tick.pre_routing", repo, &phases);
1000}
1001
1002/// Core tick for one project, after the routing phase.
1003///
1004/// Takes the router's decision as a `DispatchMode` value instead of the router itself, so
1005/// every project can run this at the same time:
1006/// 1. `tick_dispatch_tasks`  — spawn agents for status:routed tasks
1007/// 2. `tick_unblock_parents` — unblock parents whose sub-issues are all done
1008/// 3. `tick_job_scheduler`   — fire due cron jobs
1009#[expect(
1010    clippy::too_many_arguments,
1011    reason = "each argument is engine state the tick passes down"
1012)]
1013pub(crate) async fn tick_after_routing(
1014    backend: &Arc<dyn ExternalBackend>,
1015    tmux: &Arc<TmuxManager>,
1016    repo: &str,
1017    runner: &Arc<TaskRunner>,
1018    capture: &Arc<CaptureService>,
1019    semaphore: &Arc<Semaphore>,
1020    project_dir: &Path,
1021    task_manager: &Arc<TaskManager>,
1022    weight_tx: &mpsc::Sender<WeightSignal>,
1023    dispatch_mode: DispatchMode,
1024    dispatching: &Arc<DashMap<String, String>>,
1025    store: &Arc<TaskStore>,
1026    transport: Option<&Arc<Transport>>,
1027    session_map: &HashMap<String, bool>,
1028) {
1029    let mut phases: Vec<(&str, u128)> = Vec::new();
1030    let mut at = Instant::now();
1031
1032    if let Err(e) = tick_dispatch_tasks(
1033        backend,
1034        tmux,
1035        repo,
1036        runner,
1037        capture,
1038        semaphore,
1039        task_manager,
1040        weight_tx,
1041        dispatch_mode,
1042        dispatching,
1043        store,
1044        session_map,
1045    )
1046    .await
1047    {
1048        tracing::warn!(err = %e, "dispatch phase failed");
1049    }
1050    phases.push(("dispatch", at.elapsed().as_millis()));
1051
1052    at = Instant::now();
1053    if let Err(e) = tick_unblock_parents(backend, task_manager, store, repo).await {
1054        tracing::warn!(err = %e, "parent-unblock phase failed");
1055    }
1056    phases.push(("unblock_parents", at.elapsed().as_millis()));
1057
1058    at = Instant::now();
1059    let jobs_path = project_dir.join(".orch.yml");
1060    if let Err(e) = tick_job_scheduler(&jobs_path, backend, Some(store), repo, transport).await {
1061        tracing::error!(?e, "job scheduler tick failed");
1062    }
1063    phases.push(("jobs", at.elapsed().as_millis()));
1064
1065    super::log_phase_timings("tick.post_routing", repo, &phases);
1066}
1067
1068/// Core tick — runs every 10s for every project.
1069///
1070/// Projects no longer wait on each other: the phases around routing run for all of them at
1071/// once, so tick time tracks the slowest project instead of the sum. Routing stays serial
1072/// because it needs the router write lock and one shared `RoutingTickQuota`, which is what
1073/// gives `router.max_tasks_per_tick` its meaning.
1074///
1075/// The tmux session map, the global sweeps and the dependency reconcile are the same for
1076/// every project, so they run once per tick rather than once per project.
1077#[expect(
1078    clippy::too_many_arguments,
1079    reason = "each argument is engine state the tick passes down"
1080)]
1081pub(crate) async fn tick_all(
1082    engines: &[ProjectEngine],
1083    tmux: &Arc<TmuxManager>,
1084    capture: &Arc<CaptureService>,
1085    semaphore: &Arc<Semaphore>,
1086    config: &EngineConfig,
1087    router: &Arc<RwLock<Router>>,
1088    weight_tx: &mpsc::Sender<WeightSignal>,
1089    dispatching: &Arc<DashMap<String, String>>,
1090    transport: Option<&Arc<Transport>>,
1091    active_repos: &HashSet<String>,
1092    auto_merge_in_flight: &Arc<DashSet<String>>,
1093) {
1094    let _tick_span = tracing::info_span!("engine.tick").entered();
1095
1096    let Some(first) = engines.first() else {
1097        return;
1098    };
1099    // All project engines share one SQLite store, so leadership and the global sweeps below
1100    // are the same whichever project they are read from
1101    let store = &first.store;
1102
1103    // Calls made since the previous tick, so hourly quota exhaustion can be traced
1104    for (project, call_type, calls) in http::drain_call_counts().into_iter().take(10) {
1105        tracing::debug!(
1106            project,
1107            call_type,
1108            calls,
1109            "github api calls since last tick"
1110        );
1111    }
1112
1113    // One `tmux list-panes -a` for every project's stuck-task recovery, instead of one each
1114    let session_map = tmux.batch_session_active().await;
1115
1116    let mut passes = Vec::with_capacity(engines.len());
1117    for engine in engines {
1118        passes.push(REPO_CONTEXT.scope(
1119            engine.repo.clone(),
1120            tick_before_routing(
1121                &engine.backend,
1122                tmux,
1123                &engine.repo,
1124                capture,
1125                config,
1126                &engine.task_manager,
1127                dispatching,
1128                &engine.store,
1129                &session_map,
1130            ),
1131        ));
1132    }
1133    future::join_all(passes).await;
1134
1135    if !store.is_leader() {
1136        return;
1137    }
1138
1139    // Store-wide, so once per tick rather than once per project. Both read every repo, and
1140    // the NeedsReview sweep increments a counter it just read, which concurrent per-project
1141    // passes would each consume (#3864)
1142    let at = Instant::now();
1143    {
1144        let router_guard = router.read().await;
1145        tick_global_sweeps(
1146            &first.task_manager,
1147            store,
1148            &router_guard,
1149            dispatching,
1150            auto_merge_in_flight,
1151            active_repos,
1152        )
1153        .await;
1154    }
1155    let sweeps_ms = at.elapsed().as_millis();
1156
1157    let at = Instant::now();
1158    recover_untracked_repo_stuck_tasks(
1159        tmux,
1160        config,
1161        store,
1162        &session_map,
1163        dispatching,
1164        active_repos,
1165    )
1166    .await;
1167    let untracked_ms = at.elapsed().as_millis();
1168
1169    let at = Instant::now();
1170    if let Err(err) = dependencies::reconcile_dependencies(
1171        first.backend.as_ref(),
1172        store,
1173        transport.map(AsRef::as_ref),
1174    )
1175    .await
1176    {
1177        tracing::warn!(err = %err, "dependency reconcile failed");
1178    }
1179    super::log_phase_timings(
1180        "tick.global",
1181        &first.repo,
1182        &[
1183            ("global_sweeps", sweeps_ms),
1184            ("untracked_stuck", untracked_ms),
1185            ("dependencies", at.elapsed().as_millis()),
1186        ],
1187    );
1188
1189    {
1190        let mut router_guard = router.write().await;
1191        let mut routing_quota = RoutingTickQuota::new(router_config::max_tasks_per_routing_tick());
1192        for engine in engines {
1193            let at = Instant::now();
1194            REPO_CONTEXT
1195                .scope(engine.repo.clone(), async {
1196                    if let Err(e) = tick_route_tasks(
1197                        &engine.backend,
1198                        &engine.task_manager,
1199                        &mut router_guard,
1200                        &engine.store,
1201                        &engine.repo,
1202                        &mut routing_quota,
1203                    )
1204                    .await
1205                    {
1206                        tracing::warn!(err = %e, "routing phase failed");
1207                    }
1208                })
1209                .await;
1210            super::log_phase_timings(
1211                "tick.routing",
1212                &engine.repo,
1213                &[("route", at.elapsed().as_millis())],
1214            );
1215        }
1216
1217        // Global routing sweep for tasks from inactive or removed repos.
1218        // tick_route_tasks is scoped to the active repo; tasks from projects no longer
1219        // in config are never returned by list_routable and would stay in 'new' indefinitely.
1220        if let Err(e) =
1221            route_new_tasks_global(&mut router_guard, store, active_repos, &mut routing_quota).await
1222        {
1223            tracing::warn!(err = %e, "global new-task routing sweep failed");
1224        }
1225    }
1226
1227    let dispatch_mode = dispatch_mode_from_router(&*router.read().await);
1228
1229    // Re-read the session map: the completion phase above kills the sessions of finished
1230    // agents, and dispatch must not treat a killed session as one that still blocks a task
1231    let session_map = tmux.batch_session_active().await;
1232
1233    let mut passes = Vec::with_capacity(engines.len());
1234    for engine in engines {
1235        passes.push(REPO_CONTEXT.scope(
1236            engine.repo.clone(),
1237            tick_after_routing(
1238                &engine.backend,
1239                tmux,
1240                &engine.repo,
1241                &engine.runner,
1242                capture,
1243                semaphore,
1244                &engine.project_dir,
1245                &engine.task_manager,
1246                weight_tx,
1247                dispatch_mode,
1248                dispatching,
1249                &engine.store,
1250                transport,
1251                &session_map,
1252            ),
1253        ));
1254    }
1255    future::join_all(passes).await;
1256
1257    // Global dispatch sweep for routed tasks from inactive or removed repos.
1258    // tick_dispatch_tasks is scoped to each active repo; tasks from projects no longer
1259    // in config are never returned by list_external_by_status and would stay in
1260    // 'routed' indefinitely (see #3413). Excludes the full active-repo set, not just
1261    // one repo, so it doesn't treat other active repos as orphaned.
1262    if let Err(e) = dispatch_routed_tasks_global(
1263        tmux,
1264        capture,
1265        semaphore,
1266        weight_tx,
1267        dispatch_mode,
1268        dispatching,
1269        store,
1270        &session_map,
1271        active_repos,
1272    )
1273    .await
1274    {
1275        tracing::warn!(err = %e, "global routed-task dispatch sweep failed");
1276    }
1277}
1278
1279/// Status a finished run moves to. Only a successful run with no PR (or with the review agent
1280/// off) becomes `done`. A failed run stays in `needs_review` with its issue open
1281pub(crate) fn display_status_for(
1282    signal: &WeightSignal,
1283    enable_review: bool,
1284    has_pr: bool,
1285) -> &'static str {
1286    match signal {
1287        WeightSignal::Success { .. } if enable_review => {
1288            if has_pr {
1289                "needs_review"
1290            } else {
1291                "done"
1292            }
1293        }
1294        // Silence detection or another non-rate-limit reset already moved the task to "new".
1295        // Converting it to needs_review would trigger the no-code shortcut and falsely close it
1296        WeightSignal::RateLimited { .. } | WeightSignal::Rerouted => "new",
1297        WeightSignal::Blocked => "blocked",
1298        // The review path re-routes a task with no PR and no commits
1299        WeightSignal::Failed { .. } => "needs_review",
1300        // None means the runner guard skipped the task or the status was unrecognised
1301        WeightSignal::None if enable_review => "needs_review",
1302        WeightSignal::Success { .. } | WeightSignal::None => "done",
1303    }
1304}
1305
1306#[cfg(test)]
1307mod tests;
1308
1309#[cfg(test)]
1310mod recovery_tests;
1311
1312#[cfg(test)]
1313mod dispatch_tests;