use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::mpsc::{self, Receiver, SyncSender, TryRecvError, TrySendError};
use std::time::{Duration, Instant};

use crate::audit::{DiscoveredFrom, PublicationPointAudit};
use crate::parallel::object_worker::ObjectWorkerSubmitError;
use crate::parallel::repo_runtime::{RepoSyncRequestStatus, RepoSyncRuntimeOutcome};
use crate::parallel::types::RepoIdentity;
use crate::policy::SignedObjectFailurePolicy;
use crate::report::Warning;
use crate::validation::objects::{
    ObjectsOutput, OwnedRoaTask, ParallelObjectsPrepare, ParallelObjectsStage,
    prepare_publication_point_for_parallel_roa, reduce_parallel_roa_stage,
};
use crate::validation::tree::{
    CaInstanceHandle, DiscoveredChildCaInstance, PublicationPointRunResult, PublicationPointRunner,
    TreeRunAuditOutput, TreeRunConfig, TreeRunError, TreeRunOutput,
    run_tree_serial_audit_multi_root,
};
use crate::validation::tree_runner::{FreshPublicationPointStage, Rpkiv1PublicationPointRunner};

#[derive(Clone, Debug)]
struct QueuedCaInstance {
    id: u64,
    handle: CaInstanceHandle,
    parent_id: Option<u64>,
    discovered_from: Option<DiscoveredFrom>,
}

#[derive(Clone, Debug)]
struct ReadyCaInstance {
    node: QueuedCaInstance,
    repo_outcome: RepoSyncRuntimeOutcome,
}

struct InflightPublicationPoint {
    node: QueuedCaInstance,
    fresh_stage: FreshPublicationPointStage,
    objects_stage: ParallelObjectsStage,
    repo_outcome: RepoSyncRuntimeOutcome,
    warnings: Vec<Warning>,
    started_at: Instant,
    objects_started_at: Instant,
    task_count: usize,
    tasks_submitted: usize,
    first_task_submitted_at: Option<Instant>,
    last_task_submitted_at: Option<Instant>,
    first_result_at: Option<Instant>,
    last_result_at: Option<Instant>,
    worker_ms_total: u64,
    worker_ms_max: u64,
    queue_wait_ms_total: u64,
    queue_wait_ms_max: u64,
    results: Vec<crate::validation::objects::RoaTaskResult>,
}

struct FinishedPublicationPoint {
    node: QueuedCaInstance,
    result: Result<PublicationPointRunResult, String>,
}

struct FinalizeTask {
    state: InflightPublicationPoint,
}

struct FinalizeWorkerResult {
    finished: FinishedPublicationPoint,
    metrics: FinalizePublicationPointMetrics,
}

#[derive(Default)]
struct ReadyStageMetrics {
    manifest_rsync_uri: Option<String>,
    publication_point_rsync_uri: Option<String>,
    ready_count: usize,
    fallback_count: usize,
    complete_count: usize,
    staged_count: usize,
    zero_task_count: usize,
    error_count: usize,
    discovered_children: usize,
    locked_files: usize,
    roa_tasks: usize,
    aspa_objects: usize,
    stage_fresh_ms: u64,
    snapshot_prepare_ms: u64,
    snapshot_current_index_lock_ms: u64,
    snapshot_manifest_load_ms: u64,
    snapshot_manifest_index_lookup_ms: u64,
    snapshot_manifest_blob_load_ms: u64,
    snapshot_manifest_decode_ms: u64,
    snapshot_replay_guard_ms: u64,
    replay_meta_hit_count: usize,
    replay_meta_miss_count: usize,
    snapshot_manifest_entries_ms: u64,
    snapshot_pack_files_ms: u64,
    snapshot_pack_files_index_lookup_ms: u64,
    snapshot_pack_files_blob_load_ms: u64,
    snapshot_ee_path_validate_ms: u64,
    snapshot_manifest_file_count: usize,
    child_discovery_ms: u64,
    child_enqueue_ms: u64,
    prepare_ms: u64,
    build_roa_tasks_ms: u64,
    total_ms: u64,
}

#[derive(Default)]
struct ReadyStageBatchMetrics {
    ready_count: usize,
    fallback_count: usize,
    complete_count: usize,
    staged_count: usize,
    zero_task_count: usize,
    error_count: usize,
    discovered_children: usize,
    locked_files: usize,
    roa_tasks: usize,
    aspa_objects: usize,
    stage_fresh_ms_total: u64,
    stage_fresh_ms_max: u64,
    stage_fresh_ms_max_manifest_rsync_uri: Option<String>,
    stage_fresh_ms_max_publication_point_rsync_uri: Option<String>,
    snapshot_prepare_ms_total: u64,
    snapshot_prepare_ms_max: u64,
    snapshot_current_index_lock_ms_total: u64,
    snapshot_current_index_lock_ms_max: u64,
    snapshot_manifest_load_ms_total: u64,
    snapshot_manifest_load_ms_max: u64,
    snapshot_manifest_index_lookup_ms_total: u64,
    snapshot_manifest_index_lookup_ms_max: u64,
    snapshot_manifest_blob_load_ms_total: u64,
    snapshot_manifest_blob_load_ms_max: u64,
    snapshot_manifest_decode_ms_total: u64,
    snapshot_manifest_decode_ms_max: u64,
    snapshot_replay_guard_ms_total: u64,
    snapshot_replay_guard_ms_max: u64,
    replay_meta_hit_count: usize,
    replay_meta_miss_count: usize,
    snapshot_manifest_entries_ms_total: u64,
    snapshot_manifest_entries_ms_max: u64,
    snapshot_pack_files_ms_total: u64,
    snapshot_pack_files_ms_max: u64,
    snapshot_pack_files_index_lookup_ms_total: u64,
    snapshot_pack_files_index_lookup_ms_max: u64,
    snapshot_pack_files_blob_load_ms_total: u64,
    snapshot_pack_files_blob_load_ms_max: u64,
    snapshot_ee_path_validate_ms_total: u64,
    snapshot_ee_path_validate_ms_max: u64,
    snapshot_manifest_file_count_total: usize,
    snapshot_manifest_file_count_max: usize,
    child_discovery_ms_total: u64,
    child_discovery_ms_max: u64,
    child_enqueue_ms_total: u64,
    child_enqueue_ms_max: u64,
    prepare_ms_total: u64,
    prepare_ms_max: u64,
    build_roa_tasks_ms_total: u64,
    build_roa_tasks_ms_max: u64,
    total_ms: u64,
}

