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