Skip to main content

orch/engine/sync/
mod.rs

1//! Sync tick — periodic operations that run less frequently than the core tick.
2//!
3//! The sync tick runs every ~45 seconds and handles:
4//! - Worktree cleanup for done tasks
5//! - Merged-PR detection
6//! - @mention scanning and internal task creation
7//! - PR review processing and follow-up dispatch
8//! - Stale InReview detection
9//! - Owner /slash command scanning
10
11mod comments;
12mod unblock;
13
14use super::EngineConfig;
15use crate::backends::ExternalTask;
16use crate::backends::{ExternalBackend, Status};
17use crate::cooldown;
18use crate::cooldown::{
19    cooldown_reason, github_circuit_remaining_secs, is_agent_in_cooldown, is_github_circuit_open,
20    is_model_in_cooldown, refresh_degraded_agents,
21};
22use crate::engine;
23use crate::engine::agents::patterns;
24use crate::engine::ci::bootstrap;
25use crate::engine::git::cleanup::ReviewTaskSnapshot;
26use crate::engine::git::cleanup::{check_merged_prs, cleanup_done_worktrees, prune_old_run_output};
27use crate::engine::review::poll::review_open_prs;
28use crate::engine::router::Router;
29use crate::engine::router::RouterConfig;
30use crate::engine::router::config as router_config;
31use crate::engine::tasks;
32use crate::engine::tasks::dependencies;
33use crate::engine::tasks::{TaskManager, status_to_task_status};
34use crate::github::http::GhHttp;
35use crate::store;
36use crate::store::Task;
37use crate::store::TaskRun;
38use crate::store::TaskStatus;
39use crate::store::TaskStore;
40use crate::sys::tmux::TmuxManager;
41use comments::{fetch_comments_since, filter_mentions_by_since, scan_comments};
42use dashmap::{DashMap, DashSet};
43use std::collections::HashMap;
44use std::collections::HashSet;
45use std::sync::Arc;
46use std::time::Instant;
47use tokio::sync::RwLock;
48use unblock::{REBROADCAST_BLOCK_REASON, auto_unblock_blocked_tasks};
49pub(crate) use unblock::{
50    auto_recover_rebroadcast_blocked_tasks_global, auto_unblock_ci_failure_blocked_tasks_global,
51};
52
53/// Read a KV value from the store.
54///
55/// Returns `None` if the store is unavailable, the key doesn't exist, OR if
56/// the store query fails. Use [`try_kv_get_prefer_store`] if you need to
57/// distinguish between "key not found" and actual errors.
58async fn kv_get_prefer_store(store: Option<&Arc<TaskStore>>, key: &str) -> Option<String> {
59    match try_kv_get_prefer_store(store, key).await {
60        Ok(opt) => opt,
61        Err(e) => {
62            tracing::error!(key, err = %e, "kv_get failed");
63            None
64        }
65    }
66}
67
68/// Try to read a KV value from the store, returning errors instead of
69/// silently discarding them.
70///
71/// Returns `Ok(None)` if the store is unavailable or the key doesn't exist.
72/// Returns `Err` if the store query fails.
73async fn try_kv_get_prefer_store(
74    store: Option<&Arc<TaskStore>>,
75    key: &str,
76) -> anyhow::Result<Option<String>> {
77    if let Some(s) = store {
78        Ok(s.kv_get(key).await?)
79    } else {
80        Ok(None)
81    }
82}
83
84/// Write a KV value to the store.
85///
86/// Logs warnings on failure but provides no way for callers to know if the
87/// write succeeded. Use [`try_kv_set_prefer_store`] if you need to handle
88/// errors or guarantee persistence (e.g., for circuit breaker state).
89async fn kv_set_prefer_store(store: Option<&Arc<TaskStore>>, key: &str, value: &str) {
90    if let Err(e) = try_kv_set_prefer_store(store, key, value).await {
91        tracing::error!(key, err = %e, "kv_set failed");
92    }
93}
94
95/// Try to write a KV value to the store, returning errors instead of
96/// silently logging them.
97///
98/// Returns `Ok(())` if the store is unavailable (best-effort) or if the
99/// write succeeds. Returns `Err` if the store query fails.
100async fn try_kv_set_prefer_store(
101    store: Option<&Arc<TaskStore>>,
102    key: &str,
103    value: &str,
104) -> anyhow::Result<()> {
105    if let Some(s) = store {
106        s.kv_set(key, value).await?;
107    }
108    Ok(())
109}
110
111async fn prefetch_review_tasks(
112    store: &Arc<TaskStore>,
113    repo: &str,
114) -> anyhow::Result<(
115    Vec<ReviewTaskSnapshot>,
116    Vec<ReviewTaskSnapshot>,
117    Vec<ReviewTaskSnapshot>,
118)> {
119    // Approved tasks wait on the same merge path as a review in progress
120    let mut in_review = store.list_by_status(repo, TaskStatus::InReview).await?;
121    in_review.extend(store.list_by_status(repo, TaskStatus::Approved).await?);
122    let in_review = in_review
123        .into_iter()
124        .map(|stored| ReviewTaskSnapshot {
125            external: tasks::store_task_to_external(&stored),
126            stored,
127        })
128        .collect();
129    let needs_review = store
130        .list_by_status(repo, TaskStatus::NeedsReview)
131        .await?
132        .into_iter()
133        .map(|stored| ReviewTaskSnapshot {
134            external: tasks::store_task_to_external(&stored),
135            stored,
136        })
137        .collect();
138
139    // Also prefetch blocked tasks that have a branch or PR number recorded.
140    // These can be merged externally (or manually) but previously were invisible
141    // to the merged-PR checker, leaving tasks stuck in Blocked after merges.
142    let blocked_candidates = store
143        .list_by_status(repo, TaskStatus::Blocked)
144        .await?
145        .into_iter()
146        .filter(|stored| stored.pr_number.is_some() || !stored.branch.is_empty())
147        .map(|stored| ReviewTaskSnapshot {
148            external: tasks::store_task_to_external(&stored),
149            stored,
150        })
151        .collect();
152
153    Ok((in_review, needs_review, blocked_candidates))
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157enum FailureCategory {
158    FalseFailure,
159    RateLimit,
160    CreditExhausted,
161    SilentExit0,
162    Timeout,
163    ConnectionError,
164    CliFlagError,
165    AllAgentsExhausted,
166    ParseError,
167    MaxAttempts,
168    PushFailed,
169    PrCreateFailed,
170    ModelUnavailable,
171    Unknown,
172}
173
174impl FailureCategory {
175    /// Whether auto-unblock may put the task back in the queue on its own.
176    ///
177    /// `MaxAttempts` is deliberately absent: the task already ran the configured
178    /// number of times, so an automatic retry just restarts the loop that produced
179    /// the block. It stays blocked until `orch task unblock` or `orch task retry`
180    /// (#3783)
181    fn is_recoverable(self) -> bool {
182        matches!(
183            self,
184            FailureCategory::FalseFailure
185                | FailureCategory::RateLimit
186                | FailureCategory::CreditExhausted
187                | FailureCategory::SilentExit0
188                | FailureCategory::Timeout
189                | FailureCategory::ConnectionError
190                | FailureCategory::CliFlagError
191                | FailureCategory::AllAgentsExhausted
192                | FailureCategory::ParseError
193                | FailureCategory::ModelUnavailable
194        )
195    }
196
197    fn as_str(self) -> &'static str {
198        match self {
199            FailureCategory::FalseFailure => "FalseFailure",
200            FailureCategory::RateLimit => "RateLimit",
201            FailureCategory::CreditExhausted => "CreditExhausted",
202            FailureCategory::SilentExit0 => "SilentExit0",
203            FailureCategory::Timeout => "Timeout",
204            FailureCategory::ConnectionError => "ConnectionError",
205            FailureCategory::CliFlagError => "CliFlagError",
206            FailureCategory::AllAgentsExhausted => "AllAgentsExhausted",
207            FailureCategory::ParseError => "ParseError",
208            FailureCategory::MaxAttempts => "MaxAttempts",
209            FailureCategory::PushFailed => "PushFailed",
210            FailureCategory::PrCreateFailed => "PrCreateFailed",
211            FailureCategory::ModelUnavailable => "ModelUnavailable",
212            FailureCategory::Unknown => "Unknown",
213        }
214    }
215}
216
217fn classify_failure(error: &str, outcome: &str) -> FailureCategory {
218    let lower = error.to_lowercase();
219
220    if outcome == "timeout" || lower.contains("timeout") {
221        return FailureCategory::Timeout;
222    }
223
224    // Credit exhaustion is a transient condition (credits replenish, billing cycles
225    // reset). Classifying it as recoverable allows auto-unblock to retry once the
226    // credit-related cooldown expires, instead of permanently blocking the task.
227    //
228    // Checked before the generic rate-limit branch below: billing-cycle exhaustion
229    // messages (e.g. Kimi's "usage limit for this billing cycle") also contain
230    // "usage limit"/"rate limit" substrings, so checking outcome/content-based
231    // rate-limit patterns first would misclassify them as plain RateLimit (issue
232    // #3529). `outcome` also carries the specific string from `classify_run_outcome`
233    // when the task_run already recorded it.
234    if outcome == "billing_cycle_exhausted"
235        || outcome == "credit_exhausted"
236        || outcome == "org_level_disabled"
237        || cooldown::detect_credit_exhaustion(&lower).is_some()
238    {
239        return FailureCategory::CreditExhausted;
240    }
241
242    if outcome == "rate_limit" || lower.contains("rate limit") || lower.contains("usage limit") {
243        return FailureCategory::RateLimit;
244    }
245
246    if error.trim().is_empty() {
247        return FailureCategory::FalseFailure;
248    }
249
250    if lower.contains("all agents exhausted") {
251        return FailureCategory::AllAgentsExhausted;
252    }
253
254    if lower.contains("max attempts") || lower.contains("exceeded max attempts") {
255        return FailureCategory::MaxAttempts;
256    }
257
258    if lower.contains("output-format=stream-json") && lower.contains("requires --verbose") {
259        return FailureCategory::CliFlagError;
260    }
261
262    if lower.contains("model unavailable")
263        || lower.contains("model not found")
264        || (lower.contains("does not exist") && lower.contains("model"))
265    {
266        return FailureCategory::ModelUnavailable;
267    }
268
269    if lower.contains("push failed") {
270        return FailureCategory::PushFailed;
271    }
272
273    if lower.contains("create pr failed")
274        || lower.contains("failed to create pull request")
275        || lower.contains("pull request creation failed")
276    {
277        return FailureCategory::PrCreateFailed;
278    }
279
280    if lower.contains("exit 0") {
281        return FailureCategory::SilentExit0;
282    }
283
284    if outcome == "parse_error"
285        || outcome == "truncated"
286        || lower.contains("invalid response")
287        || lower.contains("parse error")
288        || lower.contains("truncated")
289    {
290        return FailureCategory::ParseError;
291    }
292
293    if patterns::detect_network_error(&lower).is_some() {
294        return FailureCategory::ConnectionError;
295    }
296
297    FailureCategory::Unknown
298}
299
300fn classify_failure_from_run(run: &TaskRun) -> Option<FailureCategory> {
301    // Completed successfully — no failure to classify.
302    if run.outcome == "success" && run.error.trim().is_empty() {
303        return None;
304    }
305
306    // Skip runs with no meaningful data. Some runs are created then never
307    // populated (aborted/stale work). Treat these as non-failures so they
308    // don't block auto-unblock logic which considers recent failures.
309    // Historically an all-NULL/empty run would be promoted to Unknown which
310    // prevented auto-unblock. Ensure we early-return None for truly empty
311    // runs (no outcome, no error, no exit_code, no output).
312    if run.outcome.trim().is_empty()
313        && run.error.trim().is_empty()
314        && run.exit_code.is_none()
315        && run.stdout.trim().is_empty()
316        && run.stderr.trim().is_empty()
317    {
318        return None;
319    }
320
321    let has_output = !run.stdout.trim().is_empty() || !run.stderr.trim().is_empty();
322    if run.exit_code == Some(0) && !has_output && run.outcome != "success" {
323        return Some(FailureCategory::SilentExit0);
324    }
325
326    let mut category = classify_failure(&run.error, &run.outcome);
327
328    // Promote a bare "false failure" to Unknown only when we have a
329    // concrete non-zero exit code or other signs the run truly failed.
330    // Do NOT promote when exit_code is None (incomplete run) — those are
331    // handled above by skipping. This prevents NULL/aborted runs from
332    // turning recoverable FalseFailure into non-recoverable Unknown.
333    // Only promote when we have explicit evidence: a non-zero exit code
334    // or non-empty stdout/stderr. If exit_code is None we keep FalseFailure
335    // so the run remains recoverable.
336    if category == FailureCategory::FalseFailure {
337        let has_nonzero_exit = run.exit_code.is_some() && run.exit_code != Some(0);
338        let has_output = !run.stdout.trim().is_empty() || !run.stderr.trim().is_empty();
339        if has_nonzero_exit || has_output {
340            category = FailureCategory::Unknown;
341        }
342    }
343
344    Some(category)
345}
346
347/// Global sweep: re-fire stale NeedsReview tasks and escalate persistently-stuck ones
348/// to Blocked, across all repos.
349///
350/// Two cases where the event-driven subscriber in `subscribers/review/mod.rs` can miss
351/// a NeedsReview task: all review slots are busy when the event fires, or the
352/// broadcast receiver lagged and dropped it. Re-publish the NeedsReview status
353/// after a short idle window so the subscriber can pick it up when a slot is free.
354/// Using a status re-fire rather than spawning the review agent directly keeps this
355/// path stateless. The subscriber is still the sole spawner and uses the InReview
356/// transition as its atomic guard (issue #857)
357///
358/// Queries across all repos and writes through the store via `*_by_store_id`
359/// TaskManager helpers. Called once per main tick from `tick_global_sweeps`
360pub(crate) async fn refire_and_escalate_stale_needs_review_global(
361    task_manager: &Arc<TaskManager>,
362    store: &Arc<TaskStore>,
363    router: &Router,
364    dispatching: &Arc<DashMap<String, String>>,
365    active_repos: &HashSet<String>,
366) -> anyhow::Result<()> {
367    const MIN_STALE_NEEDS_REVIEW_MINUTES: i64 = 1;
368    const MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS: u64 = 5;
369
370    let needs_review_tasks = match store
371        .list_all_by_status_global(TaskStatus::NeedsReview)
372        .await
373    {
374        Ok(tasks) => tasks,
375        Err(e) => {
376            tracing::warn!(err = %e, "global NeedsReview refire sweep: failed to list needs_review tasks");
377            return Ok(());
378        }
379    };
380
381    if needs_review_tasks.is_empty() {
382        return Ok(());
383    }
384
385    // Re-firing while every review agent is cooled wastes the counter and can
386    // escalate a task to Blocked while the subscriber would only bail again
387    let all_review_agents_cooled = router.healthy_agent_count("review") == 0;
388    if all_review_agents_cooled {
389        tracing::info!(
390            count = needs_review_tasks.len(),
391            "global NeedsReview refire sweep: no review agent available — skipping this pass"
392        );
393        return Ok(());
394    }
395
396    for stored in needs_review_tasks {
397        // No review subscriber listens for a repo outside the active set
398        if !active_repos.contains(&stored.repo) {
399            continue;
400        }
401
402        let external = tasks::store_task_to_external(&stored);
403        let ext_id = external.id.clone();
404        let repo = stored.repo.clone();
405
406        let age_minutes = match chrono::DateTime::parse_from_rfc3339(&external.updated_at) {
407            Ok(updated_at) => {
408                let age = chrono::Utc::now() - updated_at.with_timezone(&chrono::Utc);
409                if age.num_minutes() < MIN_STALE_NEEDS_REVIEW_MINUTES {
410                    continue;
411                }
412                Some(age.num_minutes())
413            }
414            Err(_) => None,
415        };
416
417        // Skip tasks actively being dispatched by their owning repo's engine loop.
418        let dispatch_key = format!("{}/{}", repo, ext_id.0);
419        if dispatching.contains_key(&dispatch_key) {
420            continue;
421        }
422
423        let current_refires = u64::try_from(stored.needs_review_refires).unwrap_or(0);
424        let new_refires = current_refires + 1;
425
426        if new_refires > MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS {
427            tracing::warn!(
428                task_id = stored.id,
429                repo = %repo,
430                new_refires,
431                "global NeedsReview refire sweep: escalating to Blocked after repeated refires"
432            );
433            let fields = [
434                ("block_reason", serde_json::json!(REBROADCAST_BLOCK_REASON)),
435                (
436                    "last_error",
437                    serde_json::json!(format!("escalated after {} retries", new_refires)),
438                ),
439            ];
440            if let Err(e) = task_manager
441                .update_task_status_and_result_by_store_id(
442                    stored.id,
443                    &repo,
444                    &ext_id,
445                    Status::Blocked,
446                    &fields,
447                )
448                .await
449            {
450                tracing::error!(task_id = stored.id, repo = %repo, err = %e, "global NeedsReview refire sweep: escalation to Blocked failed — skipping to avoid silent auto-unblock loop");
451                continue;
452            }
453            if let Err(e) = store::store_increment_by_id(
454                &Some(Arc::clone(store)),
455                stored.id,
456                "needs_review_refires",
457            )
458            .await
459            {
460                tracing::warn!(
461                    task_id = stored.id,
462                    repo = %repo,
463                    err = %e,
464                    "global NeedsReview refire sweep: failed to increment needs_review_refires after escalation"
465                );
466            }
467            continue;
468        }
469
470        // Exponential backoff: MIN * 2^(current_refires)
471        let required_minutes =
472            MIN_STALE_NEEDS_REVIEW_MINUTES * (1i64 << u32::try_from(current_refires).unwrap_or(0));
473
474        let should_fire = match age_minutes {
475            Some(age) => age >= required_minutes,
476            None => true,
477        };
478
479        if !should_fire {
480            continue;
481        }
482
483        if let Err(e) = task_manager
484            .update_task_status_by_store_id(stored.id, &repo, &ext_id, Status::NeedsReview)
485            .await
486        {
487            tracing::warn!(
488                task_id = stored.id,
489                repo = %repo,
490                err = %e,
491                "global NeedsReview refire sweep: failed to re-fire NeedsReview event — not incrementing counter"
492            );
493            continue;
494        }
495
496        let fired_refires = match store::store_increment_by_id(
497            &Some(Arc::clone(store)),
498            stored.id,
499            "needs_review_refires",
500        )
501        .await
502        {
503            Ok(v) => v,
504            Err(e) => {
505                tracing::warn!(
506                    task_id = stored.id,
507                    repo = %repo,
508                    err = %e,
509                    "global NeedsReview refire sweep: failed to increment needs_review_refires after re-fire"
510                );
511                current_refires + 1
512            }
513        };
514
515        tracing::info!(
516            task_id = stored.id,
517            repo = %repo,
518            age_minutes,
519            refires = fired_refires,
520            required_minutes,
521            "global NeedsReview refire sweep: re-firing NeedsReview event for stale task"
522        );
523    }
524
525    Ok(())
526}
527
528/// Sync tick — runs every 45s.
529///
530/// Handles less-frequent operations:
531/// - Cleanup finished worktrees
532/// - Check for merged PRs → mark tasks done
533/// - Scan for @mentions
534#[expect(
535    clippy::too_many_arguments,
536    reason = "the engine passes its shared handles one by one"
537)]
538pub(crate) async fn sync_tick(
539    backend: &Arc<dyn ExternalBackend>,
540    tmux: &Arc<TmuxManager>,
541    repo: &str,
542    config: &EngineConfig,
543    router: &Arc<RwLock<Router>>,
544    task_manager: &Arc<TaskManager>,
545    store: &Arc<TaskStore>,
546    dispatching: &Arc<DashMap<String, String>>,
547    auto_merge_in_flight: &Arc<DashSet<String>>,
548) -> anyhow::Result<()> {
549    // One node polls GitHub and decides for the whole cluster
550    if !store.is_leader() {
551        return Ok(());
552    }
553
554    tracing::debug!("sync tick");
555
556    let mut phases: Vec<(&str, u128)> = Vec::new();
557    let mut at = Instant::now();
558
559    // Global GitHub 5xx circuit breaker — skip non-critical background work
560    // during sustained GitHub outages to reduce churn and wasted API calls.
561    let gh_circuit_open = is_github_circuit_open();
562
563    if gh_circuit_open {
564        let remaining = github_circuit_remaining_secs();
565        tracing::debug!(
566            remaining_secs = remaining,
567            "GitHub 5xx circuit breaker open — skipping non-critical sync work"
568        );
569        // Persist circuit breaker state as a metric for operators.
570        // This is critical for avoiding thundering herd after restart during outages.
571        if let Err(e) =
572            try_kv_set_prefer_store(Some(store), "metrics:orch.github_5xx_circuit.open", "1").await
573        {
574            tracing::error!(err = %e, "failed to persist circuit breaker state — may cause thundering herd after restart");
575        }
576    } else if let Err(e) =
577        try_kv_set_prefer_store(Some(store), "metrics:orch.github_5xx_circuit.open", "0").await
578    {
579        tracing::error!(err = %e, "failed to clear circuit breaker state");
580    }
581
582    // 0. Ingest all active external tasks into the unified store.
583    //    This ensures the store has data for tasks created before dual-write was added.
584    if !gh_circuit_open {
585        if let Err(e) = ingest_external_tasks(backend, repo, store).await {
586            tracing::debug!(err = %e, "external task ingest failed");
587        }
588        phases.push(("ingest", at.elapsed().as_millis()));
589        at = Instant::now();
590
591        // Reconcile existing board members too: labels can change without a
592        // local task transition, and a human/automation may move a card. The
593        // backend only writes drifted fields through the shared GitHub client.
594        if let Err(e) = backend.reconcile_project_statuses().await {
595            tracing::warn!(err = %e, "project status reconciliation failed");
596        }
597        phases.push(("board_reconcile", at.elapsed().as_millis()));
598    }
599    at = Instant::now();
600
601    // 1. Cleanup worktrees for done tasks (background — must not block routing/dispatch)
602    if !gh_circuit_open {
603        let backend = Arc::clone(backend);
604        let repo = repo.to_string();
605        let task_manager = Arc::clone(task_manager);
606        let store = Arc::clone(store);
607        tokio::spawn(async move {
608            if let Err(e) = cleanup_done_worktrees(&backend, &repo, &task_manager, &store).await {
609                tracing::warn!(err = %e, "worktree cleanup failed");
610            }
611            if let Err(e) = prune_old_run_output(&store).await {
612                tracing::warn!(err = %e, "task run pruning failed");
613            }
614        });
615    }
616
617    let (in_review_tasks, needs_review_tasks, blocked_review_candidates) =
618        match prefetch_review_tasks(store, repo).await {
619            Ok(tasks) => tasks,
620            Err(e) => {
621                tracing::warn!(err = %e, "failed to prefetch review tasks");
622                (vec![], vec![], vec![])
623            }
624        };
625    phases.push(("prefetch_review", at.elapsed().as_millis()));
626    at = Instant::now();
627
628    if !gh_circuit_open {
629        let mention_fallback = chrono::Utc::now() - chrono::Duration::hours(24);
630        let mention_since = kv_get_prefer_store(Some(store), "mentions_last_checked")
631            .await
632            .unwrap_or_else(|| mention_fallback.format("%Y-%m-%dT%H:%M:%SZ").to_string());
633        let shared_since = mention_since.clone();
634
635        let cached_router_config = router.read().await.config.clone();
636        // Include blocked tasks that have branch/pr info when checking for merged PRs.
637        let mut combined_needs = needs_review_tasks.clone();
638        combined_needs.extend(blocked_review_candidates.clone());
639
640        let (merge_result, comments_result, review_result) = tokio::join!(
641            check_merged_prs(
642                backend,
643                repo,
644                store,
645                task_manager,
646                &in_review_tasks,
647                &combined_needs,
648            ),
649            fetch_comments_since(backend, &shared_since),
650            async {
651                let gh = match GhHttp::new() {
652                    Ok(g) => g,
653                    Err(e) => {
654                        tracing::warn!(err = %e, "failed to create GitHub HTTP client for review poll");
655                        return Ok(());
656                    }
657                };
658                Box::pin(review_open_prs(
659                    backend,
660                    repo,
661                    config,
662                    task_manager,
663                    store,
664                    dispatching,
665                    auto_merge_in_flight,
666                    &in_review_tasks,
667                    &gh,
668                    &cached_router_config,
669                ))
670                .await
671            }
672        );
673
674        if let Err(e) = merge_result {
675            tracing::warn!(err = %e, "PR merge check failed");
676        }
677
678        match comments_result {
679            Ok(comments) => {
680                let filtered = filter_mentions_by_since(&comments, &mention_since);
681
682                if let Err(e) =
683                    scan_comments(backend, Some(store), repo, task_manager, Some(&filtered)).await
684                {
685                    tracing::warn!(err = %e, "comment scan failed");
686                }
687            }
688            Err(e) => {
689                tracing::warn!(err = %e, "comment fetch failed");
690            }
691        }
692
693        if let Err(e) = review_result {
694            tracing::warn!(err = %e, "PR review failed");
695        }
696
697        if let Err(e) = bootstrap::apply_pending(store, task_manager, repo).await {
698            tracing::warn!(err = %e, "CI bootstrap ruleset apply failed");
699        }
700
701        phases.push(("merge_comments_review", at.elapsed().as_millis()));
702    }
703    at = Instant::now();
704
705    // 5. Stale InReview recovery lives in `tick_recover_stuck_tasks`, the single owner of an
706    // in_review task whose review session is gone or hung. It ran here too, after one minute,
707    // which beat a finished review's result to the engine and dropped it as stale
708
709    // 5c. Detect stale InProgress tasks and recover them.
710    //
711    // Similar to stale InReview detection, we check for InProgress tasks whose
712    // agent tmux session has died (crash, OOM, etc.) and reset them to Routed
713    // so they can be re-dispatched.
714    let in_progress_tasks: Vec<_> = match store.list_by_status(repo, TaskStatus::InProgress).await {
715        Ok(tasks) => tasks
716            .into_iter()
717            .map(|stored| {
718                let external = tasks::store_task_to_external(&stored);
719                (stored, external)
720            })
721            .collect(),
722        Err(e) => {
723            tracing::warn!(err = %e, "failed to list in_progress tasks — skipping stale InProgress check");
724            vec![]
725        }
726    };
727
728    if !in_progress_tasks.is_empty() {
729        // Fetch all live tmux sessions once instead of one subprocess call per task.
730        let live_sessions: HashSet<String> = tmux
731            .list_sessions()
732            .await
733            .unwrap_or_default()
734            .into_iter()
735            .map(|s| s.name)
736            .collect();
737
738        for (_stored, external) in &in_progress_tasks {
739            // A task is only considered stale if it has been in InProgress for > 5 minutes.
740            const MIN_STALE_MINUTES: i64 = 5;
741
742            let task_id = &external.id.0;
743
744            // Skip tasks currently being processed by the main tick (dispatch + agent flow).
745            let dispatch_key = format!("{repo}/{task_id}");
746            {
747                if dispatching.contains_key(&dispatch_key) {
748                    tracing::debug!(
749                        task_id = %task_id,
750                        "task locked by dispatch flow, skipping stale check"
751                    );
752                    continue;
753                }
754            }
755
756            // Skip tasks that just transitioned to InProgress — allow time for the
757            // agent to start its tmux session before treating it as stale.
758            match chrono::DateTime::parse_from_rfc3339(&external.updated_at) {
759                Ok(updated_at) => {
760                    let age = chrono::Utc::now() - updated_at.with_timezone(&chrono::Utc);
761                    if age.num_minutes() < MIN_STALE_MINUTES {
762                        tracing::debug!(
763                            task_id = %task_id,
764                            age_seconds = age.num_seconds(),
765                            "InProgress task is too young to be considered stale, skipping"
766                        );
767                        continue;
768                    }
769                }
770                Err(e) => {
771                    tracing::warn!(
772                        task_id = %task_id,
773                        ts = %external.updated_at,
774                        err = %e,
775                        "invalid updated_at timestamp — treating task as potentially stale"
776                    );
777                }
778            }
779
780            let agent_session = tmux.session_name(repo, task_id);
781            if live_sessions.contains(&agent_session) {
782                // Agent is still alive — skip.
783                continue;
784            }
785
786            // No agent session exists. The agent is dead regardless of
787            // session tracking — hard restart, crash, or flag not persisted.
788            // Reset to Routed so the dispatcher can re-spawn it.
789            {
790                tracing::warn!(
791                    task_id = %task_id,
792                    session = %agent_session,
793                    "InProgress task has no active agent session — resetting to Routed"
794                );
795                match task_manager
796                    .update_task_status_if(&external.id, Status::Routed, Status::InProgress)
797                    .await
798                {
799                    Err(e) => {
800                        tracing::error!(task_id = %task_id, err = %e, "failed to reset stale InProgress task — task may be stuck in InProgress indefinitely");
801                    }
802                    Ok(false) => {
803                        tracing::debug!(
804                            task_id = %task_id,
805                            "stale InProgress reset skipped — task already transitioned (concurrent Done/Blocked/NeedsReview)"
806                        );
807                    }
808                    Ok(true) => {
809                        // Successfully reset to Routed
810                    }
811                }
812            }
813        }
814    }
815
816    phases.push(("stale_in_progress", at.elapsed().as_millis()));
817    at = Instant::now();
818    // 5c. Auto-unblock tasks with recoverable failures.
819    if let Err(e) =
820        auto_unblock_blocked_tasks(repo, task_manager, store, dispatching, auto_merge_in_flight)
821            .await
822    {
823        tracing::warn!(err = %e, "auto-unblock failed");
824    }
825
826    phases.push(("auto_unblock", at.elapsed().as_millis()));
827
828    engine::log_phase_timings("sync", repo, &phases);
829    Ok(())
830}
831
832/**
833 * Agent health is the same whichever project asks, so it runs once per sync pass rather than
834 * once per project. Called after every project's `sync_tick`
835 **/
836pub(crate) async fn sync_shared_tail(router: &Arc<RwLock<Router>>, store: Option<&Arc<TaskStore>>) {
837    let Some(store) = store else {
838        return;
839    };
840    if !store.is_leader() {
841        return;
842    }
843
844    // Pre-emptive health check: refresh degraded-agent flags from the rate_limits table.
845    // Clone what is needed out of the router first, so the write lock is not starved for the
846    // duration of the DB query
847    let (available_agents, config) = {
848        let r = router.read().await;
849        (r.available_agents.clone(), r.config.clone())
850    };
851    let model_checker = |agent: &str| -> bool {
852        for comp in &["simple", "medium", "complex", "review"] {
853            if config.has_available_model_for_complexity(agent, comp) {
854                return true;
855            }
856        }
857        false
858    };
859    refresh_degraded_agents(
860        store,
861        &available_agents,
862        &model_checker,
863        router_config::health_check_window_hours(),
864        router_config::degraded_rate_limit_threshold(),
865    )
866    .await;
867
868    emit_degraded_agents_if_needed(&available_agents, &config, Some(store)).await;
869}
870
871/// Per-agent degradation detail collected during the alerting check.
872struct DegradedAgentDetail {
873    /// Agent name (e.g. "claude", "codex").
874    agent: String,
875    /// Reason the agent is degraded: the stored cooldown reason when the agent
876    /// itself is in cooldown, or `"no_available_model"` when all model pools
877    /// are individually cooled.
878    reason: String,
879    /// Models that are individually in cooldown for this agent, deduped across
880    /// all complexity tiers.
881    cooled_models: Vec<String>,
882}
883
884/// Per-agent pool health used for stale model pool detection.
885struct AgentPoolHealth {
886    agent: String,
887    cooled_models: Vec<String>,
888    persistent_failed_models: Vec<String>,
889    total_configured_models: usize,
890}
891
892/// Inspect router & cooldown state and emit metrics every tick.
893///
894/// - `metrics:orch.agents_degraded.count` is written on every call with the
895///   current number of degraded agents (0 when healthy).
896/// - When `count >= 3` a WARN log is emitted with full dimensions (agent
897///   names, cooled models, cooldown reasons) and a dedicated alert metric
898///   `metrics:orch.agents_degraded.alert` is set to `"1"`. The alert is
899///   cleared to `"0"` when the count drops below the threshold.
900pub(crate) async fn emit_degraded_agents_if_needed(
901    available_agents: &[String],
902    config: &RouterConfig,
903    store: Option<&Arc<TaskStore>>,
904) {
905    // Edge-triggered: only log when the affected-agents set changes, so a
906    // persistent condition doesn't flood the log every sync tick.
907    const STALE_AGENTS_KV: &str = "metrics:orch.model_pool_stale_persistent.agents";
908
909    // Complexity tiers to check for configured models.
910    const COMPLEXITIES: &[&str] = &["simple", "medium", "complex", "review"];
911    const HEAVILY_COOLED_RATIO_THRESHOLD: f64 = 0.5;
912
913    let mut details: Vec<DegradedAgentDetail> = Vec::new();
914    let mut pool_health: Vec<AgentPoolHealth> = Vec::new();
915
916    for agent in available_agents {
917        let agent_in_cd = is_agent_in_cooldown(agent);
918
919        // Collect individually cooled models across all complexity tiers (deduped).
920        let mut cooled_models: Vec<String> = Vec::new();
921        let mut persistent_failed_models: Vec<String> = Vec::new();
922        let mut seen_models = HashSet::new();
923        for comp in COMPLEXITIES {
924            if let Some(pool) = config.model_pool_for_complexity(agent, comp) {
925                for model in pool {
926                    if seen_models.insert(model.clone()) && is_model_in_cooldown(agent, &model) {
927                        let key = format!("{agent}:{model}");
928                        if matches!(
929                            cooldown_reason(&key).as_deref(),
930                            Some("persistent_model_error" | "model_not_found")
931                        ) {
932                            persistent_failed_models.push(model.clone());
933                        }
934                        cooled_models.push(model);
935                    }
936                }
937            }
938        }
939        let total_configured_models = seen_models.len();
940        pool_health.push(AgentPoolHealth {
941            agent: agent.clone(),
942            cooled_models: cooled_models.clone(),
943            persistent_failed_models: persistent_failed_models.clone(),
944            total_configured_models,
945        });
946
947        // An agent is degraded if it is in agent-level cooldown OR has no
948        // available (non-cooled) model across any complexity tier.
949        let has_model = COMPLEXITIES
950            .iter()
951            .any(|comp| config.has_available_model_for_complexity(agent, comp));
952
953        if agent_in_cd || !has_model {
954            let reason = if agent_in_cd {
955                cooldown_reason(agent).unwrap_or_else(|| "agent_cooldown".to_string())
956            } else {
957                "no_available_model".to_string()
958            };
959            details.push(DegradedAgentDetail {
960                agent: agent.clone(),
961                reason,
962                cooled_models,
963            });
964        }
965    }
966
967    let count = details.len();
968
969    // Always persist the count metric so operators can scrape it every tick,
970    // including when the count is 0.
971    if let Err(e) = try_kv_set_prefer_store(
972        store,
973        "metrics:orch.agents_degraded.count",
974        &count.to_string(),
975    )
976    .await
977    {
978        tracing::warn!(err = %e, "failed to persist degraded agents count metric");
979    }
980
981    if count >= 3 {
982        // Build structured dimension strings for the log.
983        let degraded_agents: Vec<&str> = details.iter().map(|d| d.agent.as_str()).collect();
984        let cooled_models_dim: Vec<String> = details
985            .iter()
986            .filter(|d| !d.cooled_models.is_empty())
987            .map(|d| format!("{}:[{}]", d.agent, d.cooled_models.join(",")))
988            .collect();
989        let reasons_dim: Vec<String> = details
990            .iter()
991            .map(|d| format!("{}={}", d.agent, d.reason))
992            .collect();
993
994        tracing::warn!(
995            degraded_count = count,
996            degraded_agents = ?degraded_agents,
997            cooled_models = %cooled_models_dim.join("; "),
998            cooldown_reasons = %reasons_dim.join("; "),
999            "multi-agent degradation detected"
1000        );
1001
1002        // Dedicated alert metric: "1" while the threshold is exceeded.
1003        if let Err(e) =
1004            try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "1").await
1005        {
1006            tracing::warn!(err = %e, "failed to persist degraded agents alert metric");
1007        }
1008    } else if let Err(e) =
1009        try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "0").await
1010    {
1011        // Clear the alert metric when healthy.
1012        tracing::warn!(err = %e, "failed to clear degraded agents alert metric");
1013    }
1014
1015    // Additional operator signal for dead/stale model pools:
1016    // alert when any agent has at least 50% of configured models cooled and at
1017    // least one persistent model failure marker in cooldown reason.
1018    let heavily_cooled_agents: Vec<String> = pool_health
1019        .iter()
1020        .filter_map(|d| {
1021            if d.total_configured_models == 0 || d.persistent_failed_models.is_empty() {
1022                return None;
1023            }
1024            #[expect(
1025                clippy::cast_precision_loss,
1026                reason = "model counts are far below 2^52"
1027            )]
1028            let ratio = d.cooled_models.len() as f64 / d.total_configured_models as f64;
1029            (ratio >= HEAVILY_COOLED_RATIO_THRESHOLD).then(|| {
1030                format!(
1031                    "{}:{}/{}:{}",
1032                    d.agent,
1033                    d.cooled_models.len(),
1034                    d.total_configured_models,
1035                    d.persistent_failed_models.join(",")
1036                )
1037            })
1038        })
1039        .collect();
1040
1041    let current_dim = heavily_cooled_agents.join(",");
1042    let prev_dim = kv_get_prefer_store(store, STALE_AGENTS_KV)
1043        .await
1044        .unwrap_or_default();
1045
1046    if heavily_cooled_agents.is_empty() {
1047        if !prev_dim.is_empty() {
1048            tracing::info!("agent model pool stale condition cleared");
1049        }
1050        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, "").await {
1051            tracing::warn!(err = %e, "failed to clear stale model pool agents state");
1052        }
1053        if let Err(e) =
1054            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "0")
1055                .await
1056        {
1057            tracing::warn!(err = %e, "failed to clear stale model pool alert metric");
1058        }
1059    } else {
1060        if current_dim != prev_dim {
1061            tracing::warn!(
1062                affected_agents = ?heavily_cooled_agents,
1063                "agent model pool appears stale: persistent model failures in heavily cooled pool"
1064            );
1065        }
1066        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, &current_dim).await {
1067            tracing::warn!(err = %e, "failed to persist stale model pool agents state");
1068        }
1069        if let Err(e) =
1070            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "1")
1071                .await
1072        {
1073            tracing::warn!(err = %e, "failed to persist stale model pool alert metric");
1074        }
1075    }
1076}
1077
1078/// Ingest all active external tasks into the unified SQLite store.
1079///
1080/// Upserts each task so the store stays in sync with the backend.
1081/// Fetches all open issues (including unlabeled ones) so newly created
1082/// issues appear in the store immediately, not only after they get a
1083/// `status:*` label.  This is best-effort — individual task failures
1084/// are logged and skipped.
1085pub(crate) async fn ingest_external_tasks(
1086    backend: &Arc<dyn ExternalBackend>,
1087    repo: &str,
1088    store: &Arc<TaskStore>,
1089) -> anyhow::Result<()> {
1090    #[derive(Clone)]
1091    struct DuplicateTarget {
1092        id: String,
1093        status_label: String,
1094    }
1095
1096    let mut existing_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
1097    let mut accepted_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
1098
1099    let cutoff = (chrono::Utc::now() - chrono::Duration::hours(24))
1100        .format("%Y-%m-%dT%H:%M:%SZ")
1101        .to_string();
1102    match store.list_for_doctor(repo, &cutoff).await {
1103        Ok(recent) => {
1104            let mut insert_target = |task: &Task| {
1105                if task.origin == "internal" {
1106                    return;
1107                }
1108                let Some(ext_id) = task.external_id.as_ref() else {
1109                    return;
1110                };
1111                let status_label = task
1112                    .labels
1113                    .iter()
1114                    .find(|l| l.starts_with("status:"))
1115                    .cloned()
1116                    .unwrap_or_default();
1117                existing_by_title
1118                    .entry(task.title.clone())
1119                    .or_insert(DuplicateTarget {
1120                        id: ext_id.clone(),
1121                        status_label,
1122                    });
1123            };
1124
1125            // Prefer active tasks over recently done ones when selecting a canonical issue.
1126            for task in recent.iter().filter(|t| t.status != TaskStatus::Done) {
1127                insert_target(task);
1128            }
1129            for task in recent.iter().filter(|t| t.status == TaskStatus::Done) {
1130                insert_target(task);
1131            }
1132        }
1133        Err(e) => {
1134            tracing::warn!(repo, err = %e, "ingest: failed to load recent tasks for dedup");
1135        }
1136    }
1137
1138    // Fetch every open issue, with no `since` filter. The GitHub backend overrides
1139    // list_active_open_issues() to use one list_all_open_issues() request.
1140    //
1141    // A `since` cursor keys on updated_at, so an open issue with no task was skipped
1142    // forever once the cursor passed its updated_at, and the cursor had to be reset,
1143    // sentinelled and periodically ignored to recover (#3545, #3787, #3792). An
1144    // unfiltered listing has no such state and is cheaper too: its URL repeats, so
1145    // `get_all_pages` sends it conditionally and GitHub answers 304 while nothing
1146    // changed. A 304 does not count against the REST quota, a `since` fetch does.
1147    let all_tasks: Vec<(ExternalTask, Option<Status>)> =
1148        match backend.list_active_open_issues().await {
1149            Ok(tasks) => tasks,
1150            Err(e) => {
1151                tracing::warn!(
1152                    repo,
1153                    err = %e,
1154                    "ingest: failed to list open issues — no new issue is ingested this cycle"
1155                );
1156                return Ok(());
1157            }
1158        };
1159
1160    // Upsert into the store, collecting store IDs for batch status check
1161    // Also acknowledge newly detected issues (eyes reaction).
1162    let mut id_status_pairs: Vec<(i64, Status)> = Vec::new();
1163    // Collect (store_id, node_id) for newly ingested tasks so we can batch-fetch
1164    // estimate values from GitHub Projects after the loop.
1165    let mut new_task_node_ids: Vec<(i64, String)> = Vec::new();
1166    // Pre-load existing external IDs for this repo to avoid N+1 queries
1167    // (each get_by_external_id call is an individual SQL query). If the
1168    // lookup fails, fall back to an empty set so we conservatively treat
1169    // tasks as new (they will be upserted below).
1170    let existing_ext_ids: HashSet<String> = match store.existing_external_ids(repo).await {
1171        Ok(s) => s,
1172        Err(e) => {
1173            tracing::warn!(repo = repo, err = %e, "ingest: failed to load existing external ids — proceeding");
1174            HashSet::new()
1175        }
1176    };
1177    for (task, status) in &all_tasks {
1178        // Check if this task already exists in the store before upserting.
1179        // Use the pre-loaded HashSet to avoid issuing N individual queries.
1180        let is_new = !existing_ext_ids.contains(&task.id.0);
1181
1182        if is_new {
1183            let duplicate_target = existing_by_title
1184                .get(&task.title)
1185                .or_else(|| accepted_by_title.get(&task.title));
1186            if let Some(target) = duplicate_target
1187                && target.id != task.id.0
1188            {
1189                let label = target.status_label.as_str();
1190                let should_dedupe =
1191                    match backend.has_open_issue_with_title(&task.title, label).await {
1192                        Ok(true) => true,
1193                        Ok(false) => false,
1194                        Err(e) => {
1195                            tracing::warn!(
1196                                task_id = task.id.0,
1197                                err = %e,
1198                                "ingest: dedup check failed — defaulting to keep issue"
1199                            );
1200                            false
1201                        }
1202                    };
1203
1204                if should_dedupe {
1205                    let comment = format!(
1206                        "Duplicate of #{id} — closing to avoid duplicate work.{footer}",
1207                        id = target.id,
1208                        footer = engine::orch_footer()
1209                    );
1210                    if let Err(e) = backend.post_comment(&task.id, &comment).await {
1211                        tracing::warn!(
1212                            task_id = task.id.0,
1213                            err = %e,
1214                            "ingest: failed to comment on duplicate issue"
1215                        );
1216                    }
1217                    match backend.update_status(&task.id, Status::Done).await {
1218                        Ok(()) => {
1219                            tracing::info!(
1220                                task_id = task.id.0,
1221                                duplicate_of = target.id,
1222                                "ingest: closed duplicate issue"
1223                            );
1224                            continue;
1225                        }
1226                        Err(e) => {
1227                            tracing::warn!(
1228                                task_id = task.id.0,
1229                                err = %e,
1230                                "ingest: failed to close duplicate issue — falling through to ingest normally"
1231                            );
1232                        }
1233                    }
1234                }
1235            }
1236        }
1237
1238        match store.upsert_external(&task.upsert_row(repo)).await {
1239            Ok(store_id) => {
1240                if let Ok(number) = task.id.0.parse::<i64>()
1241                    && let Err(err) = dependencies::sync_issue_dependencies(
1242                        backend.as_ref(),
1243                        store,
1244                        store_id,
1245                        repo,
1246                        Some(number),
1247                        &task.body,
1248                    )
1249                    .await
1250                {
1251                    tracing::warn!(
1252                        task_id = task.id.0,
1253                        err = %err,
1254                        "ingest: dependency sync failed"
1255                    );
1256                }
1257                if let Some(s) = status {
1258                    id_status_pairs.push((store_id, *s));
1259                }
1260                // Acknowledge newly detected issues with an eyes reaction.
1261                if is_new {
1262                    let status_label = task
1263                        .labels
1264                        .iter()
1265                        .find(|l| l.starts_with("status:"))
1266                        .cloned()
1267                        .unwrap_or_default();
1268                    accepted_by_title
1269                        .entry(task.title.clone())
1270                        .or_insert(DuplicateTarget {
1271                            id: task.id.0.clone(),
1272                            status_label,
1273                        });
1274                    if let Err(e) = backend.acknowledge_issue(&task.id).await {
1275                        tracing::debug!(
1276                            task_id = task.id.0,
1277                            err = %e,
1278                            "ingest: acknowledgment failed"
1279                        );
1280                    }
1281                    // Sync to project board only for newly ingested tasks.
1282                    // Collect the returned node_id so we can batch-fetch estimates.
1283                    let task_status = status.unwrap_or(Status::New);
1284                    match backend.sync_to_project(&task.id, task_status).await {
1285                        Ok(Some(node_id)) => {
1286                            new_task_node_ids.push((store_id, node_id));
1287                        }
1288                        Ok(None) => {
1289                            // Project sync not configured or failed — no node_id to collect.
1290                        }
1291                        Err(e) => {
1292                            tracing::debug!(
1293                                task_id = task.id.0,
1294                                err = %e,
1295                                "ingest: project board sync failed"
1296                            );
1297                        }
1298                    }
1299                }
1300            }
1301            Err(e) => {
1302                tracing::debug!(task_id = task.id.0, ?e, "ingest: upsert failed");
1303            }
1304        }
1305    }
1306
1307    // Batch-fetch all upserted tasks in a single query, then sync status for NEW tasks.
1308    // Only sync status from backend → store for NEW tasks (first ingest).
1309    // Once a task exists in the store, its status is authoritative —
1310    // re-ingestion must not overwrite store-first status changes
1311    // (e.g., store has Routed but GitHub still shows New labels).
1312    if !id_status_pairs.is_empty() {
1313        let all_ids: Vec<i64> = id_status_pairs.iter().map(|(id, _)| *id).collect();
1314        let existing_map = match store.get_batch(&all_ids).await {
1315            Ok(map) => map,
1316            Err(e) => {
1317                tracing::warn!(err = %e, task_count = all_ids.len(), "ingest: get_batch failed — skipping initial status sync for newly ingested tasks this tick");
1318                return Ok(());
1319            }
1320        };
1321        for (store_id, status) in id_status_pairs {
1322            if let Some(existing) = existing_map.get(&store_id)
1323                && existing.status == TaskStatus::New
1324            {
1325                let db_status = status_to_task_status(status);
1326                if db_status != TaskStatus::New
1327                    && let Err(e) = store.update_status(store_id, db_status).await
1328                {
1329                    tracing::debug!(?e, "ingest: status sync failed");
1330                }
1331            }
1332        }
1333    }
1334
1335    // Batch-fetch estimate values from GitHub Projects for newly ingested tasks.
1336    // For each task where `tasks.estimate == 0`, populate it from the project board.
1337    if !new_task_node_ids.is_empty() {
1338        let node_ids: Vec<String> = new_task_node_ids.iter().map(|(_, n)| n.clone()).collect();
1339        match backend.get_project_item_estimates(&node_ids).await {
1340            Ok(estimates) => {
1341                for (store_id, node_id) in new_task_node_ids {
1342                    if let Some(&estimate) = estimates.get(&node_id)
1343                        && estimate > 0
1344                        && let Err(e) = store.set_estimate_if_zero(store_id, estimate).await
1345                    {
1346                        tracing::debug!(
1347                            store_id,
1348                            estimate,
1349                            err = %e,
1350                            "ingest: failed to set estimate from project"
1351                        );
1352                    }
1353                }
1354            }
1355            Err(e) => {
1356                tracing::debug!(
1357                    err = %e,
1358                    "ingest: project estimate fetch failed — skipping estimate sync this tick"
1359                );
1360            }
1361        }
1362    }
1363
1364    Ok(())
1365}
1366
1367#[cfg(test)]
1368mod tests;
1369
1370#[cfg(test)]
1371mod unblock_tests;
1372
1373#[cfg(test)]
1374mod comments_tests;