impl ReadyStageBatchMetrics {
    fn record(&mut self, metrics: ReadyStageMetrics) {
        self.ready_count += metrics.ready_count;
        self.fallback_count += metrics.fallback_count;
        self.complete_count += metrics.complete_count;
        self.staged_count += metrics.staged_count;
        self.zero_task_count += metrics.zero_task_count;
        self.error_count += metrics.error_count;
        self.discovered_children += metrics.discovered_children;
        self.locked_files += metrics.locked_files;
        self.roa_tasks += metrics.roa_tasks;
        self.aspa_objects += metrics.aspa_objects;
        if metrics.stage_fresh_ms >= self.stage_fresh_ms_max {
            self.stage_fresh_ms_max_manifest_rsync_uri = metrics.manifest_rsync_uri.clone();
            self.stage_fresh_ms_max_publication_point_rsync_uri =
                metrics.publication_point_rsync_uri.clone();
        }
        self.stage_fresh_ms_total += metrics.stage_fresh_ms;
        self.stage_fresh_ms_max = self.stage_fresh_ms_max.max(metrics.stage_fresh_ms);
        self.snapshot_prepare_ms_total += metrics.snapshot_prepare_ms;
        self.snapshot_prepare_ms_max = self
            .snapshot_prepare_ms_max
            .max(metrics.snapshot_prepare_ms);
        self.snapshot_current_index_lock_ms_total += metrics.snapshot_current_index_lock_ms;
        self.snapshot_current_index_lock_ms_max = self
            .snapshot_current_index_lock_ms_max
            .max(metrics.snapshot_current_index_lock_ms);
        self.snapshot_manifest_load_ms_total += metrics.snapshot_manifest_load_ms;
        self.snapshot_manifest_load_ms_max = self
            .snapshot_manifest_load_ms_max
            .max(metrics.snapshot_manifest_load_ms);
        self.snapshot_manifest_index_lookup_ms_total += metrics.snapshot_manifest_index_lookup_ms;
        self.snapshot_manifest_index_lookup_ms_max = self
            .snapshot_manifest_index_lookup_ms_max
            .max(metrics.snapshot_manifest_index_lookup_ms);
        self.snapshot_manifest_blob_load_ms_total += metrics.snapshot_manifest_blob_load_ms;
        self.snapshot_manifest_blob_load_ms_max = self
            .snapshot_manifest_blob_load_ms_max
            .max(metrics.snapshot_manifest_blob_load_ms);
        self.snapshot_manifest_decode_ms_total += metrics.snapshot_manifest_decode_ms;
        self.snapshot_manifest_decode_ms_max = self
            .snapshot_manifest_decode_ms_max
            .max(metrics.snapshot_manifest_decode_ms);
        self.snapshot_replay_guard_ms_total += metrics.snapshot_replay_guard_ms;
        self.snapshot_replay_guard_ms_max = self
            .snapshot_replay_guard_ms_max
            .max(metrics.snapshot_replay_guard_ms);
        self.replay_meta_hit_count += metrics.replay_meta_hit_count;
        self.replay_meta_miss_count += metrics.replay_meta_miss_count;
        self.snapshot_manifest_entries_ms_total += metrics.snapshot_manifest_entries_ms;
        self.snapshot_manifest_entries_ms_max = self
            .snapshot_manifest_entries_ms_max
            .max(metrics.snapshot_manifest_entries_ms);
        self.snapshot_pack_files_ms_total += metrics.snapshot_pack_files_ms;
        self.snapshot_pack_files_ms_max = self
            .snapshot_pack_files_ms_max
            .max(metrics.snapshot_pack_files_ms);
        self.snapshot_pack_files_index_lookup_ms_total +=
            metrics.snapshot_pack_files_index_lookup_ms;
        self.snapshot_pack_files_index_lookup_ms_max = self
            .snapshot_pack_files_index_lookup_ms_max
            .max(metrics.snapshot_pack_files_index_lookup_ms);
        self.snapshot_pack_files_blob_load_ms_total += metrics.snapshot_pack_files_blob_load_ms;
        self.snapshot_pack_files_blob_load_ms_max = self
            .snapshot_pack_files_blob_load_ms_max
            .max(metrics.snapshot_pack_files_blob_load_ms);
        self.snapshot_ee_path_validate_ms_total += metrics.snapshot_ee_path_validate_ms;
        self.snapshot_ee_path_validate_ms_max = self
            .snapshot_ee_path_validate_ms_max
            .max(metrics.snapshot_ee_path_validate_ms);
        self.snapshot_manifest_file_count_total += metrics.snapshot_manifest_file_count;
        self.snapshot_manifest_file_count_max = self
            .snapshot_manifest_file_count_max
            .max(metrics.snapshot_manifest_file_count);
        self.child_discovery_ms_total += metrics.child_discovery_ms;
        self.child_discovery_ms_max = self.child_discovery_ms_max.max(metrics.child_discovery_ms);
        self.child_enqueue_ms_total += metrics.child_enqueue_ms;
        self.child_enqueue_ms_max = self.child_enqueue_ms_max.max(metrics.child_enqueue_ms);
        self.prepare_ms_total += metrics.prepare_ms;
        self.prepare_ms_max = self.prepare_ms_max.max(metrics.prepare_ms);
        self.build_roa_tasks_ms_total += metrics.build_roa_tasks_ms;
        self.build_roa_tasks_ms_max = self.build_roa_tasks_ms_max.max(metrics.build_roa_tasks_ms);
        self.total_ms += metrics.total_ms;
    }
}

#[derive(Default)]
struct RoaDispatchMetrics {
    attempted: usize,
    submitted: usize,
    queue_full: bool,
    pending_remaining: usize,
    duration_ms: u64,
}

#[derive(Default)]
struct ObjectDrainMetrics {
    results_drained: usize,
    publication_points_completed: usize,
    worker_ms_total: u64,
    worker_ms_max: u64,
    queue_wait_ms_total: u64,
    queue_wait_ms_max: u64,
    result_budget_exhausted: bool,
    duration_ms: u64,
}

#[derive(Default)]
struct FinalizeSubmitMetrics {
    submitted: usize,
    queue_full: bool,
    duration_ms: u64,
}

#[derive(Default)]
struct FinalizePublicationPointMetrics {
    reduce_ms: u64,
    finalize_ms: u64,
    finalize_queue_wait_ms: Option<u64>,
    finalize_worker_ms: u64,
}

#[derive(Default)]
struct FinalizeResultsDrainMetrics {
    results_drained: usize,
    reduce_ms_total: u64,
    reduce_ms_max: u64,
    finalize_ms_total: u64,
    finalize_ms_max: u64,
    finalize_queue_wait_ms_max: u64,
    finalize_worker_ms_total: u64,
    finalize_worker_ms_max: u64,
    duration_ms: u64,
}

#[derive(Default)]
struct RepoDrainMetrics {
    event_count: usize,
    completions: usize,
    ready_enqueued: usize,
    duration_ms: u64,
}

fn elapsed_ms(started: Instant) -> u64 {
    started.elapsed().as_millis() as u64
}

fn compact_phase2_finished_result(
    mut result: PublicationPointRunResult,
    compact_audit: bool,
) -> PublicationPointRunResult {
    // Phase2 only needs warnings, objects, audit, and traversal metadata after finalize.
    // Dropping the snapshot here avoids retaining manifest/files/raw-byte caches until run end.
    result.snapshot = None;
    if compact_audit {
        result.audit.objects.clear();
        result.audit.warnings.clear();
        result.objects.audit.clear();
        result.discovered_children.clear();
    }
    result
}

fn compact_phase2_finished_result_result(
    result: Result<PublicationPointRunResult, String>,
    compact_audit: bool,
) -> Result<PublicationPointRunResult, String> {
    result.map(|result| compact_phase2_finished_result(result, compact_audit))
}

pub fn run_tree_parallel_phase2_audit_multi_root(
    roots: Vec<CaInstanceHandle>,
    runner: &Rpkiv1PublicationPointRunner<'_>,
    config: &TreeRunConfig,
) -> Result<TreeRunAuditOutput, TreeRunError> {
    if runner.policy.signed_object_failure_policy == SignedObjectFailurePolicy::DropPublicationPoint
    {
        return run_tree_serial_audit_multi_root(roots, runner, config);
    }

    let Some(repo_runtime) = runner.repo_sync_runtime.as_ref() else {
        return run_tree_serial_audit_multi_root(roots, runner, config);
    };
    if runner.parallel_roa_worker_pool.is_none() {
        return run_tree_serial_audit_multi_root(roots, runner, config);
    }

    let mut next_id: u64 = 0;
    let mut ca_queue: VecDeque<QueuedCaInstance> = VecDeque::new();
    for root in roots {
        ca_queue.push_back(QueuedCaInstance {
            id: next_id,
            handle: root,
            parent_id: None,
            discovered_from: None,
        });
        next_id += 1;
    }

    let mut visited_manifest_uris: HashSet<String> = HashSet::new();
    let mut ca_waiting_repo_by_identity: HashMap<RepoIdentity, Vec<QueuedCaInstance>> =
        HashMap::new();
    let mut ready_queue: VecDeque<ReadyCaInstance> = VecDeque::new();
    let mut inflight_publication_points: HashMap<u64, InflightPublicationPoint> = HashMap::new();
    let mut pending_finalization: VecDeque<FinalizeTask> = VecDeque::new();
    let mut pending_roa_dispatch: VecDeque<OwnedRoaTask> = VecDeque::new();
    let mut finished: Vec<FinishedPublicationPoint> = Vec::new();
    let mut instances_started = 0usize;
    let phase2_config = runner.parallel_phase2_config.as_ref();
    let ready_batch_size = phase2_config
        .map(|cfg| cfg.ready_batch_size)
        .unwrap_or(256)
        .max(1);
    let ready_batch_wall_time_budget_ms = phase2_config
        .map(|cfg| cfg.ready_batch_wall_time_budget_ms)
        .unwrap_or(100)
        .max(1);
    let ready_batch_wall_time_budget = Duration::from_millis(ready_batch_wall_time_budget_ms);
    let object_result_drain_batch_size = phase2_config
        .map(|cfg| cfg.object_result_drain_batch_size)
        .unwrap_or(2048)
        .max(1);
    let publication_point_finalize_queue_capacity = phase2_config
        .map(|cfg| cfg.publication_point_finalize_queue_capacity)
        .unwrap_or(32768)
        .max(1);

    let (finalize_task_tx, finalize_task_rx) =
        mpsc::sync_channel::<FinalizeTask>(publication_point_finalize_queue_capacity);
    let (finalize_result_tx, finalize_result_rx) = mpsc::channel::<FinalizeWorkerResult>();
    let mut finalize_inflight = 0usize;

    return std::thread::scope(|scope| {
        let finalize_worker = scope.spawn(move || {
            run_finalize_worker(
                runner,
                finalize_task_rx,
                finalize_result_tx,
                config.compact_audit,
            )
        });

        let run_result: Result<(), TreeRunError> = (|| {
            loop {
                drain_finalize_results_with_progress(
                    &finalize_result_rx,
                    &mut finished,
                    &mut finalize_inflight,
                    pending_finalization.len(),
                    pending_roa_dispatch.len(),
                    inflight_publication_points.len(),
                )?;
                flush_pending_roa_dispatch_with_progress(
                    runner,
                    &mut pending_roa_dispatch,
                    &mut inflight_publication_points,
                    &pending_finalization,
                )?;
                drain_object_results_with_progress(
                    runner,
                    &mut inflight_publication_points,
                    &mut pending_finalization,
                    pending_roa_dispatch.len(),
                    object_result_drain_batch_size,
                )?;
                submit_pending_finalization_with_progress(
                    &finalize_task_tx,
                    &mut pending_finalization,
                    &mut finalize_inflight,
                    publication_point_finalize_queue_capacity,
                    pending_roa_dispatch.len(),
                    inflight_publication_points.len(),
                )?;

                start_queued_ca_instances(
                    repo_runtime.as_ref(),
                    &mut ca_queue,
                    &mut ready_queue,
                    &mut ca_waiting_repo_by_identity,
                    &mut finished,
                    &mut visited_manifest_uris,
                    &mut instances_started,
                    config,
                );

                let repo_poll_timeout = event_poll_timeout(
                    &ca_queue,
                    &ready_queue,
                    &pending_roa_dispatch,
                    &inflight_publication_points,
                    &pending_finalization,
                    finalize_inflight,
                    instances_started,
                    config,
                );
                let repo_metrics = drain_repo_events(
                    repo_runtime.as_ref(),
                    &mut ca_waiting_repo_by_identity,
                    &mut ready_queue,
                    repo_poll_timeout,
                )?;
                if repo_metrics.event_count > 0 {
                    crate::progress_log::emit(
                        "phase2_repo_events_drain",
                        serde_json::json!({
                            "event_count": repo_metrics.event_count,
                            "completions": repo_metrics.completions,
                            "ready_enqueued": repo_metrics.ready_enqueued,
                            "duration_ms": repo_metrics.duration_ms,
                            "ready_queue_len": ready_queue.len(),
                            "ca_waiting_repo_identities": ca_waiting_repo_by_identity.len(),
                        }),
                    );
                }

                let ready_batch_started = Instant::now();
                let mut ready_batch_metrics = ReadyStageBatchMetrics::default();
                let mut ready_time_budget_exhausted = false;
                while ready_batch_metrics.ready_count < ready_batch_size {
                    let Some(ready) = ready_queue.pop_front() else {
                        break;
                    };
                    let metrics = stage_ready_publication_point(
                        runner,
                        &mut next_id,
                        &mut ca_queue,
                        &mut pending_roa_dispatch,
                        &mut inflight_publication_points,
                        &mut finished,
                        ready,
                        config.compact_audit,
                    );
                    ready_batch_metrics.record(metrics);
                    if ready_batch_metrics.ready_count > 0
                        && ready_batch_started.elapsed() >= ready_batch_wall_time_budget
                    {
                        ready_time_budget_exhausted = !ready_queue.is_empty();
                        break;
                    }
                }
                if ready_batch_metrics.ready_count > 0 {
                    ready_batch_metrics.total_ms = elapsed_ms(ready_batch_started);
                    let ready_count_budget_exhausted = ready_batch_metrics.ready_count
                        >= ready_batch_size
                        && !ready_queue.is_empty();
                    ready_time_budget_exhausted = ready_time_budget_exhausted
                        || (!ready_queue.is_empty()
                            && ready_batch_metrics.total_ms >= ready_batch_wall_time_budget_ms);
                    crate::progress_log::emit(
                        "phase2_ready_queue_batch",
                        serde_json::json!({
                            "ready_count": ready_batch_metrics.ready_count,
                            "fallback_count": ready_batch_metrics.fallback_count,
                            "complete_count": ready_batch_metrics.complete_count,
                            "staged_count": ready_batch_metrics.staged_count,
                            "zero_task_count": ready_batch_metrics.zero_task_count,
                            "error_count": ready_batch_metrics.error_count,
                            "discovered_children": ready_batch_metrics.discovered_children,
                            "locked_files": ready_batch_metrics.locked_files,
                            "roa_tasks": ready_batch_metrics.roa_tasks,
                            "aspa_objects": ready_batch_metrics.aspa_objects,
                            "stage_fresh_ms_total": ready_batch_metrics.stage_fresh_ms_total,
                            "stage_fresh_ms_max": ready_batch_metrics.stage_fresh_ms_max,
                            "stage_fresh_ms_max_manifest_rsync_uri": ready_batch_metrics.stage_fresh_ms_max_manifest_rsync_uri,
                            "stage_fresh_ms_max_publication_point_rsync_uri": ready_batch_metrics.stage_fresh_ms_max_publication_point_rsync_uri,
                            "child_enqueue_ms_total": ready_batch_metrics.child_enqueue_ms_total,
                            "child_enqueue_ms_max": ready_batch_metrics.child_enqueue_ms_max,
                            "prepare_ms_total": ready_batch_metrics.prepare_ms_total,
                            "prepare_ms_max": ready_batch_metrics.prepare_ms_max,
                            "build_roa_tasks_ms_total": ready_batch_metrics.build_roa_tasks_ms_total,
                            "build_roa_tasks_ms_max": ready_batch_metrics.build_roa_tasks_ms_max,
                            "batch_duration_ms": ready_batch_metrics.total_ms,
                            "ready_batch_size": ready_batch_size,
                            "ready_batch_wall_time_budget_ms": ready_batch_wall_time_budget_ms,
                            "ready_queue_len_after_batch": ready_queue.len(),
                            "ready_queue_budget_exhausted": !ready_queue.is_empty(),
                            "ready_count_budget_exhausted": ready_count_budget_exhausted,
                            "ready_time_budget_exhausted": ready_time_budget_exhausted,
                            "ca_queue_len_after_batch": ca_queue.len(),
                            "pending_roa_dispatch_len_after_batch": pending_roa_dispatch.len(),
                            "inflight_publication_points_after_batch": inflight_publication_points.len(),
                            "pending_finalization_len_after_batch": pending_finalization.len(),
                            "finalize_inflight_after_batch": finalize_inflight,
                        }),
                    );
                    crate::progress_log::emit(
                        "phase2_ready_queue_stage_fresh_breakdown",
                        serde_json::json!({
                            "ready_count": ready_batch_metrics.ready_count,
                            "stage_fresh_ms_total": ready_batch_metrics.stage_fresh_ms_total,
                            "stage_fresh_ms_max": ready_batch_metrics.stage_fresh_ms_max,
                            "stage_fresh_ms_max_manifest_rsync_uri": ready_batch_metrics.stage_fresh_ms_max_manifest_rsync_uri,
                            "stage_fresh_ms_max_publication_point_rsync_uri": ready_batch_metrics.stage_fresh_ms_max_publication_point_rsync_uri,
                            "snapshot_prepare_ms_total": ready_batch_metrics.snapshot_prepare_ms_total,
                            "snapshot_prepare_ms_max": ready_batch_metrics.snapshot_prepare_ms_max,
                            "snapshot_current_index_lock_ms_total": ready_batch_metrics.snapshot_current_index_lock_ms_total,
                            "snapshot_current_index_lock_ms_max": ready_batch_metrics.snapshot_current_index_lock_ms_max,
                            "snapshot_manifest_load_ms_total": ready_batch_metrics.snapshot_manifest_load_ms_total,
                            "snapshot_manifest_load_ms_max": ready_batch_metrics.snapshot_manifest_load_ms_max,
                            "snapshot_manifest_index_lookup_ms_total": ready_batch_metrics.snapshot_manifest_index_lookup_ms_total,
                            "snapshot_manifest_index_lookup_ms_max": ready_batch_metrics.snapshot_manifest_index_lookup_ms_max,
                            "snapshot_manifest_blob_load_ms_total": ready_batch_metrics.snapshot_manifest_blob_load_ms_total,
                            "snapshot_manifest_blob_load_ms_max": ready_batch_metrics.snapshot_manifest_blob_load_ms_max,
                            "snapshot_manifest_decode_ms_total": ready_batch_metrics.snapshot_manifest_decode_ms_total,
                            "snapshot_manifest_decode_ms_max": ready_batch_metrics.snapshot_manifest_decode_ms_max,
                            "snapshot_replay_guard_ms_total": ready_batch_metrics.snapshot_replay_guard_ms_total,
                            "snapshot_replay_guard_ms_max": ready_batch_metrics.snapshot_replay_guard_ms_max,
                            "replay_meta_hit_count": ready_batch_metrics.replay_meta_hit_count,
                            "replay_meta_miss_count": ready_batch_metrics.replay_meta_miss_count,
                            "snapshot_manifest_entries_ms_total": ready_batch_metrics.snapshot_manifest_entries_ms_total,
                            "snapshot_manifest_entries_ms_max": ready_batch_metrics.snapshot_manifest_entries_ms_max,
                            "snapshot_pack_files_ms_total": ready_batch_metrics.snapshot_pack_files_ms_total,
                            "snapshot_pack_files_ms_max": ready_batch_metrics.snapshot_pack_files_ms_max,
                            "snapshot_pack_files_index_lookup_ms_total": ready_batch_metrics.snapshot_pack_files_index_lookup_ms_total,
                            "snapshot_pack_files_index_lookup_ms_max": ready_batch_metrics.snapshot_pack_files_index_lookup_ms_max,
                            "snapshot_pack_files_blob_load_ms_total": ready_batch_metrics.snapshot_pack_files_blob_load_ms_total,
                            "snapshot_pack_files_blob_load_ms_max": ready_batch_metrics.snapshot_pack_files_blob_load_ms_max,
                            "snapshot_ee_path_validate_ms_total": ready_batch_metrics.snapshot_ee_path_validate_ms_total,
                            "snapshot_ee_path_validate_ms_max": ready_batch_metrics.snapshot_ee_path_validate_ms_max,
                            "snapshot_manifest_file_count_total": ready_batch_metrics.snapshot_manifest_file_count_total,
                            "snapshot_manifest_file_count_max": ready_batch_metrics.snapshot_manifest_file_count_max,
                            "child_discovery_ms_total": ready_batch_metrics.child_discovery_ms_total,
                            "child_discovery_ms_max": ready_batch_metrics.child_discovery_ms_max,
                            "batch_duration_ms": ready_batch_metrics.total_ms,
                        }),
                    );
                }

                flush_pending_roa_dispatch_with_progress(
                    runner,
                    &mut pending_roa_dispatch,
                    &mut inflight_publication_points,
                    &pending_finalization,
                )?;
                drain_object_results_with_progress(
                    runner,
                    &mut inflight_publication_points,
                    &mut pending_finalization,
                    pending_roa_dispatch.len(),
                    object_result_drain_batch_size,
                )?;
                submit_pending_finalization_with_progress(
                    &finalize_task_tx,
                    &mut pending_finalization,
                    &mut finalize_inflight,
                    publication_point_finalize_queue_capacity,
                    pending_roa_dispatch.len(),
                    inflight_publication_points.len(),
                )?;
                drain_finalize_results_with_progress(
                    &finalize_result_rx,
                    &mut finished,
                    &mut finalize_inflight,
                    pending_finalization.len(),
                    pending_roa_dispatch.len(),
                    inflight_publication_points.len(),
                )?;

                if is_complete(
                    &ca_queue,
                    &ready_queue,
                    &ca_waiting_repo_by_identity,
                    &pending_roa_dispatch,
                    &inflight_publication_points,
                    &pending_finalization,
                    finalize_inflight,
                    instances_started,
                    config,
                ) {
                    break;
                }
            }

            repo_runtime
                .reset_run_state()
                .map_err(TreeRunError::Runner)?;
            Ok(())
        })();

        drop(finalize_task_tx);
        let worker_result = finalize_worker
            .join()
            .map_err(|_| TreeRunError::Runner("phase2 finalize worker panicked".to_string()))?;
        run_result?;
        worker_result?;
        drain_finalize_results_with_progress(
            &finalize_result_rx,
            &mut finished,
            &mut finalize_inflight,
            pending_finalization.len(),
            pending_roa_dispatch.len(),
            inflight_publication_points.len(),
        )?;
        if finalize_inflight != 0 || !pending_finalization.is_empty() {
            return Err(TreeRunError::Runner(format!(
                "phase2 finalize worker stopped with pending work: queued={} inflight={}",
                pending_finalization.len(),
                finalize_inflight
            )));
        }
        Ok(build_tree_output(finished))
    });
}

fn can_start_more(instances_started: usize, config: &TreeRunConfig) -> bool {
    config
        .max_instances
        .map(|max| instances_started < max)
        .unwrap_or(true)
}

fn start_queued_ca_instances(
    repo_runtime: &dyn crate::parallel::repo_runtime::RepoSyncRuntime,
    ca_queue: &mut VecDeque<QueuedCaInstance>,
    ready_queue: &mut VecDeque<ReadyCaInstance>,
    ca_waiting_repo_by_identity: &mut HashMap<RepoIdentity, Vec<QueuedCaInstance>>,
    finished: &mut Vec<FinishedPublicationPoint>,
    visited_manifest_uris: &mut HashSet<String>,
    instances_started: &mut usize,
    config: &TreeRunConfig,
) {
    while can_start_more(*instances_started, config) {
        let Some(node) = ca_queue.pop_front() else {
            break;
        };
        if !visited_manifest_uris.insert(node.handle.manifest_rsync_uri.clone()) {
            continue;
        }
        if let Some(max_depth) = config.max_depth {
            if node.handle.depth > max_depth {
                continue;
            }
        }
        *instances_started += 1;
        match repo_runtime.request_publication_point_repo(&node.handle, 0) {
            Ok(RepoSyncRequestStatus::Ready { mut outcome, .. }) => {
                // Ready here means this CA is reusing repo work that has already completed
                // (often due to child prefetch). Do not add the transport duration again.
                outcome.repo_sync_duration_ms = 0;
                ready_queue.push_back(ReadyCaInstance {
                    node,
                    repo_outcome: outcome,
                });
            }
            Ok(RepoSyncRequestStatus::Pending { identity, .. }) => {
                ca_waiting_repo_by_identity
                    .entry(identity)
                    .or_default()
                    .push(node);
            }
            Err(err) => {
                finished.push(FinishedPublicationPoint {
                    node,
                    result: Err(err),
                });
            }
        }
    }
}

fn stage_ready_publication_point(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    next_id: &mut u64,
    ca_queue: &mut VecDeque<QueuedCaInstance>,
    pending_roa_dispatch: &mut VecDeque<OwnedRoaTask>,
    inflight_publication_points: &mut HashMap<u64, InflightPublicationPoint>,
    finished: &mut Vec<FinishedPublicationPoint>,
    ready: ReadyCaInstance,
    compact_audit: bool,
) -> ReadyStageMetrics {
    let publication_point_started = Instant::now();
    let mut metrics = ReadyStageMetrics {
        ready_count: 1,
        manifest_rsync_uri: Some(ready.node.handle.manifest_rsync_uri.clone()),
        publication_point_rsync_uri: Some(ready.node.handle.publication_point_rsync_uri.clone()),
        ..ReadyStageMetrics::default()
    };
    let mut warnings = ready.repo_outcome.warnings.clone();
    let repo_outcome = ready.repo_outcome.clone();
    let stage_fresh_started = Instant::now();
    let stage = runner.stage_fresh_publication_point_after_repo_ready(
        &ready.node.handle,
        repo_outcome.repo_sync_ok,
        repo_outcome.repo_sync_err.as_deref(),
    );
    metrics.stage_fresh_ms = elapsed_ms(stage_fresh_started);

    let fresh_stage = match stage {
        Ok(stage) => stage,
        Err(err) => {
            if metrics.stage_fresh_ms >= crate::progress_log::stage_fresh_slow_threshold_ms() {
                crate::progress_log::emit(
                    "phase2_stage_fresh_slow",
                    serde_json::json!({
                        "manifest_rsync_uri": ready.node.handle.manifest_rsync_uri.as_str(),
                        "publication_point_rsync_uri": ready.node.handle.publication_point_rsync_uri.as_str(),
                        "status": "error",
                        "error": err.error.to_string(),
                        "stage_fresh_ms": metrics.stage_fresh_ms,
                        "snapshot_prepare_ms": err.snapshot_prepare_ms,
                        "repo_sync_source": repo_outcome.repo_sync_source.as_deref(),
                        "repo_sync_phase": repo_outcome.repo_sync_phase.as_deref(),
                        "repo_sync_duration_ms": repo_outcome.repo_sync_duration_ms,
                    }),
                );
            }
            metrics.fallback_count = 1;
            let fallback = runner.run_publication_point(&ready.node.handle);
            if let Ok(result) = fallback.as_ref() {
                metrics.discovered_children = result.discovered_children.len();
                let child_enqueue_started = Instant::now();
                enqueue_discovered_children(
                    runner,
                    next_id,
                    ca_queue,
                    &ready.node,
                    result.discovered_children.clone(),
                );
                metrics.child_enqueue_ms = elapsed_ms(child_enqueue_started);
            }
            finished.push(FinishedPublicationPoint {
                node: ready.node,
                result: compact_phase2_finished_result_result(fallback, compact_audit),
            });
            metrics.total_ms = elapsed_ms(publication_point_started);
            return metrics;
        }
    };
    metrics.snapshot_prepare_ms = fresh_stage.snapshot_prepare_ms;
    metrics.snapshot_current_index_lock_ms =
        fresh_stage.snapshot_prepare_timing.current_index_lock_ms;
    metrics.snapshot_manifest_load_ms = fresh_stage.snapshot_prepare_timing.manifest_load_ms;
    metrics.snapshot_manifest_index_lookup_ms =
        fresh_stage.snapshot_prepare_timing.manifest_index_lookup_ms;
    metrics.snapshot_manifest_blob_load_ms =
        fresh_stage.snapshot_prepare_timing.manifest_blob_load_ms;
    metrics.snapshot_manifest_decode_ms = fresh_stage.snapshot_prepare_timing.manifest_decode_ms;
    metrics.snapshot_replay_guard_ms = fresh_stage.snapshot_prepare_timing.replay_guard_ms;
    metrics.replay_meta_hit_count = fresh_stage.snapshot_prepare_timing.replay_meta_hit as usize;
    metrics.replay_meta_miss_count = fresh_stage.snapshot_prepare_timing.replay_meta_miss as usize;
    metrics.snapshot_manifest_entries_ms = fresh_stage.snapshot_prepare_timing.manifest_entries_ms;
    metrics.snapshot_pack_files_ms = fresh_stage.snapshot_prepare_timing.pack_files_ms;
    metrics.snapshot_pack_files_index_lookup_ms = fresh_stage
        .snapshot_prepare_timing
        .pack_files_index_lookup_ms;
    metrics.snapshot_pack_files_blob_load_ms =
        fresh_stage.snapshot_prepare_timing.pack_files_blob_load_ms;
    metrics.snapshot_ee_path_validate_ms = fresh_stage.snapshot_prepare_timing.ee_path_validate_ms;
    metrics.snapshot_manifest_file_count = fresh_stage.snapshot_prepare_timing.manifest_file_count;
    metrics.child_discovery_ms = fresh_stage.child_discovery_ms;
    if metrics.stage_fresh_ms >= crate::progress_log::stage_fresh_slow_threshold_ms() {
        crate::progress_log::emit(
            "phase2_stage_fresh_slow",
            serde_json::json!({
                "manifest_rsync_uri": ready.node.handle.manifest_rsync_uri.as_str(),
                "publication_point_rsync_uri": ready.node.handle.publication_point_rsync_uri.as_str(),
                "status": "ok",
                "stage_fresh_ms": metrics.stage_fresh_ms,
                "snapshot_prepare_ms": fresh_stage.snapshot_prepare_ms,
                "snapshot_current_index_lock_ms": fresh_stage.snapshot_prepare_timing.current_index_lock_ms,
                "snapshot_manifest_load_ms": fresh_stage.snapshot_prepare_timing.manifest_load_ms,
                "snapshot_manifest_index_lookup_ms": fresh_stage.snapshot_prepare_timing.manifest_index_lookup_ms,
                "snapshot_manifest_blob_load_ms": fresh_stage.snapshot_prepare_timing.manifest_blob_load_ms,
                "snapshot_manifest_decode_ms": fresh_stage.snapshot_prepare_timing.manifest_decode_ms,
                "snapshot_replay_guard_ms": fresh_stage.snapshot_prepare_timing.replay_guard_ms,
                "replay_meta_hit": fresh_stage.snapshot_prepare_timing.replay_meta_hit,
                "replay_meta_miss": fresh_stage.snapshot_prepare_timing.replay_meta_miss,
                "snapshot_manifest_entries_ms": fresh_stage.snapshot_prepare_timing.manifest_entries_ms,
                "snapshot_pack_files_ms": fresh_stage.snapshot_prepare_timing.pack_files_ms,
                "snapshot_pack_files_index_lookup_ms": fresh_stage.snapshot_prepare_timing.pack_files_index_lookup_ms,
                "snapshot_pack_files_blob_load_ms": fresh_stage.snapshot_prepare_timing.pack_files_blob_load_ms,
                "snapshot_ee_path_validate_ms": fresh_stage.snapshot_prepare_timing.ee_path_validate_ms,
                "snapshot_manifest_file_count": fresh_stage.snapshot_prepare_timing.manifest_file_count,
                "child_discovery_ms": fresh_stage.child_discovery_ms,
                "child_count": fresh_stage.discovered_children.len(),
                "repo_sync_source": repo_outcome.repo_sync_source.as_deref(),
                "repo_sync_phase": repo_outcome.repo_sync_phase.as_deref(),
                "repo_sync_duration_ms": repo_outcome.repo_sync_duration_ms,
            }),
        );
    }
    warnings.extend(fresh_stage.warnings.clone());

    metrics.discovered_children = fresh_stage.discovered_children.len();
    let child_enqueue_started = Instant::now();
    enqueue_discovered_children(
        runner,
        next_id,
        ca_queue,
        &ready.node,
        fresh_stage.discovered_children.clone(),
    );
    metrics.child_enqueue_ms = elapsed_ms(child_enqueue_started);

    let prepare_started = Instant::now();
    match prepare_publication_point_for_parallel_roa(
        ready.node.id,
        &fresh_stage.fresh_point,
        runner.policy,
        &ready.node.handle.ca_certificate_der,
        ready.node.handle.ca_certificate_rsync_uri.as_deref(),
        ready.node.handle.effective_ip_resources.as_ref(),
        ready.node.handle.effective_as_resources.as_ref(),
        runner.validation_time,
        runner.persist_vcir,
    ) {
        ParallelObjectsPrepare::Complete(mut objects) => {
            metrics.prepare_ms = elapsed_ms(prepare_started);
            metrics.complete_count = 1;
            metrics.roa_tasks = objects.stats.roa_total;
            metrics.aspa_objects = objects.stats.aspa_total;
            objects
                .router_keys
                .extend(fresh_stage.discovered_router_keys.clone());
            objects.local_outputs_cache.extend(
                crate::validation::tree_runner::build_router_key_local_outputs(
                    &ready.node.handle,
                    &objects.router_keys,
                ),
            );
            finalize_ready_objects(
                runner,
                ready.node,
                fresh_stage,
                warnings,
                objects,
                repo_outcome,
                finished,
                compact_audit,
            );
        }
        ParallelObjectsPrepare::Staged(objects_stage) => {
            metrics.prepare_ms = elapsed_ms(prepare_started);
            metrics.staged_count = 1;
            metrics.locked_files = objects_stage.locked_file_count();
            metrics.aspa_objects = objects_stage.aspa_task_count();
            let build_tasks_started = Instant::now();
            let tasks = objects_stage.build_roa_tasks();
            metrics.build_roa_tasks_ms = elapsed_ms(build_tasks_started);
            let task_count = objects_stage.roa_task_count();
            metrics.roa_tasks = task_count;
            for task in tasks {
                pending_roa_dispatch.push_back(task);
            }
            if task_count == 0 {
                metrics.zero_task_count = 1;
                match reduce_parallel_roa_stage(objects_stage, Vec::new(), runner.timing.as_ref()) {
                    Ok(mut objects) => {
                        objects
                            .router_keys
                            .extend(fresh_stage.discovered_router_keys.clone());
                        objects.local_outputs_cache.extend(
                            crate::validation::tree_runner::build_router_key_local_outputs(
                                &ready.node.handle,
                                &objects.router_keys,
                            ),
                        );
                        finalize_ready_objects(
                            runner,
                            ready.node,
                            fresh_stage,
                            warnings,
                            objects,
                            repo_outcome,
                            finished,
                            compact_audit,
                        );
                    }
                    Err(err) => finished.push(FinishedPublicationPoint {
                        node: ready.node,
                        result: Err(err),
                    }),
                }
            } else {
                inflight_publication_points.insert(
                    ready.node.id,
                    InflightPublicationPoint {
                        node: ready.node,
                        fresh_stage,
                        objects_stage,
                        repo_outcome,
                        warnings,
                        started_at: publication_point_started,
                        objects_started_at: Instant::now(),
                        task_count,
                        tasks_submitted: 0,
                        first_task_submitted_at: None,
                        last_task_submitted_at: None,
                        first_result_at: None,
                        last_result_at: None,
                        worker_ms_total: 0,
                        worker_ms_max: 0,
                        queue_wait_ms_total: 0,
                        queue_wait_ms_max: 0,
                        results: Vec::with_capacity(task_count),
                    },
                );
            }
        }
    }
    metrics.total_ms = elapsed_ms(publication_point_started);
    metrics
}

fn enqueue_discovered_children(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    next_id: &mut u64,
    ca_queue: &mut VecDeque<QueuedCaInstance>,
    parent: &QueuedCaInstance,
    mut children: Vec<DiscoveredChildCaInstance>,
) {
    children.sort_by(|a, b| {
        a.handle
            .manifest_rsync_uri
            .cmp(&b.handle.manifest_rsync_uri)
            .then_with(|| {
                a.discovered_from
                    .child_ca_certificate_rsync_uri
                    .cmp(&b.discovered_from.child_ca_certificate_rsync_uri)
            })
    });
    if let Some(runtime) = runner.repo_sync_runtime.as_ref() {
        let _ = runtime.prefetch_discovered_children(&children);
    }
    for child in children {
        let mut handle = child.handle.with_depth(parent.handle.depth + 1);
        handle.parent_manifest_rsync_uri = Some(parent.handle.manifest_rsync_uri.clone());
        ca_queue.push_back(QueuedCaInstance {
            id: *next_id,
            handle,
            parent_id: Some(parent.id),
            discovered_from: Some(child.discovered_from),
        });
        *next_id += 1;
    }
}

fn finalize_ready_objects(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    node: QueuedCaInstance,
    fresh_stage: FreshPublicationPointStage,
    warnings: Vec<Warning>,
    objects: ObjectsOutput,
    repo_outcome: RepoSyncRuntimeOutcome,
    finished: &mut Vec<FinishedPublicationPoint>,
    compact_audit: bool,
) {
    let result = runner
        .finalize_fresh_publication_point_from_reducer(
            &node.handle,
            &fresh_stage.fresh_point,
            warnings,
            objects,
            fresh_stage.child_audits,
            fresh_stage.discovered_children,
            repo_outcome.repo_sync_source.as_deref(),
            repo_outcome.repo_sync_phase.as_deref(),
            repo_outcome.repo_sync_duration_ms,
            repo_outcome.repo_sync_err.as_deref(),
        )
        .map(|out| out.result);
    finished.push(FinishedPublicationPoint {
        node,
        result: compact_phase2_finished_result_result(result, compact_audit),
    });
}

fn flush_pending_roa_dispatch(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    pending_roa_dispatch: &mut VecDeque<OwnedRoaTask>,
    inflight_publication_points: &mut HashMap<u64, InflightPublicationPoint>,
) -> Result<RoaDispatchMetrics, TreeRunError> {
    let started = Instant::now();
    let mut metrics = RoaDispatchMetrics::default();
    let Some(pool) = runner.parallel_roa_worker_pool.as_ref() else {
        return Ok(metrics);
    };
    while let Some(mut task) = pending_roa_dispatch.pop_front() {
        metrics.attempted += 1;
        let pp_id = task.publication_point_id;
        task.submitted_at = Some(Instant::now());
        match pool.try_submit_round_robin(task) {
            Ok(_) => {
                metrics.submitted += 1;
                if let Some(state) = inflight_publication_points.get_mut(&pp_id) {
                    let now = Instant::now();
                    state.tasks_submitted += 1;
                    if state.first_task_submitted_at.is_none() {
                        state.first_task_submitted_at = Some(now);
                    }
                    state.last_task_submitted_at = Some(now);
                }
            }
            Err(ObjectWorkerSubmitError::QueueFull { task, .. }) => {
                pending_roa_dispatch.push_front(task);
                metrics.queue_full = true;
                break;
            }
            Err(ObjectWorkerSubmitError::Disconnected { .. }) => {
                return Err(TreeRunError::Runner(
                    "parallel ROA worker queue disconnected".to_string(),
                ));
            }
        }
    }
    metrics.pending_remaining = pending_roa_dispatch.len();
    metrics.duration_ms = elapsed_ms(started);
    Ok(metrics)
}

fn flush_pending_roa_dispatch_with_progress(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    pending_roa_dispatch: &mut VecDeque<OwnedRoaTask>,
    inflight_publication_points: &mut HashMap<u64, InflightPublicationPoint>,
    pending_finalization: &VecDeque<FinalizeTask>,
) -> Result<(), TreeRunError> {
    let dispatch_metrics =
        flush_pending_roa_dispatch(runner, pending_roa_dispatch, inflight_publication_points)?;
    if dispatch_metrics.attempted > 0 || dispatch_metrics.queue_full {
        crate::progress_log::emit(
            "phase2_roa_dispatch_batch",
            serde_json::json!({
                "attempted": dispatch_metrics.attempted,
                "submitted": dispatch_metrics.submitted,
                "queue_full": dispatch_metrics.queue_full,
                "pending_remaining": dispatch_metrics.pending_remaining,
                "duration_ms": dispatch_metrics.duration_ms,
                "inflight_publication_points": inflight_publication_points.len(),
                "pending_finalization_len": pending_finalization.len(),
            }),
        );
    }
    Ok(())
}

fn drain_object_results(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    inflight_publication_points: &mut HashMap<u64, InflightPublicationPoint>,
    pending_finalization: &mut VecDeque<FinalizeTask>,
    result_budget: usize,
) -> Result<ObjectDrainMetrics, TreeRunError> {
    let started = Instant::now();
    let mut metrics = ObjectDrainMetrics::default();
    let Some(pool) = runner.parallel_roa_worker_pool.as_ref() else {
        return Ok(metrics);
    };
    let result_budget = result_budget.max(1);
    while metrics.results_drained < result_budget {
        let Some(result) = pool
            .recv_result_timeout(Duration::from_millis(0))
            .map_err(TreeRunError::Runner)?
        else {
            break;
        };
        metrics.results_drained += 1;
        let pp_id = result.publication_point_id;
        let _worker_index = result.worker_index;
        metrics.worker_ms_total += result.worker_ms;
        metrics.worker_ms_max = metrics.worker_ms_max.max(result.worker_ms);
        metrics.queue_wait_ms_total += result.queue_wait_ms;
        metrics.queue_wait_ms_max = metrics.queue_wait_ms_max.max(result.queue_wait_ms);
        let should_finalize = if let Some(state) = inflight_publication_points.get_mut(&pp_id) {
            let now = Instant::now();
            if state.first_result_at.is_none() {
                state.first_result_at = Some(now);
            }
            state.last_result_at = Some(now);
            state.worker_ms_total += result.worker_ms;
            state.worker_ms_max = state.worker_ms_max.max(result.worker_ms);
            state.queue_wait_ms_total += result.queue_wait_ms;
            state.queue_wait_ms_max = state.queue_wait_ms_max.max(result.queue_wait_ms);
            state.results.push(result);
            state.results.len() == state.task_count
        } else {
            false
        };
        if should_finalize {
            let state = inflight_publication_points
                .remove(&pp_id)
                .expect("inflight publication point must exist");
            metrics.publication_points_completed += 1;
            pending_finalization.push_back(FinalizeTask { state });
        }
    }
    metrics.result_budget_exhausted = metrics.results_drained == result_budget;
    metrics.duration_ms = elapsed_ms(started);
    Ok(metrics)
}

fn drain_object_results_with_progress(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    inflight_publication_points: &mut HashMap<u64, InflightPublicationPoint>,
    pending_finalization: &mut VecDeque<FinalizeTask>,
    pending_roa_dispatch_len: usize,
    result_budget: usize,
) -> Result<(), TreeRunError> {
    let drain_metrics = drain_object_results(
        runner,
        inflight_publication_points,
        pending_finalization,
        result_budget,
    )?;
    if drain_metrics.results_drained > 0 || drain_metrics.result_budget_exhausted {
        crate::progress_log::emit(
            "phase2_object_results_drain",
            serde_json::json!({
                "results_drained": drain_metrics.results_drained,
                "publication_points_completed": drain_metrics.publication_points_completed,
                "result_budget_exhausted": drain_metrics.result_budget_exhausted,
                "result_drain_batch_size": result_budget,
                "worker_ms_total": drain_metrics.worker_ms_total,
                "worker_ms_max": drain_metrics.worker_ms_max,
                "queue_wait_ms_total": drain_metrics.queue_wait_ms_total,
                "queue_wait_ms_max": drain_metrics.queue_wait_ms_max,
                "duration_ms": drain_metrics.duration_ms,
                "pending_roa_dispatch_len": pending_roa_dispatch_len,
                "inflight_publication_points": inflight_publication_points.len(),
                "pending_finalization_len": pending_finalization.len(),
            }),
        );
    }
    Ok(())
}

fn submit_pending_finalization(
    finalize_task_tx: &SyncSender<FinalizeTask>,
    pending_finalization: &mut VecDeque<FinalizeTask>,
    finalize_inflight: &mut usize,
) -> Result<FinalizeSubmitMetrics, TreeRunError> {
    let started = Instant::now();
    let mut metrics = FinalizeSubmitMetrics::default();
    while let Some(task) = pending_finalization.pop_front() {
        match finalize_task_tx.try_send(task) {
            Ok(()) => {
                metrics.submitted += 1;
                *finalize_inflight += 1;
            }
            Err(TrySendError::Full(task)) => {
                pending_finalization.push_front(task);
                metrics.queue_full = true;
                break;
            }
            Err(TrySendError::Disconnected(_task)) => {
                return Err(TreeRunError::Runner(
                    "phase2 finalize worker queue disconnected".to_string(),
                ));
            }
        }
    }
    metrics.duration_ms = elapsed_ms(started);
    Ok(metrics)
}

fn submit_pending_finalization_with_progress(
    finalize_task_tx: &SyncSender<FinalizeTask>,
    pending_finalization: &mut VecDeque<FinalizeTask>,
    finalize_inflight: &mut usize,
    finalize_queue_capacity: usize,
    pending_roa_dispatch_len: usize,
    inflight_publication_points_len: usize,
) -> Result<(), TreeRunError> {
    let submit_metrics =
        submit_pending_finalization(finalize_task_tx, pending_finalization, finalize_inflight)?;
    if submit_metrics.submitted > 0 || submit_metrics.queue_full {
        crate::progress_log::emit(
            "phase2_finalize_task_submit",
            serde_json::json!({
                "submitted": submit_metrics.submitted,
                "queue_full": submit_metrics.queue_full,
                "duration_ms": submit_metrics.duration_ms,
                "finalize_queue_capacity": finalize_queue_capacity,
                "pending_finalization_len": pending_finalization.len(),
                "finalize_inflight": *finalize_inflight,
                "pending_roa_dispatch_len": pending_roa_dispatch_len,
                "inflight_publication_points": inflight_publication_points_len,
            }),
        );
    }
    Ok(())
}

fn drain_finalize_results(
    finalize_result_rx: &Receiver<FinalizeWorkerResult>,
    finished: &mut Vec<FinishedPublicationPoint>,
    finalize_inflight: &mut usize,
) -> Result<FinalizeResultsDrainMetrics, TreeRunError> {
    let started = Instant::now();
    let mut metrics = FinalizeResultsDrainMetrics::default();
    loop {
        match finalize_result_rx.try_recv() {
            Ok(result) => {
                metrics.results_drained += 1;
                metrics.reduce_ms_total += result.metrics.reduce_ms;
                metrics.reduce_ms_max = metrics.reduce_ms_max.max(result.metrics.reduce_ms);
                metrics.finalize_ms_total += result.metrics.finalize_ms;
                metrics.finalize_ms_max = metrics.finalize_ms_max.max(result.metrics.finalize_ms);
                metrics.finalize_queue_wait_ms_max = metrics
                    .finalize_queue_wait_ms_max
                    .max(result.metrics.finalize_queue_wait_ms.unwrap_or(0));
                metrics.finalize_worker_ms_total += result.metrics.finalize_worker_ms;
                metrics.finalize_worker_ms_max = metrics
                    .finalize_worker_ms_max
                    .max(result.metrics.finalize_worker_ms);
                *finalize_inflight = finalize_inflight.saturating_sub(1);
                finished.push(result.finished);
            }
            Err(TryRecvError::Empty) => break,
            Err(TryRecvError::Disconnected) => {
                if *finalize_inflight == 0 {
                    break;
                }
                return Err(TreeRunError::Runner(
                    "phase2 finalize result channel disconnected".to_string(),
                ));
            }
        }
    }
    metrics.duration_ms = elapsed_ms(started);
    Ok(metrics)
}

fn drain_finalize_results_with_progress(
    finalize_result_rx: &Receiver<FinalizeWorkerResult>,
    finished: &mut Vec<FinishedPublicationPoint>,
    finalize_inflight: &mut usize,
    pending_finalization_len: usize,
    pending_roa_dispatch_len: usize,
    inflight_publication_points_len: usize,
) -> Result<(), TreeRunError> {
    let drain_metrics = drain_finalize_results(finalize_result_rx, finished, finalize_inflight)?;
    if drain_metrics.results_drained >= 64
        || (drain_metrics.results_drained > 0
            && (*finalize_inflight == 0 || pending_finalization_len > 0))
    {
        crate::progress_log::emit(
            "phase2_finalize_results_drain",
            serde_json::json!({
                "results_drained": drain_metrics.results_drained,
                "reduce_ms_total": drain_metrics.reduce_ms_total,
                "reduce_ms_max": drain_metrics.reduce_ms_max,
                "finalize_ms_total": drain_metrics.finalize_ms_total,
                "finalize_ms_max": drain_metrics.finalize_ms_max,
                "finalize_queue_wait_ms_max": drain_metrics.finalize_queue_wait_ms_max,
                "finalize_worker_ms_total": drain_metrics.finalize_worker_ms_total,
                "finalize_worker_ms_max": drain_metrics.finalize_worker_ms_max,
                "duration_ms": drain_metrics.duration_ms,
                "pending_finalization_len": pending_finalization_len,
                "finalize_inflight": *finalize_inflight,
                "pending_roa_dispatch_len": pending_roa_dispatch_len,
                "inflight_publication_points": inflight_publication_points_len,
            }),
        );
    }
    Ok(())
}

fn run_finalize_worker(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    finalize_task_rx: Receiver<FinalizeTask>,
    finalize_result_tx: mpsc::Sender<FinalizeWorkerResult>,
    compact_audit: bool,
) -> Result<(), TreeRunError> {
    while let Ok(task) = finalize_task_rx.recv() {
        let result = finalize_publication_point_state(runner, task.state, compact_audit);
        if finalize_result_tx.send(result).is_err() {
            return Err(TreeRunError::Runner(
                "phase2 finalize result receiver disconnected".to_string(),
            ));
        }
    }
    Ok(())
}

fn finalize_publication_point_state(
    runner: &Rpkiv1PublicationPointRunner<'_>,
    state: InflightPublicationPoint,
    compact_audit: bool,
) -> FinalizeWorkerResult {
    let finalize_worker_started = Instant::now();
    let InflightPublicationPoint {
        node,
        fresh_stage,
        objects_stage,
        repo_outcome,
        warnings,
        started_at,
        objects_started_at,
        task_count,
        tasks_submitted,
        first_task_submitted_at,
        last_task_submitted_at,
        first_result_at,
        last_result_at,
        worker_ms_total,
        worker_ms_max,
        queue_wait_ms_total,
        queue_wait_ms_max,
        results,
    } = state;
    let finalize_queue_wait_ms = last_result_at.map(|last_result| {
        Instant::now()
            .saturating_duration_since(last_result)
            .as_millis() as u64
    });
    let objects_processing_ms = objects_started_at.elapsed().as_millis() as u64;
    let reduce_started = Instant::now();
    let reduce_result = reduce_parallel_roa_stage(objects_stage, results, runner.timing.as_ref());
    let reduce_ms = elapsed_ms(reduce_started);

    let (result, finalize_ms) = match reduce_result {
        Ok(mut objects) => {
            let finalize_started = Instant::now();
            objects
                .router_keys
                .extend(fresh_stage.discovered_router_keys.clone());
            objects.local_outputs_cache.extend(
                crate::validation::tree_runner::build_router_key_local_outputs(
                    &node.handle,
                    &objects.router_keys,
                ),
            );
            let result = runner
                .finalize_fresh_publication_point_from_reducer(
                    &node.handle,
                    &fresh_stage.fresh_point,
                    warnings,
                    objects,
                    fresh_stage.child_audits,
                    fresh_stage.discovered_children,
                    repo_outcome.repo_sync_source.as_deref(),
                    repo_outcome.repo_sync_phase.as_deref(),
                    repo_outcome.repo_sync_duration_ms,
                    repo_outcome.repo_sync_err.as_deref(),
                )
                .map(|out| out.result);
            (
                compact_phase2_finished_result_result(result, compact_audit),
                elapsed_ms(finalize_started),
            )
        }
        Err(err) => (Err(err), 0),
    };
    let finalize_worker_ms = elapsed_ms(finalize_worker_started);
    crate::progress_log::emit(
        "phase2_publication_point_reduced",
        serde_json::json!({
            "manifest_rsync_uri": node.handle.manifest_rsync_uri.as_str(),
            "publication_point_rsync_uri": node.handle.publication_point_rsync_uri.as_str(),
            "objects_processing_ms": objects_processing_ms,
            "task_count": task_count,
            "tasks_submitted": tasks_submitted,
            "first_task_submitted_ms": first_task_submitted_at.map(|t| t.saturating_duration_since(objects_started_at).as_millis() as u64),
            "last_task_submitted_ms": last_task_submitted_at.map(|t| t.saturating_duration_since(objects_started_at).as_millis() as u64),
            "task_submit_span_ms": match (first_task_submitted_at, last_task_submitted_at) {
                (Some(first), Some(last)) => Some(last.saturating_duration_since(first).as_millis() as u64),
                _ => None,
            },
            "first_result_ms": first_result_at.map(|t| t.saturating_duration_since(objects_started_at).as_millis() as u64),
            "last_result_ms": last_result_at.map(|t| t.saturating_duration_since(objects_started_at).as_millis() as u64),
            "all_results_ready_ms": last_result_at.map(|t| t.saturating_duration_since(objects_started_at).as_millis() as u64),
            "finalize_queue_wait_ms": finalize_queue_wait_ms,
            "result_span_ms": match (first_result_at, last_result_at) {
                (Some(first), Some(last)) => Some(last.saturating_duration_since(first).as_millis() as u64),
                _ => None,
            },
            "worker_ms_total": worker_ms_total,
            "worker_ms_max": worker_ms_max,
            "worker_ms_avg": if task_count > 0 { worker_ms_total / task_count as u64 } else { 0 },
            "queue_wait_ms_total": queue_wait_ms_total,
            "queue_wait_ms_max": queue_wait_ms_max,
            "queue_wait_ms_avg": if task_count > 0 { queue_wait_ms_total / task_count as u64 } else { 0 },
            "reduce_ms": reduce_ms,
            "finalize_ms": finalize_ms,
            "finalize_worker_ms": finalize_worker_ms,
            "total_duration_ms": started_at.elapsed().as_millis() as u64,
        }),
    );
    FinalizeWorkerResult {
        finished: FinishedPublicationPoint { node, result },
        metrics: FinalizePublicationPointMetrics {
            reduce_ms,
            finalize_ms,
            finalize_queue_wait_ms,
            finalize_worker_ms,
        },
    }
}

fn drain_repo_events(
    repo_runtime: &dyn crate::parallel::repo_runtime::RepoSyncRuntime,
    ca_waiting_repo_by_identity: &mut HashMap<RepoIdentity, Vec<QueuedCaInstance>>,
    ready_queue: &mut VecDeque<ReadyCaInstance>,
    timeout: Duration,
) -> Result<RepoDrainMetrics, TreeRunError> {
    let started = Instant::now();
    let mut metrics = RepoDrainMetrics::default();
    if let Some(event) = repo_runtime
        .recv_repo_result_timeout(timeout)
        .map_err(TreeRunError::Runner)?
    {
        metrics.event_count += 1;
        metrics.completions += event.completions.len();
        for completion in event.completions {
            let mut outcome = completion.outcome;
            if completion.identity != event.transport_identity {
                // Shared RRDP/rsync transports release many publication points, but the transport
                // wall time should only be counted once in per-PP stage timing aggregation.
                outcome.repo_sync_duration_ms = 0;
            }
            if let Some(waiters) = ca_waiting_repo_by_identity.remove(&completion.identity) {
                metrics.ready_enqueued += waiters.len();
                for node in waiters {
                    ready_queue.push_back(ReadyCaInstance {
                        node,
                        repo_outcome: outcome.clone(),
                    });
                }
            }
        }
    }
    metrics.duration_ms = elapsed_ms(started);
    Ok(metrics)
}

fn event_poll_timeout(
    ca_queue: &VecDeque<QueuedCaInstance>,
    ready_queue: &VecDeque<ReadyCaInstance>,
    pending_roa_dispatch: &VecDeque<OwnedRoaTask>,
    inflight_publication_points: &HashMap<u64, InflightPublicationPoint>,
    pending_finalization: &VecDeque<FinalizeTask>,
    finalize_inflight: usize,
    instances_started: usize,
    config: &TreeRunConfig,
) -> Duration {
    if !ready_queue.is_empty()
        || !pending_roa_dispatch.is_empty()
        || !inflight_publication_points.is_empty()
        || !pending_finalization.is_empty()
        || (!ca_queue.is_empty() && can_start_more(instances_started, config))
    {
        Duration::from_millis(0)
    } else if finalize_inflight > 0 {
        Duration::from_millis(10)
    } else {
        Duration::from_millis(50)
    }
}

fn is_complete(
    ca_queue: &VecDeque<QueuedCaInstance>,
    ready_queue: &VecDeque<ReadyCaInstance>,
    ca_waiting_repo_by_identity: &HashMap<RepoIdentity, Vec<QueuedCaInstance>>,
    pending_roa_dispatch: &VecDeque<OwnedRoaTask>,
    inflight_publication_points: &HashMap<u64, InflightPublicationPoint>,
    pending_finalization: &VecDeque<FinalizeTask>,
    finalize_inflight: usize,
    instances_started: usize,
    config: &TreeRunConfig,
) -> bool {
    let ca_queue_done = ca_queue.is_empty() || !can_start_more(instances_started, config);
    ca_queue_done
        && ready_queue.is_empty()
        && ca_waiting_repo_by_identity.is_empty()
        && pending_roa_dispatch.is_empty()
        && inflight_publication_points.is_empty()
        && pending_finalization.is_empty()
        && finalize_inflight == 0
}

fn build_tree_output(mut finished: Vec<FinishedPublicationPoint>) -> TreeRunAuditOutput {
    finished.sort_by_key(|item| item.node.id);
    let mut instances_processed = 0usize;
    let mut instances_failed = 0usize;
    let mut warnings = Vec::new();
    let mut vrps = Vec::new();
    let mut aspas = Vec::new();
    let mut router_keys = Vec::new();
    let mut publication_points = Vec::new();

    for item in finished {
        match item.result {
            Ok(result) => {
                instances_processed += 1;
                warnings.extend(result.warnings);
                warnings.extend(result.objects.warnings);
                vrps.extend(result.objects.vrps);
                aspas.extend(result.objects.aspas);
                router_keys.extend(result.objects.router_keys);

                let mut audit: PublicationPointAudit = result.audit;
                audit.node_id = Some(item.node.id);
                audit.parent_node_id = item.node.parent_id;
                audit.discovered_from = item.node.discovered_from;
                publication_points.push(audit);
            }
            Err(err) => {
                instances_failed += 1;
                warnings.push(
                    Warning::new(format!("publication point failed: {err}"))
                        .with_context(&item.node.handle.manifest_rsync_uri),
                );
            }
        }
    }

    TreeRunAuditOutput {
        tree: TreeRunOutput {
            instances_processed,
            instances_failed,
            warnings,
            vrps,
            aspas,
            router_keys,
        },
        publication_points,
    }
}

pub fn run_tree_parallel_phase2_audit(
    root: CaInstanceHandle,
    runner: &Rpkiv1PublicationPointRunner<'_>,
    config: &TreeRunConfig,
) -> Result<TreeRunAuditOutput, TreeRunError> {
    run_tree_parallel_phase2_audit_multi_root(vec![root], runner, config)
}

#[cfg(test)]
mod tests {
    use super::{compact_phase2_finished_result, compact_phase2_finished_result_result};
    use crate::audit::PublicationPointAudit;
    use crate::storage::PackTime;
    use crate::validation::manifest::PublicationPointSource;
    use crate::validation::objects::{ObjectsOutput, ObjectsStats};
    use crate::validation::publication_point::PublicationPointSnapshot;
    use crate::validation::tree::PublicationPointRunResult;

    fn sample_snapshot() -> PublicationPointSnapshot {
        PublicationPointSnapshot {
            format_version: PublicationPointSnapshot::FORMAT_VERSION_V1,
            manifest_rsync_uri: "rsync://example.test/repo/example.mft".to_string(),
            publication_point_rsync_uri: "rsync://example.test/repo/".to_string(),
            manifest_number_be: vec![1],
            this_update: PackTime {
                rfc3339_utc: "2026-04-21T00:00:00Z".to_string(),
            },
            next_update: PackTime {
                rfc3339_utc: "2026-04-22T00:00:00Z".to_string(),
            },
            verified_at: PackTime {
                rfc3339_utc: "2026-04-21T00:00:01Z".to_string(),
            },
            manifest_bytes: vec![1, 2, 3],
            files: Vec::new(),
        }
    }

    fn sample_result() -> PublicationPointRunResult {
        PublicationPointRunResult {
            source: PublicationPointSource::Fresh,
            snapshot: Some(sample_snapshot()),
            warnings: Vec::new(),
            objects: ObjectsOutput {
                vrps: Vec::new(),
                aspas: Vec::new(),
                router_keys: Vec::new(),
                local_outputs_cache: Vec::new(),
                warnings: Vec::new(),
                stats: ObjectsStats::default(),
                audit: Vec::new(),
            },
            audit: PublicationPointAudit::default(),
            discovered_children: Vec::new(),
        }
    }

    #[test]
    fn compact_phase2_finished_result_drops_snapshot() {
        let result = compact_phase2_finished_result(sample_result(), false);
        assert!(result.snapshot.is_none());
        assert_eq!(result.source, PublicationPointSource::Fresh);
        assert!(result.discovered_children.is_empty());
    }

    #[test]
    fn compact_phase2_finished_result_can_drop_audit_payload() {
        let mut sample = sample_result();
        sample.audit.objects.push(crate::audit::ObjectAuditEntry {
            rsync_uri: "rsync://example.test/repo/a.roa".to_string(),
            sha256_hex: "11".repeat(32),
            kind: crate::audit::AuditObjectKind::Roa,
            result: crate::audit::AuditObjectResult::Ok,
            detail: None,
        });
        sample.audit.warnings.push(crate::audit::AuditWarning {
            message: "warning".to_string(),
            rfc_refs: Vec::new(),
            context: None,
        });
        sample.objects.audit.push(crate::audit::ObjectAuditEntry {
            rsync_uri: "rsync://example.test/repo/b.roa".to_string(),
            sha256_hex: "22".repeat(32),
            kind: crate::audit::AuditObjectKind::Roa,
            result: crate::audit::AuditObjectResult::Ok,
            detail: None,
        });
        let result = compact_phase2_finished_result(sample, true);
        assert!(result.audit.objects.is_empty());
        assert!(result.audit.warnings.is_empty());
        assert!(result.objects.audit.is_empty());
    }

    #[test]
    fn compact_phase2_finished_result_result_preserves_err() {
        let err = compact_phase2_finished_result_result(Err("boom".to_string()), false)
            .expect_err("error should be preserved");
        assert_eq!(err, "boom");
    }
}
