#include <bits/stdc++.h>

namespace {
    constexpr int uplink_queue_target_base_milli = 6000;
    constexpr int uplink_queue_target_strength_milli = 4750;
    constexpr int protected_startup_max_prefill_chunks = 16;
    constexpr bool enable_protected_startup_prefill_chunking = true;
    constexpr bool enable_protected_startup_cloud_prior = true;
    constexpr int protected_startup_cloud_prior_strength_milli = 1000;
    constexpr int cohort_scale_numerator = 1;
    constexpr int cohort_scale_denominator = 4;
    constexpr int startup_cohort_multiplier = 8;
    enum class RequestPhase : unsigned char {
        not_arrived,
        prefill_pre_ready,
        prefill_pre_running,
        prefill_upload_pending,
        prefill_proc_ready,
        prefill_proc_running,
        prefill_download_pending,
        prefill_post_ready,
        prefill_post_running,
        decode_pre_ready,
        decode_pre_running,
        decode_upload_pending,
        decode_proc_ready,
        decode_proc_running,
        decode_download_pending,
        decode_post_ready,
        decode_post_running,
        finished
    };

    struct Request {
        RequestPhase phase = RequestPhase::not_arrived;
        int generation = 0;
        int input_length = 0;
        int cloud_id = -1;
        int tokens_produced = 0;
        int decode_wave_id = -1;
        int next_prefill_layer = 0;
        int scheduled_prefill_layer_end = 0;
        int prefill_chunks_completed = 0;
        bool counted_in_cloud_load = false;
        bool decode_admitted = false;
        double arrival_time_ms = 0;
        double ready_since_ms = 0;
        double last_token_time_ms = 0;
    };

    struct ReadyQueueEntry {
        int request_id = -1;
        int generation = -1;
    };

    struct DecodeWave {
        int remaining_members = 0;
        int ready_members = 0;
    };

    struct TransferPrediction {
        double completion_time_ms = 0;
        int cloud_id = -1;
        int payload_units = 0;
        bool is_decode_transfer = false;
    };

    struct TaskTimeTable {
        std::array<std::vector<std::pair<int, double>>, 6> samples_by_kind;

        void add_sample(int size, const std::array<double, 6>& value) {
            for (int task_kind = 0; task_kind < 6; ++task_kind) {
                if (value[task_kind] >= 0)
                    samples_by_kind[task_kind].push_back({size, value[task_kind]});
            }
        }

        void sort_samples() {
            for (auto& samples : samples_by_kind)
                std::sort(samples.begin(), samples.end());
        }

        double duration(int kind, int size) const {
            const auto& samples = samples_by_kind[kind];
            const auto upper = std::lower_bound(
                samples.begin(), samples.end(), std::pair<int, double>{size, -1e100});
            if (upper == samples.begin())
                return upper->second;
            if (upper == samples.end())
                return samples.back().second;
            if (upper->first == size)
                return upper->second;
            const auto lower = std::prev(upper);
            const double ratio =
                static_cast<double>(size - lower->first) / (upper->first - lower->first);
            return lower->second + ratio * (upper->second - lower->second);
        }

        int best_decode_proc_batch(double task_setup_ms) const {
            std::vector<int> candidate{1};
            for (const auto& [size, value] : samples_by_kind[4]) {
                (void)value;
                candidate.push_back(std::min(size, 2000));
            }
            std::sort(candidate.begin(), candidate.end());
            candidate.erase(std::unique(candidate.begin(), candidate.end()), candidate.end());
            int best_size = 1;
            double best_unit = (task_setup_ms + duration(4, 1));
            for (int size : candidate) {
                const double unit_cost = (task_setup_ms + duration(4, size)) / size;
                if (unit_cost + 1e-12 < best_unit) {
                    best_unit = unit_cost;
                    best_size = size;
                }
            }
            return best_size;
        }
    };

    bool parse_cloud_id(const std::string& token, int& cloud) {
        if (token.size() < 2 || token[0] != 'C')
            return false;
        long long value = 0;
        for (std::size_t i = 1; i < token.size(); ++i) {
            if (!std::isdigit(static_cast<unsigned char>(token[i])))
                return false;
            value = value * 10 + token[i] - '0';
            if (value > INT_MAX)
                return false;
        }
        cloud = static_cast<int>(value);
        return true;
    }
    enum class EdgeTaskKind : unsigned char {
        prefill_pre,
        prefill_post,
        decode_pre,
        decode_post,
    };

    struct EdgeTaskChoice {
        bool is_valid = false;
        EdgeTaskKind task_kind = EdgeTaskKind::prefill_pre;
        double priority_key = 0;
        int tie_breaker = 0;
        int request_id = -1;
        int cloud_id = -1;
        std::vector<int> request_ids;
    };

    struct Scheduler {
        static constexpr int max_batch_size = 4096;
        int num_clouds;
        int num_layers;
        int bytes_per_token;
        double task_setup_ms;
        double transfer_latency_ms;
        double bandwidth_gbps;
        double tdr_slo_ms;
        double tpot_slo_ms;
        double throughput_upper_bound;
        double throughput_baseline;
        double distance_base;
        double w_tp;
        double w_c;
        TaskTimeTable task_times;
        double minimum_prefill_path_ms = 0;
        double current_time_ms = 0;
        bool edge_busy = false;
        std::vector<bool> cloud_busy;
        std::array<double, 2> link_available_time_ms{0., 0.};
        std::array<std::deque<TransferPrediction>, 2> predicted_transfer_queue;
        std::array<std::vector<std::deque<std::pair<double, int>>>, 2>
            predicted_decode_transfers_by_cloud;
        std::array<bool, 2> transfer_prediction_valid{true, true};
        std::vector<int> cloud_request_load;
        std::vector<int> cloud_decode_load;
        std::vector<int> cloud_active_output_requests;
        std::vector<double> cloud_prefill_work_ms;
        std::vector<double> last_cloud_starvation_time_ms, cloud_predicted_busy_until_ms,
            cloud_running_prefill_work_ms;
        int next_cloud_round_robin = 0;
        int edge_decode_round_robin_class = 0;
        int active_decode_requests = 0;
        bool decode_admission_limited = false;
        int preferred_decode_proc_batch = 1;
        int base_decode_window = 1;
        int decode_window = 1;
        int decode_controller_step = 1;
        int decode_controller_max = 1;
        int unopened_decode_ready_count = 0;
        bool decode_stream_observed = false;
        bool startup_srpt_mode = false;
        long long produced_token_count = 0;
        double first_arrival_time_ms = -1;
        double last_arrival_time_ms = -1;
        int epoch_opportunities = 0;
        int epoch_blocked = 0;
        int epoch_launches = 0;
        int epoch_starved = 0;
        double epoch_utilization_sum = 0;
        int good_epochs = 0;
        int low_epochs = 0;
        int cooldown = 0;
        int completed_epochs = 0;
        bool probe_pending = false;
        double probe_deficit = 0;
        double probe_saturation = 0;
        double probe_tdr_guard = 0;
        double probe_tpot_guard = 0;
        double probe_normalized_throughput = 0;
        std::array<std::vector<int>, 3> best_batch_size;
        std::array<std::vector<int>, 3> latency_batch_size;
        std::vector<double> cohort_cycle_ms;
        std::vector<int> best_rate_cohort;
        std::vector<int> best_cloud_count_for_cohort;
        bool synchronized_decode_enabled = false;
        int startup_decode_admission_cap = 0;
        double synchronization_ratio = 0, strong_waiting_max_decode_rate = 0;
        int strong_waiting_decode_window = 1, bootstrap_cohort = 1;

        bool strong_waiting_fallback_mode() const {
            return w_c >= 2 * w_tp && !legacy_grouping_mode() && !latency_dominant_objective_band();
        }

        double strong_waiting_batch_service_cost(int stage, int batch_size) const {
            double service_cost = task_cost(3 + stage, batch_size);
            if (!stage)
                service_cost = std::max(service_cost,
                                        transfer_latency_ms * std::min(num_clouds, batch_size) +
                                            transfer_cost_ms(batch_size) - transfer_latency_ms);
            else if (stage == 1)
                service_cost = std::max(service_cost, transfer_cost_ms(batch_size));
            return service_cost;
        }

        int synchronization_population = 64;
        int mature_entry_population = 64;
        int arrived_count = 0;
        int pending_prefill_count = 0;
        int lower_bound_cached_arrival_count = -1;
        double pending_arrival_time_sum = 0;
        double completed_tdr_sum_ms = 0;
        bool runtime_fallback_enabled = false;
        int finished_count = 0;
        int single_token_finished_count = 0;
        long long finished_token_count = 0;
        std::vector<int> first_token_completion_ids;
        int observed_first_token_count = 0;
        int first_token_count_at_last_arrival = 0;
        int observed_nonterminal_first_tokens = 0;
        bool arrival_seen_in_frame = false;
        int prefill_post_skip_count = 0;
        int prefill_pre_skip_count = 0;
        std::vector<int> prefill_proc_skip_count;
        std::vector<int> decode_proc_streak;
        std::vector<double> decode_service_debt_ms;
        std::array<int, 18> ready_count_by_phase{};
        std::vector<int> decode_proc_ready_count;
        std::vector<Request> requests;
        std::vector<DecodeWave> decode_waves;
        std::deque<ReadyQueueEntry> prefill_pre_ready_queue;
        std::deque<ReadyQueueEntry> prefill_post_ready_queue;
        std::deque<ReadyQueueEntry> fresh_decode_pre_queue;
        std::deque<ReadyQueueEntry> open_decode_pre_queue;
        std::deque<ReadyQueueEntry> decode_post_ready_queue;
        std::vector<std::deque<ReadyQueueEntry>> prefill_proc_ready_queues;
        std::vector<std::deque<ReadyQueueEntry>> decode_proc_ready_queues;

        Scheduler(int num_clouds_,
                  int num_layers_,
                  int bytes_per_token_,
                  double task_setup_ms_,
                  double transfer_latency_ms_,
                  double bandwidth_gbps_,
                  double tdr_slo_ms_,
                  double tpot_slo_ms_,
                  double throughput_upper_bound_,
                  double throughput_baseline_,
                  double distance_base_,
                  double w_tp_,
                  double w_c_,
                  TaskTimeTable task_times_)
            : num_clouds(num_clouds_),
              num_layers(num_layers_),
              bytes_per_token(bytes_per_token_),
              task_setup_ms(task_setup_ms_),
              transfer_latency_ms(transfer_latency_ms_),
              bandwidth_gbps(bandwidth_gbps_),
              tdr_slo_ms(tdr_slo_ms_),
              tpot_slo_ms(tpot_slo_ms_),
              throughput_upper_bound(throughput_upper_bound_),
              throughput_baseline(throughput_baseline_),
              distance_base(distance_base_),
              w_tp(w_tp_),
              w_c(w_c_),
              task_times(std::move(task_times_)),
              cloud_busy(num_clouds),
              cloud_request_load(num_clouds),
              cloud_decode_load(num_clouds),
              cloud_active_output_requests(num_clouds),
              cloud_prefill_work_ms(num_clouds),
              last_cloud_starvation_time_ms(num_clouds, -1e100),
              cloud_predicted_busy_until_ms(num_clouds),
              cloud_running_prefill_work_ms(num_clouds),
              prefill_proc_skip_count(num_clouds),
              decode_proc_streak(num_clouds),
              decode_service_debt_ms(num_clouds),
              decode_proc_ready_count(num_clouds),
              prefill_proc_ready_queues(num_clouds),
              decode_proc_ready_queues(num_clouds) {
            predicted_decode_transfers_by_cloud[0].resize(num_clouds);
            predicted_decode_transfers_by_cloud[1].resize(num_clouds);
            for (int step = 0; step < 3; ++step) {
                best_batch_size[step].resize(max_batch_size + 1);
                latency_batch_size[step].resize(max_batch_size + 1);
                int best = 1;
                double best_unit = std::numeric_limits<double>::infinity();
                for (int size = 1; size <= max_batch_size; ++size) {
                    const double unit = task_cost(3 + step, size) / size;
                    const double eps =
                        std::isfinite(best_unit) ? 1e-12 * std::max(1., std::abs(best_unit)) : 0;
                    if (!std::isfinite(best_unit) || unit < best_unit - eps ||
                        (std::abs(unit - best_unit) <= eps && size > best)) {
                        best = size;
                        best_unit = unit;
                    }
                    best_batch_size[step][size] = best;
                    if (w_tp <= 1e-12 && w_c > 1e-12) {
                        int latency_best = 1;
                        double latency_area = std::numeric_limits<double>::infinity();
                        for (int batch = 1; batch <= size; ++batch) {
                            const int full = size / batch;
                            const int rem = size % batch;
                            const double full_cost = task_cost(3 + step, batch);
                            double area =
                                static_cast<double>(batch) * full_cost * full * (full + 1) / 2.;
                            if (rem > 0) {
                                area += static_cast<double>(rem) *
                                        (full * full_cost + task_cost(3 + step, rem));
                            }
                            if (area < latency_area - 1e-12 ||
                                (std::abs(area - latency_area) <= 1e-12 && batch > latency_best)) {
                                latency_area = area;
                                latency_best = batch;
                            }
                        }
                        latency_batch_size[step][size] = latency_best;
                    } else {
                        latency_batch_size[step][size] = best_batch_size[step][size];
                    }
                }
            }
            if (strong_waiting_fallback_mode())
                for (int stage = 0; stage < 3; ++stage) {
                    std::vector<double> minimum_service(2001,
                                                        std::numeric_limits<double>::infinity());
                    minimum_service[0] = 0;
                    for (int population = 1; population <= 2000; ++population)
                        for (int batch_size = 1; batch_size <= population; ++batch_size) {
                            double candidate_cost =
                                       minimum_service[population - batch_size] +
                                       strong_waiting_batch_service_cost(stage, batch_size),
                                   epsilon =
                                       1e-12 * std::max(1., std::abs(minimum_service[population]));
                            if (candidate_cost < minimum_service[population] - epsilon ||
                                (std::abs(candidate_cost - minimum_service[population]) <=
                                     epsilon &&
                                 batch_size > best_batch_size[stage][population]))
                                minimum_service[population] = candidate_cost,
                                best_batch_size[stage][population] = batch_size;
                        }
                }
            preferred_decode_proc_batch = task_times.best_decode_proc_batch(task_setup_ms);
            const int cohort_limit = 2000;
            cohort_cycle_ms.assign(cohort_limit + 1, std::numeric_limits<double>::infinity());
            best_rate_cohort.assign(cohort_limit + 1, 1);
            best_cloud_count_for_cohort.assign(cohort_limit + 1, 1);
            double best_cohort_rate = 0;
            double best_pipeline_rate = 0;
            int best_rate_size = 1;
            std::vector<double> pipeline_capacity(cohort_limit + 1);
            for (int cohort_size = 1; cohort_size <= cohort_limit; ++cohort_size) {
                double best_cycle = std::numeric_limits<double>::infinity();
                int best_q = 1;
                for (int cloud_count = 1; cloud_count <= std::min(num_clouds, cohort_size);
                     ++cloud_count) {
                    std::vector<int> cloud_batches(cloud_count, cohort_size / cloud_count);
                    for (int i = 0; i < cohort_size % cloud_count; ++i)
                        ++cloud_batches[i];
                    double upload_finish = task_cost(3, cohort_size);
                    std::vector<std::pair<double, int>> proc_finishes;
                    proc_finishes.reserve(cloud_count);
                    double cloud_capacity = 0;
                    for (int batch_size : cloud_batches) {
                        upload_finish += transfer_cost_ms(batch_size);
                        proc_finishes.push_back(
                            {upload_finish + task_cost(4, batch_size), batch_size});
                        cloud_capacity +=
                            static_cast<double>(batch_size) / task_cost(4, batch_size);
                    }
                    std::sort(proc_finishes.begin(), proc_finishes.end());
                    double download_finish = 0;
                    for (const auto& [finish, batch_size] : proc_finishes) {
                        download_finish =
                            std::max(download_finish, finish) + transfer_cost_ms(batch_size);
                    }
                    const double cycle = download_finish + task_cost(5, cohort_size);
                    if (cycle < best_cycle - 1e-12) {
                        best_cycle = cycle;
                        best_q = cloud_count;
                    }
                    const double edge_capacity =
                        static_cast<double>(cohort_size) /
                        (task_cost(3, cohort_size) + task_cost(5, cohort_size));
                    const double link_capacity = static_cast<double>(cohort_size) /
                                                 (cloud_count * transfer_latency_ms +
                                                  8. * static_cast<double>(bytes_per_token) *
                                                      cohort_size / (bandwidth_gbps * 1e6));
                    best_pipeline_rate =
                        std::max(best_pipeline_rate,
                                 std::min({edge_capacity, cloud_capacity, link_capacity}));
                }
                pipeline_capacity[cohort_size] = best_pipeline_rate;
                cohort_cycle_ms[cohort_size] = best_cycle;
                best_cloud_count_for_cohort[cohort_size] = best_q;
                const double rate = static_cast<double>(cohort_size) / best_cycle;
                if (rate > best_cohort_rate + 1e-12) {
                    best_cohort_rate = rate;
                    best_rate_size = cohort_size;
                }
                best_rate_cohort[cohort_size] =
                    (cohort_size == 1 ? 1 : best_rate_cohort[cohort_size - 1]);
                const int previous_best = best_rate_cohort[cohort_size];
                if (rate >
                    static_cast<double>(previous_best) / cohort_cycle_ms[previous_best] + 1e-12) {
                    best_rate_cohort[cohort_size] = cohort_size;
                }
            }
            synchronization_ratio =
                best_pipeline_rate > 1e-15 ? best_cohort_rate / best_pipeline_rate : 0;
            const double single_rate = 1. / cohort_cycle_ms[1];
            const double batching_economy = best_cohort_rate / std::max(1e-15, single_rate);
            const double distance_tolerance = distance_base / (distance_base + 32.);
            const double throughput_pressure_value = w_tp + w_c * distance_tolerance;
            minimum_prefill_path_ms = std::numeric_limits<double>::infinity();
            double maximum_prefill_path_ms = 0;
            std::vector<int> visible_sizes{1};
            for (const auto& column : task_times.samples_by_kind) {
                for (const auto& [size, value] : column) {
                    (void)value;
                    visible_sizes.push_back(size);
                }
            }
            std::sort(visible_sizes.begin(), visible_sizes.end());
            visible_sizes.erase(std::unique(visible_sizes.begin(), visible_sizes.end()),
                                visible_sizes.end());
            for (int size : visible_sizes) {
                const double path = task_cost(0, size) + 2. * transfer_cost_ms(size) +
                                    task_cost(1, size) + task_cost(2, size);
                minimum_prefill_path_ms = std::min(minimum_prefill_path_ms, path);
                maximum_prefill_path_ms = std::max(maximum_prefill_path_ms, path);
            }
            const double modeled_norm_tp =
                std::clamp((best_cohort_rate - throughput_baseline) /
                               std::max(1e-15, throughput_upper_bound - throughput_baseline),
                           0.,
                           1.);
            const bool generous_waiting = minimum_prefill_path_ms <= 0.65 * tdr_slo_ms + 1e-12 &&
                                          cohort_cycle_ms[1] <= 0.65 * tpot_slo_ms + 1e-12;
            startup_srpt_mode =
                throughput_baseline > 1e-15 && w_tp >= 0.35 - 1e-12 && w_c + 1e-12 >= w_tp &&
                distance_base >= 256. && distance_base < 10000. &&
                throughput_pressure_value >= 0.95 - 1e-12 && modeled_norm_tp >= 0.75 - 1e-12 &&
                maximum_prefill_path_ms >= 1.20 * minimum_prefill_path_ms - 1e-12 &&
                generous_waiting;
            const bool cohort_objective =
                w_tp >= 0.72 - 1e-12 || (distance_base >= 10000. && throughput_upper_bound > 1.);
            const bool medium_weight_tolerant = w_tp >= 0.72 - 1e-12 && w_tp <= 0.86 + 1e-12 &&
                                                distance_base >= 256. &&
                                                throughput_pressure_value >= 0.97 - 1e-12;
            const bool very_tolerant_balanced =
                w_tp >= 0.30 - 1e-12 && w_tp <= 0.70 + 1e-12 && distance_base >= 10000. &&
                throughput_upper_bound > 1. && throughput_pressure_value >= 0.97 - 1e-12;
            const bool strict_model_support =
                synchronization_ratio >= 0.72 - 1e-12 && batching_economy >= 1.18 - 1e-12;
            const bool tolerant_model_support =
                synchronization_ratio >= 0.52 - 1e-12 && batching_economy >= 1.05 - 1e-12;
            const bool baseline_synchronization_enabled =
                num_clouds >= 2 && w_c > 0.02 && cohort_objective &&
                throughput_pressure_value >= 0.90 - 1e-12 && best_rate_size >= 2 &&
                (strict_model_support ||
                 ((medium_weight_tolerant || very_tolerant_balanced) && tolerant_model_support));
            const double score_weight_sum = w_tp + w_c;
            const double throughput_share = score_weight_sum > 1e-15 ? w_tp / score_weight_sum : 0.;
            const double ultra_weight_gate = std::clamp((throughput_share - 0.95) / 0.03, 0., 1.);
            const double stream_cohort_support =
                synchronization_ratio * std::sqrt(std::max(1., batching_economy));
            const double startup_strength = std::clamp((throughput_share - 0.82) / 0.08, 0., 1.);
            if (num_clouds >= 2 && distance_base >= 64. &&
                throughput_pressure_value >= 0.90 - 1e-12 && startup_strength > 1e-12) {
                startup_decode_admission_cap = std::clamp(
                    static_cast<int>(
                        std::lround(startup_strength * startup_cohort_multiplier * num_clouds)),
                    2,
                    8 * num_clouds);
            }
            const bool high_throughput_synchronization_enabled =
                num_clouds >= 2 && cohort_objective && best_rate_size >= 2 &&
                batching_economy >= 1.02 - 1e-12 &&
                ultra_weight_gate * stream_cohort_support >= 0.45 + .25 * w_c - 1e-12;
            synchronized_decode_enabled =
                baseline_synchronization_enabled || high_throughput_synchronization_enabled;
            bootstrap_cohort = best_rate_cohort[std::min(
                cohort_limit,
                std::max(8, num_clouds * std::clamp(preferred_decode_proc_batch, 2, 64)))];
            synchronization_population = std::max(24, std::min(192, bootstrap_cohort));
            mature_entry_population = synchronization_population;
            const int bootstrap_index = std::min(cohort_limit, std::max(1, bootstrap_cohort));
            const bool dominant_decode_batching =
                batching_economy >= static_cast<double>(synchronization_population) - 1e-12 &&
                maximum_prefill_path_ms <= cohort_cycle_ms[bootstrap_index] + 1e-12;
            const bool baseline_entry_support =
                dominant_decode_batching && synchronization_ratio >= .74 - 1e-12;
            const bool ultra_entry_support =
                high_throughput_synchronization_enabled && synchronization_ratio >= 0.45 - 1e-12;
            if (synchronized_decode_enabled && (baseline_entry_support || ultra_entry_support)) {
                int entry_population = synchronization_population;
                const auto score_proxy = [&](int population) {
                    const int cohort = best_rate_cohort[std::clamp(population, 1, cohort_limit)];
                    const double cycle = cohort_cycle_ms[cohort];
                    const double rate = static_cast<double>(cohort) / cycle;
                    const double norm_tp = std::clamp(
                        (rate - throughput_baseline) /
                            std::max(1e-15, throughput_upper_bound - throughput_baseline),
                        0.,
                        1.);
                    const double tdr_excess = std::max(0., cycle / std::max(1e-9, tdr_slo_ms) - 1.);
                    const double tpot_excess =
                        std::max(0., cycle / std::max(1e-9, tpot_slo_ms) - 1.);
                    const double distance = std::hypot(tdr_excess, tpot_excess);
                    const double norm_wait = distance_base > 1e-15
                                                 ? std::clamp(1. - distance / distance_base, 0., 1.)
                                                 : static_cast<double>(distance <= 1e-12);
                    return w_tp * norm_tp + w_c * norm_wait;
                };
                const double singleton_score = score_proxy(1);
                for (int population = 2; population <= synchronization_population; ++population) {
                    const int cohort = best_rate_cohort[population];
                    if (cohort >= 2 && score_proxy(population) > singleton_score + 1e-12) {
                        entry_population = population;
                        break;
                    }
                }
                mature_entry_population = entry_population;
            }
            if (w_tp >= 0.72 - 1e-12) {
                decode_window = 2000;
            } else {
                const double weight_sum = w_tp + w_c;
                const double tp_share = weight_sum > 0 ? w_tp / weight_sum : .5;
                int admission_waves = 4;
                if (tp_share < 0.34)
                    admission_waves = 1;
                if (tp_share > 0.67)
                    admission_waves = 3;
                const int practical_batch = std::min(preferred_decode_proc_batch, 64);
                const int window_cap = tp_share > 0.67 ? 768 : 512;
                decode_window =
                    std::clamp(num_clouds * practical_batch * admission_waves, 1, window_cap);
            }
            if (distance_base >= 10000.)
                decode_window = 2000;
            if (distance_base >= 100. && distance_base < 10000. && w_tp > 1e-12 &&
                w_tp < .25 - 1e-12) {
                decode_window =
                    std::min(1024, 8 * num_clouds * std::min(preferred_decode_proc_batch, 64));
            }
            if (w_tp >= 0.55 - 1e-12 && w_tp < 0.72 - 1e-12 && w_c > 0.05 &&
                distance_base >= 256. && distance_base < 10000. &&
                throughput_pressure_value >= 0.90 - 1e-12) {
                const auto model = [&](int population) {
                    const int cohort = best_rate_cohort[population];
                    const double cohort_rate = cohort / cohort_cycle_ms[cohort];
                    const double finite_pipeline =
                        std::min(pipeline_capacity[population], population / cohort_cycle_ms[1]);
                    const double rate = std::max(cohort_rate, finite_pipeline);
                    const double robust_rate = 0.85 * rate;
                    const double norm_tp = std::clamp(
                        (robust_rate - throughput_baseline) /
                            std::max(1e-15, throughput_upper_bound - throughput_baseline),
                        0.,
                        1.);
                    const double excess = std::max(
                        0., population / std::max(1e-15, rate) / std::max(1e-9, tpot_slo_ms) - 1.);
                    const double norm_wait = distance_base > 1e-15
                                                 ? std::max(0., 1. - excess / distance_base)
                                                 : static_cast<double>(excess <= 1e-12);
                    return std::pair<double, double>{w_tp * norm_tp + w_c * norm_wait, norm_tp};
                };
                const int old_window = std::clamp(decode_window, 1, cohort_limit);
                const auto old_model = model(old_window);
                int candidate = old_window;
                auto best_model = old_model;
                for (int population = 1; population < old_window; ++population) {
                    const auto value = model(population);
                    if (value.first > best_model.first + 1e-12) {
                        candidate = population;
                        best_model = value;
                    }
                }
                if (candidate < old_window && best_model.first >= old_model.first + 0.001 &&
                    best_model.second + 0.005 >= old_model.second) {
                    double fade_weight =
                        std::clamp((throughput_pressure_value - 0.985) / 0.010, 0., 1.);
                    decode_window = std::max(
                        num_clouds,
                        static_cast<int>(
                            std::lround(old_window + fade_weight * (candidate - old_window))));
                }
            }
            if (w_tp <= 1e-12 && w_c >= 0.95 - 1e-12 && distance_base < 2.) {
                decode_window = std::max(1, decode_window * 15 / 16);
            }
            const double proactive_policy_strength =
                w_tp > 1e-12 ? std::clamp((0.30 - w_tp) / 0.12, 0., 1.) : 0.;
            decode_window =
                std::max(decode_window,
                         static_cast<int>(std::lround(decode_window + proactive_policy_strength *
                                                                          (2000 - decode_window))));
            if (strong_waiting_fallback_mode()) {
                std::vector<double> score_by_population(2001);
                double best_score = -std::numeric_limits<double>::infinity();
                for (int population = 1; population <= 2000; ++population) {
                    int cloud_count = std::min(num_clouds, population),
                        per_cloud_batch = (population + cloud_count - 1) / cloud_count;
                    double cycle_time = task_cost(3, population) +
                                        2 * (transfer_latency_ms * cloud_count +
                                             transfer_cost_ms(population) - transfer_latency_ms) +
                                        task_cost(4, per_cloud_batch) + task_cost(5, population),
                           decode_rate = static_cast<double>(population) / cycle_time;
                    strong_waiting_max_decode_rate =
                        std::max(strong_waiting_max_decode_rate, decode_rate);
                    double normalized_throughput = std::clamp(
                               (decode_rate - throughput_baseline) /
                                   std::max(1e-15, throughput_upper_bound - throughput_baseline),
                               0.,
                               1.),
                           waiting_excess = std::max(
                               0., (1.5 * cycle_time - tpot_slo_ms) / std::max(1e-9, tpot_slo_ms)),
                           normalized_waiting =
                               distance_base > 1e-15
                                   ? std::max(0., 1 - waiting_excess / distance_base)
                                   : static_cast<double>(waiting_excess <= 1e-12);
                    score_by_population[population] =
                        w_tp * normalized_throughput + w_c * normalized_waiting;
                    best_score = std::max(best_score, score_by_population[population]);
                }
                double score_tolerance = .04 + .15 * std::max(0., w_tp - .55);
                for (int population = 1; population <= 2000; ++population)
                    if (score_by_population[population] >= best_score - score_tolerance)
                        strong_waiting_decode_window = population;
                strong_waiting_decode_window = std::max(strong_waiting_decode_window, num_clouds);
            }
            base_decode_window = decode_window;
            decode_controller_step = num_clouds * std::clamp(preferred_decode_proc_batch, 1, 64);
            decode_controller_max = base_decode_window;
            if (distance_base >= 100. && distance_base < 10000. && w_tp >= 0.1 - 1e-12 &&
                base_decode_window < 2000) {
                if (w_tp < .25 - 1e-12) {
                    decode_controller_max =
                        std::min(1024, base_decode_window + 3 * decode_controller_step);
                } else if (w_tp < 0.7 - 1e-12) {
                    decode_controller_max = 2000;
                } else if (w_tp < 0.8 - 1e-12) {
                    decode_controller_max =
                        std::min(1536, base_decode_window + 2 * decode_controller_step);
                }
            }
            if (distance_base >= 100. && distance_base < 10000. && w_tp > 1e-12 &&
                w_tp < .25 - 1e-12) {
                decode_controller_max = base_decode_window;
            }
        }

        bool is_valid_request_id(int id) const {
            return id >= 0 && id < static_cast<int>(requests.size());
        }

        bool latency_dominant_objective_band() const {
            return objective_band_code() == 1 && w_c > w_tp;
        }

        bool runtime_fallback_active() const {
            return runtime_fallback_enabled;
        }

        Request& get_or_create_request(int id) {
            if (id >= static_cast<int>(requests.size()))
                requests.resize(static_cast<std::size_t>(id) + 1);
            return requests[id];
        }

        bool is_ready_phase(RequestPhase phase) const {
            return phase == RequestPhase::prefill_pre_ready ||
                   phase == RequestPhase::prefill_proc_ready ||
                   phase == RequestPhase::prefill_post_ready ||
                   phase == RequestPhase::decode_pre_ready ||
                   phase == RequestPhase::decode_proc_ready ||
                   phase == RequestPhase::decode_post_ready;
        }

        void adjust_ready_count(RequestPhase phase, int cloud, int delta) {
            if (!is_ready_phase(phase))
                return;
            ready_count_by_phase[static_cast<std::size_t>(phase)] += delta;
            if (phase == RequestPhase::decode_proc_ready && cloud >= 0 && cloud < num_clouds) {
                decode_proc_ready_count[cloud] += delta;
            }
        }

        void enqueue_ready_state(int id) {
            const ReadyQueueEntry item{id, requests[id].generation};
            switch (requests[id].phase) {
                case RequestPhase::prefill_pre_ready:
                    prefill_pre_ready_queue.push_back(item);
                    break;
                case RequestPhase::prefill_proc_ready:
                    prefill_proc_ready_queues[requests[id].cloud_id].push_back(item);
                    break;
                case RequestPhase::prefill_post_ready:
                    prefill_post_ready_queue.push_back(item);
                    break;
                case RequestPhase::decode_pre_ready:
                    if (requests[id].tokens_produced == 0)
                        fresh_decode_pre_queue.push_back(item);
                    else
                        open_decode_pre_queue.push_back(item);
                    break;
                case RequestPhase::decode_proc_ready:
                    decode_proc_ready_queues[requests[id].cloud_id].push_back(item);
                    break;
                case RequestPhase::decode_post_ready:
                    decode_post_ready_queue.push_back(item);
                    break;
                default:
                    break;
            }
        }

        void set_request_phase(int id, RequestPhase to) {
            Request& r = requests[id];
            adjust_ready_count(r.phase, r.cloud_id, -1);
            r.phase = to;
            ++r.generation;
            if (is_ready_phase(to))
                r.ready_since_ms = current_time_ms;
            adjust_ready_count(r.phase, r.cloud_id, 1);
            enqueue_ready_state(id);
        }

        bool advance_request_phase(int id, RequestPhase from, RequestPhase to) {
            if (!is_valid_request_id(id) || requests[id].phase != from)
                return false;
            set_request_phase(id, to);
            return true;
        }

        bool release_server(const std::string& server) {
            if (server == "E") {
                if (!edge_busy)
                    return false;
                edge_busy = false;
                return true;
            }
            int cloud = -1;
            if (!parse_cloud_id(server, cloud) || cloud < 0 || cloud >= num_clouds ||
                !cloud_busy[cloud])
                return false;
            cloud_busy[cloud] = false;
            cloud_predicted_busy_until_ms[cloud] = cloud_running_prefill_work_ms[cloud] = 0;
            return true;
        }

        void record_predicted_transfer(int direction, int cloud, bool is_decode, int units) {
            if (direction < 0 || direction > 1 || cloud < 0 || cloud >= num_clouds || units <= 0 ||
                !transfer_prediction_valid[direction])
                return;
            const double due = std::max(current_time_ms, link_available_time_ms[direction]) +
                               transfer_cost_ms(units);
            link_available_time_ms[direction] = due;
            predicted_transfer_queue[direction].push_back({due, cloud, units, is_decode});
            if (is_decode)
                predicted_decode_transfers_by_cloud[direction][cloud].push_back({due, units});
        }

        void invalidate_transfer_predictions(int direction) {
            transfer_prediction_valid[direction] = false;
            predicted_transfer_queue[direction].clear();
            for (auto& queue : predicted_decode_transfers_by_cloud[direction])
                queue.clear();
            link_available_time_ms[direction] = current_time_ms;
        }

        void reconcile_completed_transfer(
            int direction, int cloud, bool is_decode, long long bytes, int members) {
            if (direction < 0 || direction > 1 || !transfer_prediction_valid[direction])
                return;
            auto& queue = predicted_transfer_queue[direction];
            if (queue.empty()) {
                invalidate_transfer_predictions(direction);
                return;
            }
            const TransferPrediction prediction = queue.front();
            const long long modeled_bytes =
                static_cast<long long>(bytes_per_token) * prediction.payload_units;
            const double epsilon = 1e-7 * std::max(1., std::abs(current_time_ms));
            if (prediction.cloud_id != cloud || prediction.is_decode_transfer != is_decode ||
                modeled_bytes != bytes || (is_decode && prediction.payload_units != members) ||
                std::abs(prediction.completion_time_ms - current_time_ms) > epsilon ||
                (!is_decode && members != 1)) {
                invalidate_transfer_predictions(direction);
                return;
            }
            queue.pop_front();
            if (is_decode) {
                auto& decode_queue = predicted_decode_transfers_by_cloud[direction][cloud];
                if (decode_queue.empty() ||
                    std::abs(decode_queue.front().first - prediction.completion_time_ms) >
                        epsilon ||
                    decode_queue.front().second != prediction.payload_units) {
                    invalidate_transfer_predictions(direction);
                    return;
                }
                decode_queue.pop_front();
            }
            if (queue.empty())
                link_available_time_ms[direction] = current_time_ms;
        }

        std::pair<double, int> next_predicted_decode_transfer(int direction, int cloud = -1) const {
            if (direction < 0 || direction > 1 || !transfer_prediction_valid[direction]) {
                return {std::numeric_limits<double>::infinity(), 0};
            }
            std::pair<double, int> best{std::numeric_limits<double>::infinity(), 0};
            const int first = cloud < 0 ? 0 : cloud;
            const int last = cloud < 0 ? num_clouds : cloud + 1;
            for (int candidate_cloud = first; candidate_cloud < last; ++candidate_cloud) {
                const auto& queue = predicted_decode_transfers_by_cloud[direction][candidate_cloud];
                if (!queue.empty() && queue.front().first > current_time_ms + 1e-9 &&
                    queue.front().first < best.first) {
                    best = queue.front();
                }
            }
            return best;
        }

        bool has_active_decode_output() const {
            return std::any_of(cloud_active_output_requests.begin(),
                               cloud_active_output_requests.end(),
                               [](int count) { return count > 0; });
        }

        bool group_contains_started_decode(const std::vector<int>& ids) const {
            return std::any_of(ids.begin(), ids.end(), [&](int id) {
                return is_valid_request_id(id) && requests[id].tokens_produced > 0;
            });
        }

        bool startup_srpt_active() const {
            return startup_srpt_mode && !decode_stream_observed && !has_active_decode_output();
        }

        bool is_expensive_prefill_transfer(int input_length) const {
            const double transfer_time = transfer_cost_ms(input_length);
            const double remote = task_setup_ms + task_cost(1, input_length);
            const double edge = task_setup_ms + task_cost(0, input_length);
            return transfer_time >= 2. * remote - 1e-12 && transfer_time >= 1.25 * edge - 1e-12;
        }

        bool has_expensive_prefill_upload() const {
            if (!transfer_prediction_valid[0] || arrived_count < 64)
                return false;
            return std::any_of(predicted_transfer_queue[0].begin(),
                               predicted_transfer_queue[0].end(),
                               [&](const TransferPrediction& transfer) {
                                   return !transfer.is_decode_transfer &&
                                          is_expensive_prefill_transfer(transfer.payload_units);
                               });
        }

        int queued_prefill_up() const {
            return static_cast<int>(std::count_if(
                predicted_transfer_queue[0].begin(),
                predicted_transfer_queue[0].end(),
                [](const TransferPrediction& transfer) { return !transfer.is_decode_transfer; }));
        }

        double full_prefill_path_cost(int id) const {
            const int input_length = requests[id].input_length;
            return task_cost(0, input_length) + 2. * transfer_cost_ms(input_length) +
                   task_cost(1, input_length) + task_cost(2, input_length);
        }

        double prefill_uplink_restraint_strength(int id) const {
            if (!is_valid_request_id(id) || !transfer_prediction_valid[0] ||
                predicted_transfer_queue[0].empty() || has_active_decode_output() ||
                w_c <= w_tp + 1e-12)
                return 0;
            const int input_length = requests[id].input_length;
            const double transfer_time = transfer_cost_ms(input_length);
            const double edge = task_cost(0, input_length);
            const double remote = task_cost(1, input_length);
            const double weight_sum = std::max(1e-12, w_tp + w_c);
            const double weight_strength = std::clamp((w_c - w_tp) / (0.10 * weight_sum), 0., 1.);
            const double link_ratio =
                std::min(transfer_time / std::max(1e-12, edge),
                         num_clouds * transfer_time / std::max(1e-12, 2. * remote));
            const double cost_strength = std::clamp((link_ratio - 0.80) / 0.20, 0., 1.);
            double model_strength = weight_strength * cost_strength;
            if (model_strength <= 1e-12 ||
                full_prefill_path_cost(id) <= minimum_prefill_path_ms + edge + 1e-12) {
                return 0;
            }
            const double queue_per_cloud =
                static_cast<double>(queued_prefill_up()) / std::max(1, num_clouds);
            const double target = uplink_queue_target_base_milli * 0.001 -
                                  uplink_queue_target_strength_milli * 0.001 * model_strength;
            const double depth_strength = std::clamp(queue_per_cloud - (target - 1.), 0., 1.);
            model_strength *= depth_strength;
            if (decode_stream_observed) {
                model_strength *= 0.75 + 0.15 * weight_strength;
            }
            return model_strength;
        }

        bool should_hold_prefill_pre(int id) const {
            if (id < 0 || has_active_decode_output() || !transfer_prediction_valid[0] ||
                predicted_transfer_queue[0].empty())
                return false;
            const bool legacy_hold = !decode_stream_observed && has_expensive_prefill_upload();
            if (!legacy_hold && !(w_tp >= .4 - 1e-12 && w_tp < .5 - 1e-12) &&
                prefill_uplink_restraint_strength(id) < 0.85 - 1e-12) {
                return false;
            }
            if (w_c > w_tp + 1e-12 && distance_base >= 100. - 1e-12 && last_arrival_time_ms >= 0 &&
                tdr_slo_ms > 1e-12) {
                const double transfer = transfer_cost_ms(requests[id].input_length);
                const double transfer_limit = .005 * tdr_slo_ms;
                const double irreversible = transfer + task_cost(0, requests[id].input_length);
                const double irreversible_limit = .01 * tdr_slo_ms;
                const bool within_budget =
                    transfer <= transfer_limit + 1e-12 * std::max(1., transfer_limit) &&
                    irreversible <= irreversible_limit + 1e-12 * std::max(1., irreversible_limit);
                const double raw_epochs =
                    (current_time_ms - last_arrival_time_ms) / (2. * tdr_slo_ms);
                const int epochs =
                    raw_epochs >= 4. ? 4 : (raw_epochs <= 0. ? 0 : static_cast<int>(raw_epochs));
                const int per_epoch = std::max(1, (num_clouds + 3) / 4);
                const int allowance = epochs * per_epoch;
                const double tail_limit = .04 * tdr_slo_ms;
                const double total_limit = .04 * tdr_slo_ms;
                const bool within_total_budget =
                    allowance * transfer <= tail_limit + 1e-12 * std::max(1., tail_limit) &&
                    allowance * irreversible <= total_limit + 1e-12 * std::max(1., total_limit);
                int queued_prefill = 0;
                for (const TransferPrediction& item : predicted_transfer_queue[0]) {
                    if (!item.is_decode_transfer)
                        ++queued_prefill;
                }
                if (within_budget && within_total_budget && queued_prefill < allowance) {
                    return false;
                }
            }
            const double next_wakeup = predicted_transfer_queue[0].front().completion_time_ms;
            const double prepare = task_cost(0, requests[id].input_length);
            return (w_tp >= .4 - 1e-12 && w_tp < .5 - 1e-12) ||
                   next_wakeup + prepare <=
                       link_available_time_ms[0] +
                           1e-12 * std::max(1., std::abs(link_available_time_ms[0]));
        }

        bool handle_task_completion(std::istream& in) {
            std::string server, family, step;
            if (!(in >> server >> family >> step) || !release_server(server))
                return false;
            if (family == "P") {
                if (step == "PRE") {
                    int cloud = -1, id = -1;
                    double reported_duration = 0;
                    if (!(in >> cloud >> id >> reported_duration))
                        return false;
                    if (server != "E" || !is_valid_request_id(id) || requests[id].cloud_id != cloud)
                        return false;
                    if (!advance_request_phase(id,
                                               RequestPhase::prefill_pre_running,
                                               RequestPhase::prefill_upload_pending))
                        return false;
                    record_predicted_transfer(0, cloud, false, requests[id].input_length);
                    return true;
                }
                if (step == "PROC") {
                    int l = -1, r = -1, cloud = -1, id = -1;
                    double reported_duration = 0;
                    if (!(in >> l >> r >> cloud >> id >> reported_duration))
                        return false;
                    int server_c = -1;
                    if (!parse_cloud_id(server, server_c) || server_c != cloud ||
                        !is_valid_request_id(id) || requests[id].cloud_id != cloud ||
                        l != requests[id].next_prefill_layer ||
                        r != requests[id].scheduled_prefill_layer_end || l < 0 || l >= r ||
                        r > num_layers) {
                        return false;
                    }
                    const double raw = task_times.duration(1, requests[id].input_length) *
                                       static_cast<double>(r - l) / num_layers;
                    cloud_prefill_work_ms[cloud] = std::max(0., cloud_prefill_work_ms[cloud] - raw);
                    requests[id].next_prefill_layer = r;
                    ++requests[id].prefill_chunks_completed;
                    if (r == num_layers) {
                        set_request_phase(id, RequestPhase::prefill_download_pending);
                        record_predicted_transfer(1, cloud, false, requests[id].input_length);
                    } else {
                        set_request_phase(id, RequestPhase::prefill_proc_ready);
                    }
                    return true;
                }
                if (step == "POST") {
                    int cloud = -1, id = -1;
                    double reported_duration = 0;
                    if (!(in >> cloud >> id >> reported_duration))
                        return false;
                    if (server != "E" || !is_valid_request_id(id) || requests[id].cloud_id != cloud)
                        return false;
                    if (!advance_request_phase(
                            id, RequestPhase::prefill_post_running, RequestPhase::decode_pre_ready))
                        return false;
                    --pending_prefill_count;
                    pending_arrival_time_sum -= requests[id].arrival_time_ms;
                    completed_tdr_sum_ms += current_time_ms - requests[id].arrival_time_ms;
                    requests[id].last_token_time_ms = current_time_ms;
                    ++unopened_decode_ready_count;
                    return true;
                }
                return false;
            }
            if (family != "D")
                return false;
            int cloud = -2, member_count = 0;
            if (!(in >> cloud >> member_count) || member_count < 1)
                return false;
            std::vector<int> ids(static_cast<std::size_t>(member_count));
            for (int& id : ids) {
                if (!(in >> id))
                    return false;
            }
            double reported_duration = 0;
            if (!(in >> reported_duration))
                return false;
            if (step == "PRE") {
                if (server != "E" || cloud != -1)
                    return false;
                std::vector<int> by_cloud(num_clouds);
                for (int id : ids) {
                    if (!advance_request_phase(id,
                                               RequestPhase::decode_pre_running,
                                               RequestPhase::decode_upload_pending))
                        return false;
                    ++by_cloud[requests[id].cloud_id];
                }
                for (int target_cloud = 0; target_cloud < num_clouds; ++target_cloud) {
                    if (by_cloud[target_cloud] > 0)
                        record_predicted_transfer(0, target_cloud, true, by_cloud[target_cloud]);
                }
                return true;
            }
            if (step == "PROC") {
                int server_c = -1;
                if (!parse_cloud_id(server, server_c) || server_c != cloud || cloud < 0 ||
                    cloud >= num_clouds) {
                    return false;
                }
                for (int id : ids) {
                    if (!is_valid_request_id(id) || requests[id].cloud_id != cloud ||
                        !advance_request_phase(id,
                                               RequestPhase::decode_proc_running,
                                               RequestPhase::decode_download_pending)) {
                        return false;
                    }
                }
                record_predicted_transfer(1, cloud, true, member_count);
                return true;
            }
            if (step == "POST") {
                if (server != "E" || cloud != -1)
                    return false;
                for (int id : ids) {
                    if (!is_valid_request_id(id) ||
                        requests[id].phase != RequestPhase::decode_post_running)
                        return false;
                    Request& r = requests[id];
                    if (r.tokens_produced == 0) {
                        ++cloud_active_output_requests[r.cloud_id];
                        first_token_completion_ids.push_back(id);
                    }
                    ++r.tokens_produced;
                    ++produced_token_count;
                    r.last_token_time_ms = current_time_ms;
                    set_request_phase(id, RequestPhase::decode_pre_ready);
                }
                return true;
            }
            return false;
        }

        bool handle_transfer_completion(std::istream& in) {
            std::string direction, transfer_kind;
            int cloud = -1, member_count = 0;
            long long size = 0;
            if (!(in >> direction >> cloud >> size >> transfer_kind >> member_count) || cloud < 0 ||
                cloud >= num_clouds || size < 0 || member_count < 1) {
                return false;
            }
            std::vector<int> ids(static_cast<std::size_t>(member_count));
            for (int& id : ids) {
                if (!(in >> id))
                    return false;
            }
            if (transfer_kind == "PRE") {
                if (member_count != 1 || !is_valid_request_id(ids[0]) ||
                    requests[ids[0]].cloud_id != cloud)
                    return false;
                if (direction == "UP") {
                    reconcile_completed_transfer(0, cloud, false, size, member_count);
                    return advance_request_phase(ids[0],
                                                 RequestPhase::prefill_upload_pending,
                                                 RequestPhase::prefill_proc_ready);
                }
                if (direction == "DOWN") {
                    reconcile_completed_transfer(1, cloud, false, size, member_count);
                    return advance_request_phase(ids[0],
                                                 RequestPhase::prefill_download_pending,
                                                 RequestPhase::prefill_post_ready);
                }
                return false;
            }
            if (transfer_kind != "DEC")
                return false;
            if (direction == "UP") {
                reconcile_completed_transfer(0, cloud, true, size, member_count);
                for (int id : ids) {
                    if (!is_valid_request_id(id) || requests[id].cloud_id != cloud ||
                        !advance_request_phase(id,
                                               RequestPhase::decode_upload_pending,
                                               RequestPhase::decode_proc_ready)) {
                        return false;
                    }
                }
                return true;
            }
            if (direction == "DOWN") {
                reconcile_completed_transfer(1, cloud, true, size, member_count);
                for (int id : ids) {
                    if (!is_valid_request_id(id) || requests[id].cloud_id != cloud ||
                        !advance_request_phase(id,
                                               RequestPhase::decode_download_pending,
                                               RequestPhase::decode_post_ready)) {
                        return false;
                    }
                    const int wave_id = requests[id].decode_wave_id;
                    if (wave_id >= 0 && wave_id < static_cast<int>(decode_waves.size()))
                        ++decode_waves[wave_id].ready_members;
                }
                return true;
            }
            return false;
        }

        bool read_event(std::istream& in, std::vector<int>& finished_ids) {
            std::string event_type;
            if (!(in >> event_type))
                return false;
            if (event_type == "ARR") {
                int id = -1, input_length = 0;
                if (!(in >> id >> input_length) || id < 0 || input_length <= 0)
                    return false;
                Request& request = get_or_create_request(id);
                if (request.phase != RequestPhase::not_arrived)
                    return false;
                request.input_length = input_length;
                request.arrival_time_ms = current_time_ms;
                last_arrival_time_ms = current_time_ms;
                arrival_seen_in_frame = true;
                ++arrived_count;
                ++pending_prefill_count;
                pending_arrival_time_sum += current_time_ms;
                if (first_arrival_time_ms < 0)
                    first_arrival_time_ms = current_time_ms;
                set_request_phase(id, RequestPhase::prefill_pre_ready);
                return true;
            }
            if (event_type == "FIN") {
                int id = -1;
                if (!(in >> id) || !is_valid_request_id(id))
                    return false;
                finished_ids.push_back(id);
                return true;
            }
            if (event_type == "TDN")
                return handle_task_completion(in);
            if (event_type == "XDN")
                return handle_transfer_completion(in);
            return false;
        }

        bool finish_frame(const std::vector<int>& finished_ids) {
            std::vector<unsigned char> finishes(requests.size(), 0);
            for (int id : finished_ids) {
                if (is_valid_request_id(id))
                    finishes[id] = 1;
            }
            for (int id : first_token_completion_ids) {
                if (!is_valid_request_id(id))
                    return false;
                ++observed_first_token_count;
                if (id >= static_cast<int>(finishes.size()) || !finishes[id]) {
                    ++observed_nonterminal_first_tokens;
                }
            }
            if (arrival_seen_in_frame) {
                first_token_count_at_last_arrival = observed_first_token_count;
                arrival_seen_in_frame = false;
            }
            first_token_completion_ids.clear();
            for (int id : finished_ids) {
                if (!is_valid_request_id(id) ||
                    requests[id].phase != RequestPhase::decode_pre_ready ||
                    requests[id].tokens_produced <= 0) {
                    return false;
                }
                Request& request = requests[id];
                if (!request.counted_in_cloud_load || request.cloud_id < 0 ||
                    request.cloud_id >= num_clouds || cloud_request_load[request.cloud_id] <= 0)
                    return false;
                --cloud_request_load[request.cloud_id];
                request.counted_in_cloud_load = false;
                if (!request.decode_admitted || active_decode_requests <= 0 ||
                    cloud_decode_load[request.cloud_id] <= 0)
                    return false;
                --active_decode_requests;
                --cloud_decode_load[request.cloud_id];
                if (request.tokens_produced > 0 &&
                    cloud_active_output_requests[request.cloud_id] > 0)
                    --cloud_active_output_requests[request.cloud_id];
                request.decode_admitted = false;
                ++finished_count;
                finished_token_count += request.tokens_produced;
                if (request.tokens_produced == 1)
                    ++single_token_finished_count;
                if (request.tokens_produced > 1)
                    decode_stream_observed = true;
                set_request_phase(id, RequestPhase::finished);
            }
            if (!synchronized_decode_active() && finished_count >= 8 && w_tp > 0.10) {
                const double singleton_ratio =
                    static_cast<double>(single_token_finished_count) / finished_count;
                const double mean_tokens =
                    static_cast<double>(finished_token_count) / finished_count;
                if (singleton_ratio >= 0.75 && mean_tokens <= 1.5) {
                    const double confidence = std::min(1., (finished_count - 7) / 24.);
                    const double score_tolerance = distance_base / (distance_base + 16.);
                    const double strength =
                        confidence * (0.45 + 0.55 * w_tp) * (0.35 + 0.65 * score_tolerance);
                    const int desired = std::clamp(
                        static_cast<int>(std::lround(base_decode_window +
                                                     strength * (2000 - base_decode_window))),
                        base_decode_window,
                        2000);
                    decode_window = std::max(decode_window, desired);
                    decode_controller_max = std::max(decode_controller_max, desired);
                    if (confidence >= 0.75)
                        base_decode_window = std::max(base_decode_window, desired);
                }
            }
            return true;
        }

        std::vector<int> collect_ready_requests(std::deque<ReadyQueueEntry>& queue,
                                                RequestPhase expected_phase) {
            std::vector<int> ids;
            const std::size_t count = queue.size();
            ids.reserve(count);
            for (std::size_t i = 0; i < count; ++i) {
                const ReadyQueueEntry item = queue.front();
                queue.pop_front();
                if (!is_valid_request_id(item.request_id) ||
                    requests[item.request_id].generation != item.generation ||
                    requests[item.request_id].phase != expected_phase) {
                    continue;
                }
                ids.push_back(item.request_id);
                queue.push_back(item);
            }
            return ids;
        }

        int first_ready_id(std::deque<ReadyQueueEntry>& queue, RequestPhase expected_phase) {
            while (!queue.empty()) {
                const ReadyQueueEntry item = queue.front();
                queue.pop_front();
                if (!is_valid_request_id(item.request_id) ||
                    requests[item.request_id].generation != item.generation ||
                    requests[item.request_id].phase != expected_phase) {
                    continue;
                }
                queue.push_back(item);
                return item.request_id;
            }
            return -1;
        }

        double task_cost(int kind, int size) const {
            return task_setup_ms + task_times.duration(kind, size);
        }

        bool pure_waiting_objective() const {
            return w_tp <= 1e-12 && w_c > 1e-12;
        }

        bool pure_throughput_objective() const {
            return w_c <= 1e-15 && w_tp > 1e-15;
        }

        bool observed_single_token_workload() const {
            return observed_first_token_count >= 8 && observed_nonterminal_first_tokens == 0;
        }

        int ready_prefill_count() const {
            return ready_count_by_phase[static_cast<std::size_t>(RequestPhase::prefill_pre_ready)] +
                   ready_count_by_phase[static_cast<std::size_t>(
                       RequestPhase::prefill_proc_ready)] +
                   ready_count_by_phase[static_cast<std::size_t>(RequestPhase::prefill_post_ready)];
        }

        bool protected_startup_objective_band() const {
            return w_c >= 0.30 - 1e-12 && w_tp <= 0.52 + 1e-12 && distance_base >= 512. - 1e-12 &&
                   throughput_upper_bound <= 1. + 1e-12;
        }

        bool protected_startup_mode() const {
            return !decode_stream_observed && protected_startup_objective_band();
        }

        double throughput_pressure() const {
            return w_tp + w_c * distance_base / (distance_base + 32.);
        }

        double decode_pre_fresh_expansion_strength() const {
            if (protected_startup_objective_band()) {
                return 0.;
            }
            const double teacher_strength =
                std::clamp((throughput_pressure() - 0.985) / 0.010, 0., 1.);
            return 1. - teacher_strength;
        }

        bool protected_startup_chunk_and_prior_mode() const {
            return protected_startup_mode() && w_tp >= 0.45 - 1e-12;
        }

        bool protected_startup_prefill_guard() const {
            return protected_startup_mode() &&
                   pending_prefill_count >=
                       (observed_single_token_workload() ? 2 : std::max(2, (num_clouds + 1) / 2));
        }

        bool short_output_prefill_drain_mode() const {
            const double relative_span =
                (throughput_upper_bound - throughput_baseline) /
                std::max(1e-15,
                         std::max(std::abs(throughput_upper_bound), std::abs(throughput_baseline)));
            return w_c + 1e-12 >= w_tp && !synchronized_decode_active() &&
                   relative_span + 1e-12 >= .10 && observed_single_token_workload() &&
                   ready_prefill_count() >= std::max(2, num_clouds);
        }

        bool strict_latency_mode() const {
            return pure_waiting_objective() && distance_base <= 8. + 1e-12;
        }

        bool latency_round_robin_mode() const {
            if (strict_latency_mode())
                return true;
            if (!pure_waiting_objective())
                return false;
            const int population =
                std::clamp(std::max(1, active_decode_requests), 1, max_batch_size);
            return latency_batch_size[0][population] == 1 && latency_batch_size[2][population] == 1;
        }

        bool legacy_grouping_mode() const {
            return objective_band_code() == 1 && w_tp > w_c ||
                   objective_band_code() == 2 && w_tp < w_c ||
                   !objective_band_code() && (w_tp >= .2 && w_tp < .3 || w_tp >= .6 && w_tp < .7 ||
                                              w_tp > .95 && w_c + 1e-12 >= .02);
        }

        bool tiny_wait_weight_mode() const {
            return !legacy_grouping_mode() && w_tp >= .88 && w_c > 1e-12 && w_c <= .02 + 1e-12;
        }

        bool modeled_cloud_prefix_mode() const {
            return tiny_wait_weight_mode();
        }

        int choose_modeled_cloud_count() const {
            int population = std::min(2000, std::max(1, arrived_count - finished_count)),
                max_cloud_count = std::min(num_clouds, population);
            if (max_cloud_count < 2)
                return 1;
            double average_path_cost = 0, average_prefill_proc_cost = 0;
            for (const auto& x : requests)
                if (x.phase != RequestPhase::not_arrived) {
                    average_path_cost +=
                        task_cost(0, x.input_length) + 2 * transfer_cost_ms(x.input_length) +
                        task_cost(1, x.input_length) + task_cost(2, x.input_length);
                    average_prefill_proc_cost += task_times.duration(1, x.input_length);
                }
            average_path_cost /= std::max(1, arrived_count);
            average_prefill_proc_cost /= std::max(1, arrived_count);
            double best_score = -1e100;
            int best_cloud_count = 1;
            for (int cloud_count = 1; cloud_count <= max_cloud_count; ++cloud_count) {
                double edge_rate =
                           population / (task_cost(3, population) + task_cost(5, population)),
                       link_rate = population / (cloud_count * transfer_latency_ms +
                                                 8. * static_cast<double>(bytes_per_token) *
                                                     population / (bandwidth_gbps * 1e6)),
                       cloud_rate = 0, upload_finish = task_cost(3, population);
                std::vector<std::pair<double, int>> proc_finishes;
                for (int i = 0; i < cloud_count; ++i) {
                    int x = population / cloud_count + (i < population % cloud_count);
                    cloud_rate += x / task_cost(4, x);
                    upload_finish += transfer_cost_ms(x);
                    proc_finishes.push_back({upload_finish + task_cost(4, x), x});
                }
                double pipeline_rate = std::min({edge_rate, link_rate, cloud_rate}),
                       normalized_throughput = std::clamp(
                           (pipeline_rate - throughput_baseline) /
                               std::max(1e-15, throughput_upper_bound - throughput_baseline),
                           0.,
                           1.);
                std::sort(proc_finishes.begin(), proc_finishes.end());
                double download_finish = 0;
                for (auto completion : proc_finishes)
                    download_finish = std::max(download_finish, completion.first) +
                                      transfer_cost_ms(completion.second);
                double cycle_time = download_finish + task_cost(5, population),
                       predicted_tpot =
                           std::max(cycle_time, population / std::max(pipeline_rate, 1e-30)),
                       predicted_tdr =
                           average_path_cost +
                           average_prefill_proc_cost *
                               std::max(0., static_cast<double>(population) / cloud_count - 1.) *
                               .45,
                       tdr_excess = std::max(0., predicted_tdr / tdr_slo_ms - 1.),
                       tpot_excess = std::max(0., predicted_tpot / tpot_slo_ms - 1.),
                       distance = std::hypot(tdr_excess, tpot_excess),
                       normalized_constraint = std::max(0., 1 - distance / distance_base),
                       score = w_tp * normalized_throughput + w_c * normalized_constraint +
                               1e-5 * w_c *
                                   (normalized_constraint <= 1e-15 ? -distance / (1 + distance)
                                                                   : -distance) +
                               1e-6 * w_tp *
                                   (normalized_throughput >= 1 - 1e-15
                                        ? pipeline_rate / (1 + pipeline_rate)
                                        : pipeline_rate) -
                               1e-9 * cloud_count;
                if (score > best_score + 1e-12) {
                    best_score = score;
                    best_cloud_count = cloud_count;
                }
            }
            return best_cloud_count;
        }

        int choose_modeled_cloud(int cloud_count) const {
            double average_prefill_proc_cost = 0;
            for (const auto& request : requests)
                if (request.phase != RequestPhase::not_arrived)
                    average_prefill_proc_cost += task_times.duration(1, request.input_length);
            average_prefill_proc_cost /= std::max(1, arrived_count);
            double distance_scale = std::clamp(distance_base, .12, 8.),
                   latency_pressure = w_c / (w_c + w_tp * distance_scale), best_objective = 1e100;
            int best_cloud = 0;
            for (int c = 0; c < cloud_count; ++c) {
                int decode_count = cloud_decode_load[c];
                for (const auto& request : requests)
                    decode_count += !request.decode_admitted && request.cloud_id == c &&
                                    request.phase == RequestPhase::decode_pre_ready;
                double prefill_count = cloud_request_load[c],
                       objective =
                           (1 - latency_pressure) *
                               (prefill_count * average_prefill_proc_cost +
                                .35 * decode_count * task_cost(4, std::max(1, decode_count))) +
                           latency_pressure *
                               (cloud_prefill_work_ms[c] +
                                std::max(0., cloud_predicted_busy_until_ms[c] - current_time_ms) +
                                .25 * prefill_count * average_prefill_proc_cost) +
                           1e-7 * c;
                if (objective < best_objective) {
                    best_objective = objective;
                    best_cloud = c;
                }
            }
            return best_cloud;
        }

        int aged_batch_size(int stage, const std::vector<int>& ids) const {
            double max_age_ratio = 0;
            for (int id : ids)
                max_age_ratio = std::max(
                    max_age_ratio,
                    (current_time_ms - requests[id].last_token_time_ms) /
                        std::max(1e-9, tpot_slo_ms * (requests[id].tokens_produced ? 1. : 2.)));
            int quality_level = 5;
            if (max_age_ratio > 1.15)
                --quality_level;
            if (max_age_ratio > 1.8)
                --quality_level;
            return throughput_batch_threshold(stage, static_cast<int>(ids.size()), quality_level);
        }

        int choose_legacy_prefill_chunk_end(int id, int cloud) const {
            const auto& request = requests[id];
            int remaining_layers = num_layers - request.next_prefill_layer;
            if (remaining_layers <= 1 || num_layers <= 1 || !cloud_active_output_requests[cloud])
                return num_layers;
            double full_raw_cost = task_times.duration(1, request.input_length),
                   per_layer_cost = full_raw_cost / num_layers,
                   latency_pressure = assignment_latency_pressure(),
                   quantum = tpot_slo_ms * (.14 + 1.35 * (1 - latency_pressure));
            quantum = std::max(quantum, task_setup_ms * (1.25 + 2.5 * (1 - latency_pressure)));
            double age_ratio =
                (current_time_ms - request.arrival_time_ms) / std::max(1e-9, tdr_slo_ms);
            if (age_ratio > .72)
                quantum *= 1 + 3 * (age_ratio - .72) * std::max(.25, latency_pressure);
            auto next_transfer = next_predicted_decode_transfer(0, cloud);
            if (std::isfinite(next_transfer.first) && next_transfer.first > current_time_ms &&
                latency_pressure > .25)
                quantum = std::min(quantum,
                                   std::max(task_setup_ms + per_layer_cost,
                                            (next_transfer.first - current_time_ms) * .95));
            int layers_to_take = std::max(
                1,
                static_cast<int>(std::floor(std::max(per_layer_cost, quantum - task_setup_ms) /
                                                std::max(1e-15, per_layer_cost) +
                                            1e-10)));
            layers_to_take = std::min(layers_to_take, remaining_layers);
            int end_layer = request.next_prefill_layer + layers_to_take;
            bool downstream_decode_pressure =
                std::any_of(cloud_active_output_requests.begin(),
                            cloud_active_output_requests.end(),
                            [](int v) { return v > 0; }) &&
                (transfer_cost_ms(request.input_length) > .18 * tpot_slo_ms ||
                 link_available_time_ms[1] - current_time_ms > .12 * tpot_slo_ms ||
                 std::any_of(requests.begin(), requests.end(), [](const Request& r) {
                     return r.phase == RequestPhase::decode_download_pending ||
                            r.phase == RequestPhase::decode_proc_running;
                 }));
            double slack_ratio = (request.arrival_time_ms + tdr_slo_ms -
                                  (current_time_ms + remaining_prefill_path_cost(id, 2))) /
                                 std::max(1e-9, tdr_slo_ms);
            if (end_layer == num_layers && downstream_decode_pressure && latency_pressure > .35 &&
                slack_ratio > .08 && request.next_prefill_layer < num_layers - 1)
                --end_layer;
            return std::max(request.next_prefill_layer + 1, end_layer);
        }

        bool prefer_decode_over_prefill(int prefill_id, const std::vector<int>& decode_ids) const {
            int decode_batch_size = static_cast<int>(decode_ids.size());
            double latency_pressure = assignment_latency_pressure(),
                   decode_finish_time = current_time_ms + task_cost(4, decode_batch_size) +
                                        transfer_cost_ms(decode_batch_size) +
                                        task_cost(5, decode_batch_size),
                   earliest_decode_deadline = std::numeric_limits<double>::infinity();
            for (int id : decode_ids)
                earliest_decode_deadline = std::min(
                    earliest_decode_deadline,
                    requests[id].tokens_produced
                        ? requests[id].last_token_time_ms + tpot_slo_ms
                        : current_time_ms + (1.5 + 1.5 * (1 - latency_pressure)) * tpot_slo_ms);
            double decode_slack = (earliest_decode_deadline - decode_finish_time) / tpot_slo_ms;
            const auto& prefill_request = requests[prefill_id];
            double prefill_finish_time =
                       current_time_ms + task_setup_ms +
                       task_times.duration(1, prefill_request.input_length) *
                           static_cast<double>(num_layers - prefill_request.next_prefill_layer) /
                           num_layers +
                       transfer_cost_ms(prefill_request.input_length) +
                       task_cost(2, prefill_request.input_length),
                   prefill_slack =
                       (prefill_request.arrival_time_ms + tdr_slo_ms - prefill_finish_time) /
                       tdr_slo_ms,
                   decode_efficiency = static_cast<double>(decode_batch_size) /
                                       task_cost(4, decode_batch_size) /
                                       (static_cast<double>(preferred_decode_proc_batch) /
                                        task_cost(4, preferred_decode_proc_batch)),
                   decode_score = 4.5 + 1.2 * (1 - latency_pressure) * decode_efficiency -
                                  latency_pressure * decode_slack +
                                  .14 * std::log1p(static_cast<double>(decode_batch_size)),
                   prefill_score = (has_active_decode_output() ? 2.05 : 5) +
                                   1.8 * latency_pressure - latency_pressure * prefill_slack;
            if (has_active_decode_output())
                prefill_score -=
                    latency_pressure *
                    std::min(3.,
                             transfer_cost_ms(prefill_request.input_length) / tpot_slo_ms +
                                 std::max(0., link_available_time_ms[1] - current_time_ms) /
                                     tpot_slo_ms);
            return std::min(decode_slack, prefill_slack) < .12 + .42 * latency_pressure
                       ? decode_slack <= prefill_slack
                       : decode_score >= prefill_score;
        }

        double edge_choice_score(const EdgeTaskChoice& choice) const {
            double latency_pressure =
                       w_c / std::max(1e-15, w_c + w_tp * std::clamp(distance_base, .12, 8.)),
                   request_count = choice.request_ids.size(), efficiency = 0, score = 0;
            if (choice.task_kind == EdgeTaskKind::decode_post) {
                int best_batch = best_batch_size[2][max_batch_size];
                efficiency = request_count /
                             std::max(1e-15, task_cost(5, static_cast<int>(request_count))) /
                             (best_batch / std::max(1e-15, task_cost(5, best_batch)));
                score = 5.25 + 1.15 * (1 - latency_pressure) * efficiency +
                        .16 * std::log1p(request_count) - latency_pressure * choice.priority_key;
            } else if (choice.task_kind == EdgeTaskKind::decode_pre) {
                int best_batch = best_batch_size[0][max_batch_size];
                efficiency = request_count /
                             std::max(1e-15, task_cost(3, static_cast<int>(request_count))) /
                             (best_batch / std::max(1e-15, task_cost(3, best_batch)));
                score = 3.8 + 1.2 * (1 - latency_pressure) * efficiency +
                        .18 * std::log1p(request_count) - latency_pressure * choice.priority_key;
            } else
                score = choice.task_kind == EdgeTaskKind::prefill_post
                            ? 4.45 + 2 * latency_pressure - latency_pressure * choice.priority_key
                            : 2 + 1.7 * latency_pressure - latency_pressure * choice.priority_key;
            return score;
        }

        bool should_wait_for_modeled_cloud_prefix() const {
            return modeled_cloud_prefix_mode() && !produced_token_count &&
                   pending_prefill_count > 0 &&
                   ready_count_by_phase[static_cast<std::size_t>(RequestPhase::decode_pre_ready)] <
                       std::max(2,
                                throughput_batch_threshold(
                                    0,
                                    std::min(2000, std::max(1, arrived_count - finished_count)),
                                    5)) &&
                   has_internal_future();
        }

        int cloud_decode_population(int cloud) const {
            int population = cloud_decode_load[cloud];
            for (const auto& request : requests)
                population += !request.decode_admitted && request.cloud_id == cloud &&
                              request.phase == RequestPhase::decode_pre_ready;
            return population;
        }

        std::pair<double, int> next_decode_downstream_completion() const {
            auto next_completion = next_predicted_decode_transfer(1);
            for (double busy_until : cloud_predicted_busy_until_ms)
                if (std::isfinite(busy_until) && busy_until >= current_time_ms - 1e-9 &&
                    busy_until + transfer_cost_ms(1) < next_completion.first)
                    next_completion = {busy_until + transfer_cost_ms(1), 1};
            return next_completion;
        }

        bool should_hold_for_next_transfer(int stage,
                                           int current_size,
                                           int population,
                                           std::pair<double, int> future) const {
            if (!tiny_wait_weight_mode() || current_size < 1 || future.second < 1 ||
                !std::isfinite(future.first) || future.first < current_time_ms - 1e-9)
                return false;
            population = std::min(2000, std::max(current_size, population));
            if (current_size >= throughput_batch_threshold(stage, population, 5))
                return false;
            double saved_time = task_cost(3 + stage, current_size) + task_cost(3 + stage, 1) -
                                task_cost(3 + stage, current_size + 1);
            return saved_time > 1e-12 &&
                   future.first - current_time_ms <= (.55 + .4 * w_tp) * saved_time + 1e-9;
        }

        bool should_hold_decode_post_for_wave(const std::vector<int>& ids) const {
            if (ids.empty() || !has_internal_future())
                return false;
            int wave_id = requests[ids[0]].decode_wave_id;
            if (wave_id < 0 || wave_id >= static_cast<int>(decode_waves.size()) ||
                decode_waves[wave_id].ready_members >= decode_waves[wave_id].remaining_members)
                return false;
            const auto& request = requests[ids[0]];
            double ready_age = std::max(0., current_time_ms - request.ready_since_ms),
                   token_age =
                       request.tokens_produced ? current_time_ms - request.last_token_time_ms : 0,
                   latency_pressure =
                       w_c / std::max(1e-15, w_c + w_tp * std::clamp(distance_base, .12, 8.)),
                   hold_budget = tpot_slo_ms * (.012 + .36 * (1 - latency_pressure));
            if (!request.tokens_produced)
                hold_budget *= 1.5;
            if (ready_age >= hold_budget ||
                request.tokens_produced &&
                    token_age / std::max(1e-9, tpot_slo_ms) > .78 + .35 * (1 - latency_pressure))
                return false;
            double next_completion_time = next_decode_downstream_completion().first;
            return std::isfinite(next_completion_time) &&
                   next_completion_time - current_time_ms <=
                       std::max(0., hold_budget - ready_age) + 1e-9;
        }

        double predicted_prefill_completion_time(int id, int cloud) const {
            const auto& request = requests[id];
            double edge_finish = current_time_ms + task_cost(0, request.input_length),
                   upload_finish = std::max(link_available_time_ms[0], edge_finish) +
                                   transfer_cost_ms(request.input_length),
                   queued_cloud_work = std::max(
                       0., cloud_prefill_work_ms[cloud] - cloud_running_prefill_work_ms[cloud]);
            int queued_jobs = 0;
            for (const auto& other_request : requests)
                queued_jobs += other_request.cloud_id == cloud &&
                               (other_request.phase == RequestPhase::prefill_pre_running ||
                                other_request.phase == RequestPhase::prefill_upload_pending ||
                                other_request.phase == RequestPhase::prefill_proc_ready ||
                                other_request.phase == RequestPhase::prefill_proc_running);
            queued_jobs -= cloud_running_prefill_work_ms[cloud] > 0;
            queued_cloud_work += task_setup_ms * queued_jobs;
            double completion_time = std::max(upload_finish, cloud_predicted_busy_until_ms[cloud]) +
                                     queued_cloud_work + task_cost(1, request.input_length);
            completion_time = std::max(link_available_time_ms[1], completion_time) +
                              transfer_cost_ms(request.input_length);
            return std::max(completion_time, edge_finish) + task_cost(2, request.input_length);
        }

        int throughput_batch_threshold(int stage, int population, int quality_level) const {
            double target_ratio = quality_level < 1   ? .82
                                  : quality_level < 2 ? .88
                                  : quality_level < 3 ? .93
                                  : quality_level < 4 ? .97
                                  : quality_level < 5 ? .99
                                                      : .999999999,
                   best_rate = 0;
            for (int batch_size = 1; batch_size <= population; ++batch_size)
                best_rate = std::max(best_rate,
                                     batch_size / (task_cost(3 + stage, batch_size) +
                                                   (stage < 2 ? transfer_cost_ms(batch_size) : 0)));
            int batch_size = 1;
            while (batch_size < population &&
                   batch_size / (task_cost(3 + stage, batch_size) +
                                 (stage < 2 ? transfer_cost_ms(batch_size) : 0)) +
                           1e-15 <
                       target_ratio * best_rate)
                ++batch_size;
            return batch_size;
        }

        bool should_hold_synchronized_decode_pre(int n) const {
            return legacy_grouping_mode() && !produced_token_count && pending_prefill_count > 0 &&
                   n < std::max(2,
                                throughput_batch_threshold(
                                    0,
                                    std::min(2000, std::max(1, arrived_count - finished_count)),
                                    5)) &&
                   has_internal_future();
        }

        bool should_hold_decode_pre(int n) const {
            return legacy_grouping_mode() && (distance_base >= 64. || !produced_token_count) &&
                   pending_prefill_count > 0 &&
                   n < std::max(2,
                                throughput_batch_threshold(
                                    0,
                                    std::min(2000, std::max(1, arrived_count - finished_count)),
                                    5)) &&
                   has_internal_future();
        }

        int group_size(int step, int ready) const {
            if (ready <= 0)
                return 0;
            if (strict_latency_mode())
                return 1;
            if (pure_waiting_objective() && ready <= max_batch_size)
                return latency_batch_size[step][ready];
            if (ready <= max_batch_size)
                return best_batch_size[step][ready];
            int best = 1;
            double best_unit = std::numeric_limits<double>::infinity();
            for (int size = 1; size <= ready; ++size) {
                const double unit = task_cost(3 + step, size) / size;
                const double eps =
                    std::isfinite(best_unit) ? 1e-12 * std::max(1., std::abs(best_unit)) : 0;
                if (!std::isfinite(best_unit) || unit < best_unit - eps ||
                    (std::abs(unit - best_unit) <= eps && size > best)) {
                    best = size;
                    best_unit = unit;
                }
            }
            return best;
        }

        double decode_wait_weight(int id) const {
            const Request& request = requests[id];
            if (request.tokens_produced <= 0)
                return 0;
            const double age = std::max(0., current_time_ms - request.last_token_time_ms) /
                               std::max(1e-9, tpot_slo_ms);
            const double excess = std::max(0., age - 1.);
            return 0.10 + std::min(3., age) + .5 * std::min(4., excess * excess);
        }

        std::vector<int> dynamic_batch_candidates(int step, int ready) const {
            std::vector<int> candidate;
            candidate.reserve(40);
            const auto add = [&](int size) {
                if (size >= 1 && size <= ready)
                    candidate.push_back(size);
            };
            const int legacy = group_size(step, ready);
            add(1);
            add(legacy);
            add(ready);
            add(legacy / 2);
            add((legacy + 1) / 2);
            add(legacy * 2);
            for (int divisor : {2, 3, 4, 6, 8}) {
                const int part = (ready + divisor - 1) / divisor;
                add(part);
                add(ready - part);
                add(group_size(step, part));
            }
            for (int size = 2; size < ready; size *= 2)
                add(size);
            std::sort(candidate.begin(), candidate.end());
            candidate.erase(std::unique(candidate.begin(), candidate.end()), candidate.end());
            return candidate;
        }

        double downstream_tail(int step, int size, const std::vector<int>& ids) const {
            if (step == 2 || size <= 0)
                return 0;
            if (step == 1) {
                const int ready =
                    ready_count_by_phase[static_cast<std::size_t>(RequestPhase::decode_post_ready)];
                return transfer_cost_ms(size) +
                       task_cost(5, std::min(max_batch_size, ready + size));
            }
            std::vector<int> by_cloud(num_clouds);
            const int take = std::min(size, static_cast<int>(ids.size()));
            for (int i = 0; i < take; ++i)
                ++by_cloud[requests[ids[i]].cloud_id];
            if (take < size) {
                for (int i = take; i < size; ++i)
                    ++by_cloud[i % num_clouds];
            }
            double uplink_time = 0;
            double remote_time = 0;
            for (int cloud = 0; cloud < num_clouds; ++cloud) {
                if (by_cloud[cloud] == 0)
                    continue;
                uplink_time += transfer_cost_ms(by_cloud[cloud]);
                const int merged =
                    std::min(max_batch_size, decode_proc_ready_count[cloud] + by_cloud[cloud]);
                remote_time =
                    std::max(remote_time, task_cost(4, merged) + transfer_cost_ms(by_cloud[cloud]));
            }
            const int ready =
                ready_count_by_phase[static_cast<std::size_t>(RequestPhase::decode_post_ready)];
            return uplink_time + remote_time + task_cost(5, std::min(max_batch_size, ready + size));
        }

        int dynamic_group_size(int step, const std::vector<int>& ids) const {
            const int ready = static_cast<int>(ids.size());
            if (strong_waiting_fallback_mode())
                return group_size(step, ready);
            if (ready <= 1)
                return ready;
            if (strict_latency_mode())
                return 1;
            if (pure_waiting_objective() && ready <= max_batch_size)
                return latency_batch_size[step][ready];
            if (step != 1 || w_tp <= 1e-12 || w_tp >= 0.95 - 1e-12 ||
                transfer_latency_ms > task_setup_ms || decode_admission_limited) {
                return group_size(step, ready);
            }
            std::vector<double> prefix(static_cast<std::size_t>(ready) + 1);
            for (int i = 0; i < ready; ++i) {
                prefix[i + 1] = prefix[i] + decode_wait_weight(ids[i]);
            }
            const double total_weight = prefix.back();
            const double distance_scale = std::max(1., distance_base);
            const double wait_factor = w_c / distance_scale;
            double throughput_factor = w_tp;
            if (produced_token_count >= 64) {
                throughput_factor *= std::max(0.05, 1. - online_normalized_throughput());
            }
            throughput_factor += 2. * w_c;
            const std::vector<int> candidate = dynamic_batch_candidates(step, ready);
            const int legacy_size = group_size(step, ready);
            int best_size = legacy_size;
            double best_value = std::numeric_limits<double>::infinity();
            double legacy_value = std::numeric_limits<double>::infinity();
            for (int size : candidate) {
                const double first_service = task_cost(3 + step, size);
                const int remaining = ready - size;
                const int future_group = remaining > 0 ? group_size(step, remaining) : 0;
                const double future_unit =
                    remaining > 0 ? task_cost(3 + step, future_group) / future_group : 0;
                const double future_service = future_unit * remaining;
                const double first_tail = downstream_tail(step, size, ids);
                const double future_tail =
                    remaining > 0 ? downstream_tail(step, future_group, {}) : 0;
                const double first_weight = prefix[size];
                const double later_weight = total_weight - first_weight;
                const double wait_area =
                    first_weight * (first_service + first_tail) +
                    later_weight * (first_service + .5 * future_service + future_tail);
                const double makespan =
                    first_service + future_service + std::max(first_tail, future_tail);
                const double value = wait_factor * wait_area + throughput_factor * ready * makespan;
                if (size == legacy_size)
                    legacy_value = value;
                const double eps =
                    std::isfinite(best_value) ? 1e-10 * std::max(1., std::abs(best_value)) : 0;
                if (!std::isfinite(best_value) || value < best_value - eps ||
                    (std::abs(value - best_value) <= eps && size == legacy_size)) {
                    best_value = value;
                    best_size = size;
                }
            }
            const double relative_gain =
                (legacy_value - best_value) / std::max(1e-12, std::abs(legacy_value));
            if (relative_gain < 0.04 - 1e-12)
                best_size = legacy_size;
            if (best_size != legacy_size &&
                (transfer_cost_ms(legacy_size) > 0.60 * task_cost(4, legacy_size) ||
                 transfer_cost_ms(best_size) > 0.60 * task_cost(4, best_size))) {
                best_size = legacy_size;
            }
            return best_size;
        }

        double transfer_cost_ms(int len) const {
            return transfer_latency_ms +
                   8. * static_cast<double>(bytes_per_token) * len / (bandwidth_gbps * 1e6);
        }

        double batch_hold_strength() const {
            if (w_tp <= 1e-15)
                return 0.;
            if (w_c <= 1e-15)
                return 0.95;
            const double tolerance = distance_base / (distance_base + 16.);
            const double effective = w_tp + w_c * tolerance;
            return std::clamp((effective - 0.82) / 0.18, 0., 1.) * (0.55 + 0.40 * w_tp);
        }

        bool should_hold_for_known_transfer(int step,
                                            int current,
                                            std::pair<double, int> future) const {
            if (current <= 0 || future.second <= 0 || !std::isfinite(future.first) ||
                future.first <= current_time_ms + 1e-9 ||
                current + future.second > max_batch_size) {
                return false;
            }
            double strength = batch_hold_strength();
            if (long_prefill_risk_mode() && arrived_count > 0 && pending_prefill_count == 0)
                strength = std::max(strength, .25);
            if (strength <= 1e-12)
                return false;
            const auto [g1, g2] = waiting_guard();
            const double risk = std::hypot(std::max(0., g1 - 1.), std::max(0., g2 - 1.));
            if ((distance_base <= 1e-15 && risk > 1e-12) ||
                (distance_base > 1e-15 && risk >= 0.75 * distance_base)) {
                return false;
            }
            const double separate =
                task_cost(3 + step, current) + task_cost(3 + step, future.second);
            const double merged = task_cost(3 + step, current + future.second);
            const double saved = separate - merged;
            return saved > 1e-12 && future.first - current_time_ms <= strength * saved + 1e-9;
        }

        bool prefill_chunk_mode() const {
            return num_layers > 1 && w_tp > 1e-12 && w_tp < .25 - 1e-12 && w_c >= 0.75 - 1e-12 &&
                   distance_base >= 100.;
        }

        double remaining_prefill_path_cost(int id, int extra_pieces = 1) const {
            const Request& request = requests[id];
            const double fraction =
                static_cast<double>(num_layers - request.next_prefill_layer) / num_layers;
            return extra_pieces * task_setup_ms +
                   fraction * task_times.duration(1, request.input_length) +
                   transfer_cost_ms(request.input_length) + task_cost(2, request.input_length);
        }

        int choose_prefill_proc_end_layer(int id, int cloud) const {
            const Request& fallback_request = requests[id];
            int fallback_remaining_layers = num_layers - fallback_request.next_prefill_layer;
            if (strong_waiting_fallback_mode()) {
                bool latency_stressed =
                         runtime_fallback_enabled ||
                         minimum_prefill_path_ms > tdr_slo_ms * (1. + distance_base) ||
                         (w_c >= .5 - 1e-12 && distance_base <= .25 + 1e-12),
                     high_wait_weight = w_c >= .8 - 1e-12;
                int competing_decode_count = 0;
                for (const Request& other_request : requests)
                    competing_decode_count += other_request.cloud_id == cloud &&
                                              other_request.phase != RequestPhase::not_arrived &&
                                              other_request.phase != RequestPhase::finished &&
                                              !is_prefill_phase(other_request.phase);
                double raw = task_times.duration(1, fallback_request.input_length),
                       fallback_remaining_raw = raw * fallback_remaining_layers / num_layers,
                       path = task_setup_ms + fallback_remaining_raw +
                              transfer_cost_ms(fallback_request.input_length) +
                              task_cost(2, fallback_request.input_length);
                bool urgent =
                    !latency_stressed &&
                    current_time_ms + path >= fallback_request.arrival_time_ms +
                                                  (high_wait_weight ? .8 : 1.) * tdr_slo_ms;
                int max_pieces = runtime_fallback_enabled ? 4
                                 : latency_stressed       ? (w_c >= .5    ? 16
                                                             : w_c >= .15 ? 8
                                                                          : 4)
                                 : high_wait_weight       ? 16
                                                          : 8,
                    fallback_representative =
                        std::max(1, std::min(cloud_request_load[cloud], 2000));
                double fallback_quantum =
                    high_wait_weight && !latency_stressed
                        ? std::max({2 * task_setup_ms,
                                    1.1 * task_cost(4, fallback_representative),
                                    .2 * tpot_slo_ms})
                        : std::max({3 * task_setup_ms,
                                    1.25 * task_cost(4, fallback_representative),
                                    .3 * tpot_slo_ms});
                bool should_split =
                    (!runtime_fallback_enabled && latency_stressed) || !runtime_fallback_enabled ||
                    w_tp >= .88 ||
                    (raw >= 24 * task_setup_ms &&
                     (max_pieces - 1) * task_setup_ms <= .25 * fallback_remaining_raw);
                if (competing_decode_count && !urgent && should_split &&
                    fallback_remaining_raw > 1.35 * fallback_quantum) {
                    double fallback_per_layer = raw / num_layers;
                    int minimum_layers = (num_layers + max_pieces - 1) / max_pieces,
                        quantum_layers = std::max(
                            1, static_cast<int>(std::floor(fallback_quantum / fallback_per_layer)));
                    return std::min(num_layers,
                                    fallback_request.next_prefill_layer +
                                        std::max(minimum_layers, quantum_layers));
                }
                return num_layers;
            }
            const Request& request = requests[id];
            const int remaining = num_layers - request.next_prefill_layer;
            if (tiny_wait_weight_mode())
                return choose_legacy_prefill_chunk_end(id, cloud);
            if (enable_protected_startup_prefill_chunking &&
                protected_startup_chunk_and_prior_mode()) {
                if (remaining <= 1 ||
                    request.prefill_chunks_completed >= protected_startup_max_prefill_chunks - 1)
                    return num_layers;
                const bool decode_competition = cloud_decode_load[cloud] > 0;
                int same_cloud_ready = 0;
                for (const Request& other : requests) {
                    same_cloud_ready +=
                        other.phase == RequestPhase::prefill_proc_ready && other.cloud_id == cloud;
                }
                if (!decode_competition && same_cloud_ready <= 1) {
                    return num_layers;
                }
                const double full_raw = task_times.duration(1, request.input_length);
                const double remaining_raw = full_raw * remaining / num_layers;
                if (remaining_raw <= 4 * task_setup_ms + 1e-12)
                    return num_layers;
                const double overhead_fraction = .025 + .155 * std::clamp(w_c + .20, 0., 1.);
                const double overhead_floor = task_setup_ms / std::max(.01, overhead_fraction);
                const int representative = std::clamp(
                    std::max(1, std::min(cloud_decode_load[cloud], preferred_decode_proc_batch)),
                    1,
                    64);
                double quantum =
                    std::max(overhead_floor, (1.05 + .45 * w_tp) * task_cost(4, representative));
                if (decode_competition) {
                    quantum = std::max(quantum, (.16 + .34 * w_tp) * std::max(tpot_slo_ms, 1e-9));
                }
                quantum =
                    std::min(quantum, std::max(overhead_floor, .08 * std::max(tdr_slo_ms, 1e-9)));
                const double per_layer = full_raw / num_layers;
                const int minimum_layers = (remaining + protected_startup_max_prefill_chunks - 1) /
                                           protected_startup_max_prefill_chunks;
                const double modeled_take = std::floor(
                    std::max(per_layer, quantum - task_setup_ms) / std::max(1e-15, per_layer) +
                    1e-12);
                int take = std::max(minimum_layers,
                                    static_cast<int>(std::min<double>(remaining, modeled_take)));
                take = std::clamp(take, 1, remaining);
                if (take >= remaining)
                    return num_layers;
                const int pieces = (remaining + take - 1) / take;
                if (static_cast<double>(pieces - 1) * task_setup_ms >
                    overhead_fraction * remaining_raw + 1e-12) {
                    return num_layers;
                }
                return request.next_prefill_layer + take;
            }
            if (remaining <= 1 || request.prefill_chunks_completed >= 3 || !prefill_chunk_mode())
                return num_layers;
            const auto future = next_predicted_decode_transfer(0, cloud);
            const bool decode_sensitive =
                cloud_active_output_requests[cloud] > 0 || std::isfinite(future.first);
            if (!decode_sensitive)
                return num_layers;
            const double full_raw = task_times.duration(1, request.input_length);
            const double per_layer = full_raw / num_layers;
            const double remaining_raw = per_layer * remaining;
            const int representative =
                std::max(1,
                         std::min({max_batch_size,
                                   std::max(1, cloud_decode_load[cloud]),
                                   std::max(1, preferred_decode_proc_batch)}));
            const double pressure = assignment_latency_pressure();
            double quantum = std::max({task_setup_ms + per_layer,
                                       0.85 * task_cost(4, representative),
                                       tpot_slo_ms * (0.14 + 1.05 * (1. - pressure))});
            if (std::isfinite(future.first) && future.first > current_time_ms) {
                quantum = std::min(
                    quantum,
                    std::max(task_setup_ms + per_layer, 0.92 * (future.first - current_time_ms)));
            }
            if (task_setup_ms > 0.10 * remaining_raw ||
                task_setup_ms + remaining_raw <= 1.35 * quantum) {
                return num_layers;
            }
            int take = static_cast<int>(
                std::floor((quantum - task_setup_ms) / std::max(1e-15, per_layer) + 1e-10));
            take = std::clamp(take, 1, remaining);
            return request.next_prefill_layer + take;
        }

        bool should_defer_prefill_proc_for_decode_transfer(int cloud,
                                                           int prefill_id,
                                                           int right) const {
            const auto future = next_predicted_decode_transfer(0, cloud);
            if (!std::isfinite(future.first) || future.first <= current_time_ms + 1e-9 ||
                cloud_active_output_requests[cloud] <= 0)
                return false;
            const Request& r = requests[prefill_id];
            const double raw = task_times.duration(1, r.input_length) *
                               static_cast<double>(right - r.next_prefill_layer) / num_layers;
            const double block = task_setup_ms + raw;
            const double delay = future.first - current_time_ms;
            if (delay >= 0.82 * block || assignment_latency_pressure() < 0.20 - 1e-12) {
                return false;
            }
            const double slack = r.arrival_time_ms + tdr_slo_ms -
                                 (current_time_ms + remaining_prefill_path_cost(prefill_id, 2));
            return slack > 0.06 * tdr_slo_ms;
        }

        double age_bonus(const std::vector<int>& ids, double scale) const {
            if (ids.empty())
                return 0;
            double oldest = 0;
            for (int id : ids)
                oldest = std::max(oldest, current_time_ms - requests[id].ready_since_ms);
            return 0.08 * std::min(4., oldest / std::max(1e-9, scale));
        }

        bool long_prefill_risk_mode() const {
            const double ratio = throughput_upper_bound / std::max(1e-15, throughput_baseline);
            return w_tp >= 0.20 - 1e-12 && w_tp <= 0.40 + 1e-12 && w_c > w_tp &&
                   distance_base >= 24. && distance_base <= 64. && ratio >= 8.;
        }

        int objective_band_code() const {
            return w_tp > .09 && w_tp < .2   ? 2
                   : w_tp > .7 && w_tp < .95 ? 1 + (w_tp < .86)
                                             : w_tp > 0 && w_tp < .1;
        }

        double prefill_priority_key(int id, double remaining, double stage_bonus) const {
            bool alternate_ordering =
                (objective_band_code() ||
                 w_tp == w_c && throughput_upper_bound <= .01 && produced_token_count == 0) &&
                (stage_bonus < .05 || objective_band_code() > 1 && stage_bonus > .1);
            const double scale = std::max(1e-9, tdr_slo_ms);
            if (long_prefill_risk_mode() && !alternate_ordering) {
                double offset = 1. - 0.05 * w_c;
                if (stage_bonus > 0.30) {
                    offset = 0.75 - 0.15 * w_c;
                } else if (stage_bonus > 0.10) {
                    offset = 1. - 0.10 * w_c;
                }
                const double ready_age = (current_time_ms - requests[id].ready_since_ms) / scale;
                return -(current_time_ms - requests[id].arrival_time_ms) / scale +
                       .25 * remaining / scale + offset - 0.08 * std::min(4., ready_age);
            }
            const double norm_tp = online_normalized_throughput();
            const double headroom = w_tp * (1. - norm_tp);
            const bool moderate_risk = w_tp >= 0.85 - 1e-12 && w_tp < 0.95 - 1e-12 &&
                                       distance_base >= 100. && distance_base < 1200.;
            const bool spent_waiting =
                w_tp >= 0.95 - 1e-12 && w_tp < 1. - 1e-12 && distance_base <= 16.;
            const bool neutral_prefill_order = w_tp >= 0.72 - 1e-12 && w_tp < 0.88 - 1e-12 &&
                                               distance_base >= 512. && distance_base <= 8192. &&
                                               headroom >= 0.15;
            double alpha = .5 + .5 * w_c;
            if (headroom >= 0.12 && (moderate_risk || spent_waiting))
                alpha = (legacy_grouping_mode() || modeled_cloud_prefix_mode()) && spent_waiting &&
                                distance_base > 1e-15
                            ? .125
                            : -1.;
            if (neutral_prefill_order && stage_bonus < 0.05)
                alpha = 0;
            double blend_strength = alternate_ordering
                                        ? 1
                                        : (throughput_upper_bound <= 1 + 1e-12) *
                                              std::clamp(1 - std::abs(w_tp - w_c) / .04, 0., 1.) *
                                              std::clamp((distance_base - 256) / 256., 0., 1.);
            double stage_offset = -stage_bonus;
            if (blend_strength > 0) {
                double risk_offset = 1 - .05 * w_c;
                if (stage_bonus > .3)
                    risk_offset = .75 - .15 * w_c;
                else if (stage_bonus > .1)
                    risk_offset = 1 - .1 * w_c;
                double ready_age = (current_time_ms - requests[id].ready_since_ms) / scale;
                alpha += blend_strength * (-1 - alpha);
                stage_offset +=
                    blend_strength * (risk_offset + stage_bonus - .08 * std::min(4., ready_age));
            }
            return -(current_time_ms - requests[id].arrival_time_ms) / scale +
                   alpha * remaining / scale + stage_offset;
        }

        int prefill_post_skip_limit() const {
            if (throughput_upper_bound <= 1 + 1e-12 && std::abs(w_tp - w_c) < .04 &&
                distance_base >= 512)
                return 1000000;
            if (w_tp >= 0.95 - 1e-12)
                return 32;
            return 2 + static_cast<int>(std::lround(14. * w_tp));
        }

        int prefill_work_skip_limit() const {
            if (throughput_upper_bound <= 1 + 1e-12 && std::abs(w_tp - w_c) < .04 &&
                distance_base >= 512)
                return 1000000;
            if (w_tp >= 0.95 - 1e-12)
                return 32;
            return 4 + static_cast<int>(std::lround(28. * w_tp));
        }

        static void update_skip_counter(int& skip, bool ready, bool selected) {
            if (!ready || selected)
                skip = 0;
            else
                skip = std::min(skip + 1, 1000000);
        }

        bool is_prefill_phase(RequestPhase st) const {
            return st == RequestPhase::prefill_pre_ready ||
                   st == RequestPhase::prefill_pre_running ||
                   st == RequestPhase::prefill_upload_pending ||
                   st == RequestPhase::prefill_proc_ready ||
                   st == RequestPhase::prefill_proc_running ||
                   st == RequestPhase::prefill_download_pending ||
                   st == RequestPhase::prefill_post_ready ||
                   st == RequestPhase::prefill_post_running;
        }

        double online_normalized_throughput() const {
            const double span = throughput_upper_bound - throughput_baseline;
            const double elapsed = current_time_ms - first_arrival_time_ms;
            if (span <= 1e-12 || first_arrival_time_ms < 0 || elapsed <= 1e-12)
                return 0;
            const double throughput = static_cast<double>(produced_token_count) / elapsed;
            return std::clamp((throughput - throughput_baseline) / span, 0., 1.);
        }

        std::pair<double, double> waiting_guard() const {
            double tdr_guard = 0, tpot_guard = 0;
            const double tdr_scale = std::max(1e-9, tdr_slo_ms);
            const double tpot_scale = std::max(1e-9, tpot_slo_ms);
            for (const Request& r : requests) {
                if (is_prefill_phase(r.phase)) {
                    tdr_guard =
                        std::max(tdr_guard, (current_time_ms - r.arrival_time_ms) / tdr_scale);
                }
                if (r.decode_admitted && r.tokens_produced > 0) {
                    tpot_guard =
                        std::max(tpot_guard, (current_time_ms - r.last_token_time_ms) / tpot_scale);
                }
            }
            return {tdr_guard, tpot_guard};
        }

        void update_runtime_fallback() {
            if (runtime_fallback_enabled || w_tp <= 1e-12 ||
                arrived_count < std::max(16, 4 * num_clouds) ||
                minimum_prefill_path_ms > tdr_slo_ms * (1. + distance_base))
                return;
            double lower = completed_tdr_sum_ms + pending_prefill_count * current_time_ms -
                           pending_arrival_time_sum;
            if (lower_bound_cached_arrival_count != arrived_count) {
                lower_bound_cached_arrival_count = arrived_count;
                std::vector<double> edge_work;
                edge_work.reserve(pending_prefill_count);
                for (const Request& r : requests) {
                    double work = 0;
                    if (r.phase == RequestPhase::prefill_pre_ready) {
                        work = 2. * task_setup_ms + task_times.duration(0, r.input_length) +
                               task_times.duration(2, r.input_length);
                    } else if (r.phase == RequestPhase::prefill_pre_running ||
                               r.phase == RequestPhase::prefill_upload_pending ||
                               r.phase == RequestPhase::prefill_proc_ready ||
                               r.phase == RequestPhase::prefill_proc_running ||
                               r.phase == RequestPhase::prefill_download_pending ||
                               r.phase == RequestPhase::prefill_post_ready) {
                        work = task_setup_ms + task_times.duration(2, r.input_length);
                    } else if (r.phase != RequestPhase::prefill_post_running) {
                        continue;
                    }
                    edge_work.push_back(work);
                }
                std::sort(edge_work.begin(), edge_work.end());
                const int jobs = static_cast<int>(edge_work.size());
                for (int i = 0; i < jobs; ++i)
                    lower += (jobs - i) * edge_work[i];
            }
            if (lower / arrived_count <= 1.5 * tdr_slo_ms * (1. + distance_base))
                return;
            runtime_fallback_enabled = true;
            base_decode_window = decode_window = decode_controller_max = 2000;
        }

        double edge_window_gain() const {
            const int next_window =
                std::min(decode_controller_max, decode_window + decode_controller_step);
            if (next_window <= decode_window)
                return 0;
            const double current_unit =
                (task_cost(3, decode_window) + task_cost(5, decode_window)) / decode_window;
            const double next_unit =
                (task_cost(3, next_window) + task_cost(5, next_window)) / next_window;
            if (!std::isfinite(current_unit) || current_unit <= 1e-12)
                return 0;
            return std::max(0., 1. - next_unit / current_unit);
        }

        void reset_controller_epoch() {
            epoch_opportunities = 0;
            epoch_blocked = 0;
            epoch_launches = 0;
            epoch_starved = 0;
            epoch_utilization_sum = 0;
        }

        void finish_controller_epoch() {
            const double count = std::max(1, epoch_opportunities);
            const double saturation = epoch_blocked / count;
            const double utilization =
                epoch_launches > 0 ? epoch_utilization_sum / epoch_launches : 0;
            const double starvation = epoch_starved / count;
            const double deficit = (1. - utilization) + 0.75 * starvation;
            const auto [tdr_guard, tpot_guard] = waiting_guard();
            const double normalized_throughput = online_normalized_throughput();
            const double headroom = w_tp * (1. - normalized_throughput);
            const double risk =
                std::hypot(std::max(0., tdr_guard - 1.), std::max(0., tpot_guard - 1.));
            bool rolled_back = false;
            if (probe_pending) {
                const bool no_supply_gain =
                    deficit > probe_deficit - 0.08 && saturation > probe_saturation - 0.20 &&
                    normalized_throughput < probe_normalized_throughput + 0.01;
                const bool waiting_worse =
                    tdr_guard > probe_tdr_guard + 0.15 || tpot_guard > probe_tpot_guard + 0.15;
                if (no_supply_gain || waiting_worse) {
                    decode_window =
                        std::max(base_decode_window, decode_window - decode_controller_step);
                    cooldown = 3;
                    rolled_back = true;
                }
                probe_pending = false;
            }
            if (decode_window > base_decode_window && risk >= 0.9 * distance_base) {
                decode_window = base_decode_window;
                cooldown = 3;
                probe_pending = false;
                rolled_back = true;
            }
            if (cooldown > 0)
                --cooldown;
            if (saturation <= 0.20)
                ++low_epochs;
            else
                low_epochs = 0;
            if (low_epochs >= 2 && decode_window > base_decode_window) {
                decode_window =
                    std::max(base_decode_window, decode_window - decode_controller_step);
                low_epochs = 0;
                probe_pending = false;
            }
            const double deficit_threshold = w_tp < 0.7 - 1e-12 ? 0.40 : .25;
            const bool score_gate = produced_token_count >= 128 &&
                                    normalized_throughput < 0.95 - 1e-12 &&
                                    headroom >= 0.025 - 1e-12;
            const bool risk_gate = risk < 0.9 * distance_base;
            const bool supply_gate =
                deficit >= deficit_threshold - 1e-12 || edge_window_gain() >= 0.04 - 1e-12;
            const bool good = !rolled_back && cooldown == 0 && completed_epochs > 0 &&
                              decode_window < decode_controller_max &&
                              unopened_decode_ready_count > 0 && saturation >= 0.75 - 1e-12 &&
                              score_gate && risk_gate && supply_gate;
            if (good)
                ++good_epochs;
            else
                good_epochs = 0;
            if (good_epochs >= 2) {
                probe_deficit = deficit;
                probe_saturation = saturation;
                probe_tdr_guard = tdr_guard;
                probe_tpot_guard = tpot_guard;
                probe_normalized_throughput = normalized_throughput;
                decode_window =
                    std::min(decode_controller_max, decode_window + decode_controller_step);
                probe_pending = true;
                good_epochs = 0;
            }
            ++completed_epochs;
            reset_controller_epoch();
        }

        void record_controller_opportunity(int group_size, bool starved) {
            if (decode_controller_max <= base_decode_window)
                return;
            ++epoch_opportunities;
            if (unopened_decode_ready_count > 0 && active_decode_requests >= decode_window)
                ++epoch_blocked;
            if (group_size > 0) {
                const int target = std::clamp(preferred_decode_proc_batch, 1, 64);
                ++epoch_launches;
                epoch_utilization_sum += std::min(1., static_cast<double>(group_size) / target);
            }
            if (starved)
                ++epoch_starved;
            const int horizon = std::max(32, 8 * num_clouds);
            if (epoch_opportunities >= horizon)
                finish_controller_epoch();
        }

        bool synchronized_decode_active() const {
            return !modeled_cloud_prefix_mode() && synchronized_decode_enabled &&
                   arrived_count - finished_count >= synchronization_population_threshold();
        }

        bool continuation_pair_wave_domain() const {
            return num_clouds >= 2 && w_tp >= .20 - 1e-12 && w_tp <= .30 + 1e-12 &&
                   w_c > w_tp + 1e-12 && distance_base <= 24. + 1e-12 &&
                   pending_prefill_count == 0 && has_active_decode_output();
        }

        int synchronization_population_threshold() const {
            return decode_stream_observed && has_active_decode_output()
                       ? mature_entry_population
                       : synchronization_population;
        }

        int synchronization_warm_target() const {
            return decode_stream_observed && has_active_decode_output() ? mature_entry_population
                                                                        : bootstrap_cohort;
        }

        double assignment_latency_pressure() const {
            if (w_c <= 1e-15)
                return 0.;
            if (w_tp <= 1e-15)
                return 1.;
            if (distance_base <= 1e-15)
                return 0.98;
            const double distance_scale = std::clamp(distance_base, .25, 64.);
            return std::clamp(w_c / (w_c + w_tp * distance_scale), 0., 1.);
        }

        int choose_rollout_cloud(int id) const {
            std::vector<int> cached_queued_jobs(num_clouds);
            std::vector<double> cached_queued_cloud_work(num_clouds);
            for (int cloud = 0; cloud < num_clouds; ++cloud)
                cached_queued_cloud_work[cloud] = std::max(
                    0., cloud_prefill_work_ms[cloud] - cloud_running_prefill_work_ms[cloud]);
            for (const Request& queued_request : requests) {
                if (queued_request.cloud_id >= 0 && queued_request.cloud_id < num_clouds &&
                    (queued_request.phase == RequestPhase::prefill_pre_running ||
                     queued_request.phase == RequestPhase::prefill_upload_pending ||
                     queued_request.phase == RequestPhase::prefill_proc_ready ||
                     queued_request.phase == RequestPhase::prefill_proc_running)) {
                    ++cached_queued_jobs[queued_request.cloud_id];
                }
            }
            for (int cloud = 0; cloud < num_clouds; ++cloud)
                cached_queued_jobs[cloud] -= cloud_running_prefill_work_ms[cloud] > 0;
            const Request& request = requests[id];
            const double edge_finish = current_time_ms + task_cost(0, request.input_length);
            const double upload_finish = std::max(link_available_time_ms[0], edge_finish) +
                                         transfer_cost_ms(request.input_length);
            const double weight_sum = std::max(1e-12, w_tp + w_c);
            const double throughput_price = w_tp / weight_sum;
            const double waiting_price = w_c / weight_sum / std::clamp(distance_base, .25, 64.);
            int best_cloud = 0;
            double best_objective = std::numeric_limits<double>::infinity();
            for (int cloud = 0; cloud < num_clouds; ++cloud) {
                double completion = std::max(upload_finish, cloud_predicted_busy_until_ms[cloud]) +
                                    cached_queued_cloud_work[cloud] +
                                    task_setup_ms * cached_queued_jobs[cloud] +
                                    task_cost(1, request.input_length);
                completion = std::max(link_available_time_ms[1], completion) +
                             transfer_cost_ms(request.input_length);
                completion = std::max(completion, edge_finish) + task_cost(2, request.input_length);
                const double normalized_completion =
                    (completion - request.arrival_time_ms) / std::max(1e-9, tdr_slo_ms);
                const double excess = std::max(0., normalized_completion - 1.);
                const double cloud_service = task_cost(1, request.input_length);
                const double decode_externality = cloud_service *
                                                  cloud_active_output_requests[cloud] /
                                                  std::max(1e-9, tpot_slo_ms);
                const double makespan = (completion - current_time_ms) / std::max(1e-9, tdr_slo_ms);
                const double objective =
                    waiting_price * (normalized_completion + excess * excess + decode_externality) +
                    throughput_price * (makespan + cloud_service * cloud_request_load[cloud] /
                                                       std::max(1e-9, tdr_slo_ms)) +
                    1e-12 * cloud;
                if (objective < best_objective - 1e-12) {
                    best_objective = objective;
                    best_cloud = cloud;
                }
            }
            return best_cloud;
        }

        int choose_cloud(int id) {
            if (strong_waiting_fallback_mode()) {
                int best_cloud = 0;
                for (int c = 1; c < num_clouds; ++c)
                    if (cloud_request_load[c] < cloud_request_load[best_cloud] ||
                        (cloud_request_load[c] == cloud_request_load[best_cloud] &&
                         (cloud_prefill_work_ms[c] < cloud_prefill_work_ms[best_cloud] - 1e-12 ||
                          (std::abs(cloud_prefill_work_ms[c] - cloud_prefill_work_ms[best_cloud]) <=
                               1e-12 &&
                           static_cast<int>(cloud_busy[c]) <
                               static_cast<int>(cloud_busy[best_cloud])))))
                        best_cloud = c;
                (void)id;
                return best_cloud;
            }
            if (latency_dominant_objective_band()) {
                int best_cloud = 0;
                for (int c = 1; c < num_clouds; ++c)
                    if (cloud_request_load[c] < cloud_request_load[best_cloud] ||
                        (cloud_request_load[c] == cloud_request_load[best_cloud] &&
                         (cloud_prefill_work_ms[c] < cloud_prefill_work_ms[best_cloud] - 1e-12 ||
                          (std::abs(cloud_prefill_work_ms[c] - cloud_prefill_work_ms[best_cloud]) <=
                               1e-12 &&
                           static_cast<int>(cloud_busy[c]) <
                               static_cast<int>(cloud_busy[best_cloud])))))
                        best_cloud = c;
                return best_cloud;
            }
            int cloud_limit =
                modeled_cloud_prefix_mode() ? choose_modeled_cloud_count() : num_clouds;
            if (synchronized_decode_active() && !modeled_cloud_prefix_mode()) {
                const int potential =
                    std::min(2000, std::max(bootstrap_cohort, arrived_count - finished_count));
                const int target = std::max(1, cohort_target(potential));
                cloud_limit = std::clamp(best_cloud_count_for_cohort[target], 1, num_clouds);
            }
            if (modeled_cloud_prefix_mode())
                return choose_modeled_cloud(cloud_limit);
            if (enable_protected_startup_cloud_prior && protected_startup_chunk_and_prior_mode()) {
                const int batch = std::max(1, std::min(preferred_decode_proc_batch, 64));
                const double unit = task_cost(4, batch) / batch;
                const double observed_prior =
                    (16 + observed_first_token_count - observed_nonterminal_first_tokens) /
                    (4. + observed_first_token_count);
                const double prior = 4. + protected_startup_cloud_prior_strength_milli * .001 *
                                              (observed_prior - 4.);
                int best = -1;
                double low = 1e100;
                for (int d = 0; d < cloud_limit; ++d) {
                    const int c = (next_cloud_round_robin + d) % cloud_limit;
                    const double value =
                        cloud_prefill_work_ms[c] + prior * cloud_request_load[c] * unit;
                    if (value < low - 1e-12) {
                        low = value;
                        best = c;
                    }
                }
                next_cloud_round_robin = (best + 1) % cloud_limit;
                return best;
            }
            const bool balance_by_workload = assignment_latency_pressure() <= 0.12 + 1e-12;
            int best = -1;
            for (int d = 0; d < cloud_limit; ++d) {
                const int c = (next_cloud_round_robin + d) % cloud_limit;
                if (best < 0) {
                    best = c;
                    continue;
                }
                if (balance_by_workload && w_tp >= 0.8 - 1e-12) {
                    const double value =
                        cloud_prefill_work_ms[c] + .5 * cloud_request_load[c] * task_cost(4, 1);
                    const double old = cloud_prefill_work_ms[best] +
                                       .5 * cloud_request_load[best] * task_cost(4, 1);
                    if (value < old - 1e-12)
                        best = c;
                } else if (balance_by_workload) {
                    if (cloud_request_load[c] < cloud_request_load[best] ||
                        (cloud_request_load[c] == cloud_request_load[best] &&
                         (cloud_prefill_work_ms[c] < cloud_prefill_work_ms[best] - 1e-12 ||
                          (std::abs(cloud_prefill_work_ms[c] - cloud_prefill_work_ms[best]) <=
                               1e-12 &&
                           (cloud_decode_load[c] < cloud_decode_load[best] ||
                            (cloud_decode_load[c] == cloud_decode_load[best] &&
                             static_cast<int>(cloud_busy[c]) <
                                 static_cast<int>(cloud_busy[best]))))))) {
                        best = c;
                    }
                } else {
                    const double value = cloud_request_load[c] +
                                         (0.4 + 0.8 * w_tp) * cloud_decode_load[c] +
                                         (cloud_busy[c] ? 0.35 : 0.);
                    const double best_value = cloud_request_load[best] +
                                              (0.4 + 0.8 * w_tp) * cloud_decode_load[best] +
                                              (cloud_busy[best] ? 0.35 : 0.);
                    if (value < best_value - 1e-12)
                        best = c;
                }
            }
            (void)id;
            next_cloud_round_robin = (best + 1) % cloud_limit;
            return best;
        }

        bool has_internal_future() const {
            if (edge_busy)
                return true;
            for (bool busy : cloud_busy) {
                if (busy)
                    return true;
            }
            for (const Request& r : requests) {
                if (r.phase == RequestPhase::prefill_upload_pending ||
                    r.phase == RequestPhase::prefill_download_pending ||
                    r.phase == RequestPhase::decode_upload_pending ||
                    r.phase == RequestPhase::decode_download_pending) {
                    return true;
                }
            }
            return false;
        }

        static void append_request_group(std::string& task, const std::vector<int>& ids) {
            task += " " + std::to_string(ids.size());
            for (int id : ids)
                task += " " + std::to_string(id);
        }

        int cohort_target(int available) const {
            if (available <= 1)
                return std::max(0, available);
            const int capped = std::min(2000, available);
            int target = best_rate_cohort[capped];
            const double sum = w_tp + w_c;
            const double share = sum > 1e-15 ? w_tp / sum : 0.;
            if (share >= 0.74 - 1e-12 && share <= 0.85 + 1e-12 && distance_base >= 64.) {
                target = std::max(1,
                                  (target * cohort_scale_numerator + cohort_scale_denominator - 1) /
                                      cohort_scale_denominator);
            }
            return std::min(capped, target);
        }

        bool throughput_synchronized_q2_domain() const {
            return synchronized_decode_enabled && objective_band_code() == 2 && w_tp > w_c;
        }

        void append_formed_cohort_members(std::vector<int>& group,
                                          const std::vector<int>& fresh,
                                          int requested_count) const {
            const int take = std::clamp(requested_count, 0, static_cast<int>(fresh.size()));
            if (!throughput_synchronized_q2_domain()) {
                group.insert(group.end(), fresh.begin(), fresh.begin() + take);
                return;
            }
            std::vector<int> members_per_cloud(num_clouds, 0);
            for (int id : group) {
                const int cloud = requests[id].cloud_id;
                if (cloud >= 0 && cloud < num_clouds)
                    ++members_per_cloud[cloud];
            }
            std::vector<int> candidate_indices;
            candidate_indices.reserve(take);
            for (int index = 0; index < static_cast<int>(fresh.size()); ++index)
                candidate_indices.push_back(index);
            std::vector<int> selection_order;
            selection_order.reserve(take);
            std::vector<unsigned char> selected(candidate_indices.size(), 0);
            for (int selected_count = 0;
                 selected_count < static_cast<int>(candidate_indices.size());
                 ++selected_count) {
                int best_position = -1;
                for (int position = 0; position < static_cast<int>(candidate_indices.size());
                     ++position) {
                    if (selected[position])
                        continue;
                    const int index = candidate_indices[position];
                    const int cloud = requests[fresh[index]].cloud_id;
                    if (cloud < 0 || cloud >= num_clouds)
                        continue;
                    if (best_position < 0) {
                        best_position = position;
                        continue;
                    }
                    const int best_index = candidate_indices[best_position];
                    const int best_cloud = requests[fresh[best_index]].cloud_id;
                    if (members_per_cloud[cloud] < members_per_cloud[best_cloud] ||
                        (members_per_cloud[cloud] == members_per_cloud[best_cloud] &&
                         index < best_index)) {
                        best_position = position;
                    }
                }
                if (best_position < 0)
                    break;
                selected[best_position] = 1;
                const int index = candidate_indices[best_position];
                ++members_per_cloud[requests[fresh[index]].cloud_id];
                selection_order.push_back(index);
                if (static_cast<int>(selection_order.size()) == take)
                    break;
            }
            if (static_cast<int>(selection_order.size()) < take) {
                for (int index : candidate_indices) {
                    if (std::find(selection_order.begin(), selection_order.end(), index) ==
                        selection_order.end())
                        selection_order.push_back(index);
                    if (static_cast<int>(selection_order.size()) == take)
                        break;
                }
            }
            std::vector<int> fifo_order = selection_order;
            std::sort(fifo_order.begin(), fifo_order.end());
            for (int index : fifo_order)
                group.push_back(fresh[index]);
        }

        std::vector<int> synchronized_decode_pre_group() {
            std::vector<int> open =
                collect_ready_requests(open_decode_pre_queue, RequestPhase::decode_pre_ready);
            std::sort(open.begin(), open.end(), [&](int x, int y) {
                if (requests[x].last_token_time_ms != requests[y].last_token_time_ms) {
                    return requests[x].last_token_time_ms < requests[y].last_token_time_ms;
                }
                if (requests[x].tokens_produced != requests[y].tokens_produced)
                    return requests[x].tokens_produced < requests[y].tokens_produced;
                return x < y;
            });
            std::vector<int> fresh =
                collect_ready_requests(fresh_decode_pre_queue, RequestPhase::decode_pre_ready);
            std::sort(fresh.begin(), fresh.end(), [&](int x, int y) {
                if (requests[x].ready_since_ms != requests[y].ready_since_ms) {
                    return requests[x].ready_since_ms < requests[y].ready_since_ms;
                }
                return x < y;
            });
            std::vector<int> ids;
            if (active_decode_requests > 0) {
                if (static_cast<int>(open.size()) < active_decode_requests &&
                    has_internal_future()) {
                    return ids;
                }
                ids = std::move(open);
                const int available_population =
                    std::min(2000, active_decode_requests + unopened_decode_ready_count);
                const int target =
                    std::max(active_decode_requests, cohort_target(available_population));
                const int slots = std::min({std::max(0, target - active_decode_requests),
                                            std::max(0, decode_window - active_decode_requests),
                                            static_cast<int>(fresh.size())});
                append_formed_cohort_members(ids, fresh, slots);
            } else {
                const int unfinished = std::max(1, arrived_count - finished_count);
                const int target = std::max(1, cohort_target(std::min(2000, unfinished)));
                const int pending_prefill = std::max(0, unfinished - unopened_decode_ready_count);
                const int warm_target =
                    std::min(target, std::max(2, synchronization_warm_target()));
                if (produced_token_count == 0 && pending_prefill > 0 &&
                    static_cast<int>(fresh.size()) < warm_target && has_internal_future()) {
                    return ids;
                }
                const int take = std::min({target, decode_window, static_cast<int>(fresh.size())});
                append_formed_cohort_members(ids, fresh, take);
            }
            if (ids.empty() && !has_internal_future()) {
                const int id =
                    first_ready_id(fresh_decode_pre_queue, RequestPhase::decode_pre_ready);
                if (id >= 0)
                    ids.push_back(id);
            }
            return ids;
        }

        std::vector<int> build_decode_pre_group() {
            if (synchronized_decode_active() && !protected_startup_prefill_guard()) {
                auto group = synchronized_decode_pre_group();
                if ((should_hold_synchronized_decode_pre(static_cast<int>(group.size())) &&
                     !(tiny_wait_weight_mode() && !has_internal_future())) ||
                    should_wait_for_modeled_cloud_prefix())
                    return {};
                return group;
            }
            if (unopened_decode_ready_count > 0 &&
                active_decode_requests + std::max(1, num_clouds) >= decode_window) {
                decode_admission_limited = true;
            }
            std::vector<int> open =
                collect_ready_requests(open_decode_pre_queue, RequestPhase::decode_pre_ready);
            std::sort(open.begin(), open.end(), [&](int x, int y) {
                if (requests[x].last_token_time_ms != requests[y].last_token_time_ms) {
                    return requests[x].last_token_time_ms < requests[y].last_token_time_ms;
                }
                if (requests[x].tokens_produced != requests[y].tokens_produced)
                    return requests[x].tokens_produced < requests[y].tokens_produced;
                return x < y;
            });
            std::vector<int> ids = std::move(open);
            const int canonical_slots = std::max(0, decode_window - active_decode_requests);
            const bool drain_prefill_before_fresh_decode =
                short_output_prefill_drain_mode() || protected_startup_prefill_guard() ||
                (pure_waiting_objective() && arrived_count > observed_first_token_count);
            if (!drain_prefill_before_fresh_decode) {
                std::vector<int> fresh =
                    collect_ready_requests(fresh_decode_pre_queue, RequestPhase::decode_pre_ready);
                std::sort(fresh.begin(), fresh.end(), [&](int x, int y) {
                    if (requests[x].ready_since_ms != requests[y].ready_since_ms) {
                        return requests[x].ready_since_ms < requests[y].ready_since_ms;
                    }
                    return x < y;
                });
                const int extra_fresh =
                    std::max(0, static_cast<int>(fresh.size()) - canonical_slots);
                const int slots =
                    canonical_slots + static_cast<int>(std::lround(
                                          decode_pre_fresh_expansion_strength() * extra_fresh));
                const int take = std::min(slots, static_cast<int>(fresh.size()));
                ids.insert(ids.end(), fresh.begin(), fresh.begin() + take);
            }
            if (tiny_wait_weight_mode())
                std::sort(ids.begin(), ids.end(), [&](int x, int y) {
                    return requests[x].last_token_time_ms != requests[y].last_token_time_ms
                               ? requests[x].last_token_time_ms < requests[y].last_token_time_ms
                               : x < y;
                });
            if ((should_hold_decode_pre(static_cast<int>(ids.size())) &&
                 !(tiny_wait_weight_mode() && !has_internal_future())) ||
                should_wait_for_modeled_cloud_prefix())
                return {};
            if (ids.empty() && !has_internal_future()) {
                const int id =
                    first_ready_id(fresh_decode_pre_queue, RequestPhase::decode_pre_ready);
                if (id >= 0)
                    ids.push_back(id);
            }
            if (!ids.empty())
                ids.resize(tiny_wait_weight_mode() ? aged_batch_size(0, ids)
                                                   : dynamic_group_size(0, ids));
            return ids;
        }

        EdgeTaskChoice make_decode_post_choice() {
            EdgeTaskChoice choice;
            choice.task_kind = EdgeTaskKind::decode_post;
            choice.tie_breaker = 0;
            choice.request_ids =
                collect_ready_requests(decode_post_ready_queue, RequestPhase::decode_post_ready);
            if (choice.request_ids.empty())
                return choice;
            if (strong_waiting_fallback_mode()) {
                std::stable_partition(choice.request_ids.begin(),
                                      choice.request_ids.end(),
                                      [&](int id) { return requests[id].tokens_produced > 0; });
                int o = static_cast<int>(
                        std::count_if(choice.request_ids.begin(),
                                      choice.request_ids.end(),
                                      [&](int id) { return requests[id].tokens_produced > 0; })),
                    h = 0;
                for (const Request& r : requests)
                    h += r.tokens_produced > 0 && r.phase != RequestPhase::finished;
                int w = runtime_fallback_enabled ? 2000 : strong_waiting_decode_window;
                choice.request_ids.resize(
                    o +
                    std::min(static_cast<int>(choice.request_ids.size()) - o, std::max(0, w - h)));
                if (choice.request_ids.empty())
                    return EdgeTaskChoice{};
                choice.request_ids.resize(
                    group_size(2, static_cast<int>(choice.request_ids.size())));
            } else {
                if (should_hold_for_next_transfer(
                        2,
                        static_cast<int>(choice.request_ids.size()),
                        active_decode_requests + unopened_decode_ready_count,
                        next_decode_downstream_completion()) ||
                    modeled_cloud_prefix_mode() &&
                        should_hold_decode_post_for_wave(choice.request_ids))
                    return EdgeTaskChoice{};
                if (!synchronized_decode_active() && w_tp >= 0.70 - 1e-12 && w_tp < 0.80 - 1e-12 &&
                    distance_base < 64. &&
                    static_cast<int>(choice.request_ids.size()) <
                        std::min(4, active_decode_requests) &&
                    has_internal_future())
                    return EdgeTaskChoice{};
                bool whole_wave = synchronized_decode_active();
                if (whole_wave || continuation_pair_wave_domain()) {
                    int wave_id = -1;
                    for (int id : choice.request_ids) {
                        const int w = requests[id].decode_wave_id;
                        if (w >= 0 && (wave_id < 0 || w < wave_id))
                            wave_id = w;
                    }
                    if (wave_id >= 0) {
                        whole_wave = true;
                        std::vector<int> same;
                        same.reserve(choice.request_ids.size());
                        for (int id : choice.request_ids)
                            if (requests[id].decode_wave_id == wave_id)
                                same.push_back(id);
                        if (wave_id < static_cast<int>(decode_waves.size()) &&
                            decode_waves[wave_id].ready_members <
                                decode_waves[wave_id].remaining_members &&
                            has_internal_future()) {
                            return choice;
                        }
                        choice.request_ids = std::move(same);
                    }
                }
                if (tiny_wait_weight_mode())
                    std::sort(
                        choice.request_ids.begin(), choice.request_ids.end(), [&](int x, int y) {
                            return requests[x].last_token_time_ms != requests[y].last_token_time_ms
                                       ? requests[x].last_token_time_ms <
                                             requests[y].last_token_time_ms
                                       : x < y;
                        });
                else
                    std::sort(
                        choice.request_ids.begin(), choice.request_ids.end(), [&](int x, int y) {
                            const bool left_started = requests[x].tokens_produced > 0;
                            const bool right_started = requests[y].tokens_produced > 0;
                            if (left_started != right_started)
                                return left_started > right_started;
                            if (left_started &&
                                requests[x].last_token_time_ms != requests[y].last_token_time_ms) {
                                return requests[x].last_token_time_ms <
                                       requests[y].last_token_time_ms;
                            }
                            if (requests[x].tokens_produced != requests[y].tokens_produced)
                                return requests[x].tokens_produced < requests[y].tokens_produced;
                            return x < y;
                        });
                if (!whole_wave) {
                    choice.request_ids.resize(tiny_wait_weight_mode()
                                                  ? aged_batch_size(2, choice.request_ids)
                                                  : dynamic_group_size(2, choice.request_ids));
                    if (!tiny_wait_weight_mode() &&
                        should_hold_for_known_transfer(2,
                                                       static_cast<int>(choice.request_ids.size()),
                                                       next_predicted_decode_transfer(1))) {
                        return EdgeTaskChoice{};
                    }
                }
            }
            const double finish =
                current_time_ms + task_cost(5, static_cast<int>(choice.request_ids.size()));
            bool has_open = false;
            double key = 1e100;
            for (int id : choice.request_ids) {
                if (requests[id].tokens_produced == 0)
                    continue;
                has_open = true;
                key = std::min(
                    key, (requests[id].last_token_time_ms + tpot_slo_ms - finish) / tpot_slo_ms);
            }
            if (has_open) {
                key -= 0.35 + 0.15 * w_tp;
            } else {
                key = 0.30 + 0.20 * w_c - 0.30 * w_tp;
            }
            key -= age_bonus(choice.request_ids, tpot_slo_ms);
            key -= 0.025 * std::log2(static_cast<double>(choice.request_ids.size()) + 1.);
            choice.priority_key = key;
            choice.is_valid = true;
            return choice;
        }

        EdgeTaskChoice make_prefill_post_choice() {
            EdgeTaskChoice choice;
            choice.task_kind = EdgeTaskKind::prefill_post;
            choice.tie_breaker = 1;
            const std::vector<int> ids =
                collect_ready_requests(prefill_post_ready_queue, RequestPhase::prefill_post_ready);
            if (ids.empty())
                return choice;
            double best_rank = 1e100, best_tie_time = 1e100, chosen_key = 1e100;
            bool use_ready_order = strong_waiting_fallback_mode() &&
                                   (runtime_fallback_enabled ||
                                    minimum_prefill_path_ms > tdr_slo_ms * (1. + distance_base) ||
                                    (w_c >= .5 - 1e-12 && distance_base <= .25 + 1e-12));
            for (int id : ids) {
                double remaining_cost = task_cost(2, requests[id].input_length),
                       item_key = prefill_priority_key(id, remaining_cost, .35 + .15 * w_c),
                       rank = strong_waiting_fallback_mode()
                                  ? (use_ready_order ? requests[id].ready_since_ms : remaining_cost)
                              : tiny_wait_weight_mode() ? requests[id].arrival_time_ms
                              : objective_band_code() > 1
                                  ? item_key
                                  : (runtime_fallback_active()
                                         ? requests[id].ready_since_ms
                                         : ((startup_srpt_active() ||
                                             (protected_startup_chunk_and_prior_mode() &&
                                              pending_prefill_count >= std::max(8, 2 * num_clouds)))
                                                ? remaining_cost
                                                : item_key)),
                       tie_time = strong_waiting_fallback_mode() && !use_ready_order
                                      ? requests[id].arrival_time_ms
                                      : 0.;
                if (rank < best_rank - 1e-12 ||
                    (std::abs(rank - best_rank) <= 1e-12 &&
                     (tie_time < best_tie_time - 1e-12 ||
                      (std::abs(tie_time - best_tie_time) <= 1e-12 &&
                       (choice.request_id < 0 || id < choice.request_id))))) {
                    best_rank = rank;
                    best_tie_time = tie_time;
                    chosen_key = item_key;
                    choice.request_id = id;
                }
            }
            choice.priority_key = chosen_key;
            choice.is_valid = true;
            return choice;
        }

        EdgeTaskChoice make_decode_pre_choice() {
            EdgeTaskChoice choice;
            choice.task_kind = EdgeTaskKind::decode_pre;
            choice.tie_breaker = 2;
            choice.request_ids = build_decode_pre_group();
            if (choice.request_ids.empty())
                return choice;
            std::vector<int> by_cloud(num_clouds);
            for (int id : choice.request_ids)
                ++by_cloud[requests[id].cloud_id];
            const int batch_size = static_cast<int>(choice.request_ids.size());
            const double e_cost = task_cost(3, batch_size);
            const double post_cost = task_cost(5, batch_size);
            bool has_open = false;
            double key = 1e100;
            for (int id : choice.request_ids) {
                if (requests[id].tokens_produced == 0)
                    continue;
                has_open = true;
                const int cloud_batch_size = by_cloud[requests[id].cloud_id];
                const double remaining = e_cost + transfer_cost_ms(cloud_batch_size) +
                                         task_cost(4, cloud_batch_size) +
                                         transfer_cost_ms(cloud_batch_size) + post_cost;
                const double item_key = (requests[id].last_token_time_ms + tpot_slo_ms -
                                         (current_time_ms + remaining)) /
                                        tpot_slo_ms;
                key = std::min(key, item_key);
            }
            if (has_open) {
                key -= 0.15 + 0.10 * w_tp;
            } else {
                key = 0.55 + .25 * w_c - 0.45 * w_tp;
            }
            key -= age_bonus(choice.request_ids, has_open ? tpot_slo_ms : tdr_slo_ms);
            key -= 0.02 * std::log2(static_cast<double>(batch_size) + 1.);
            choice.priority_key = key;
            choice.is_valid = true;
            return choice;
        }

        EdgeTaskChoice make_prefill_pre_choice() {
            EdgeTaskChoice choice;
            choice.task_kind = EdgeTaskKind::prefill_pre;
            choice.tie_breaker = 3;
            const std::vector<int> ids =
                collect_ready_requests(prefill_pre_ready_queue, RequestPhase::prefill_pre_ready);
            if (ids.empty())
                return choice;
            double best_rank = 1e100;
            double chosen_key = 1e100;
            const bool legacy_pressure = startup_srpt_active() ||
                                         (protected_startup_chunk_and_prior_mode() &&
                                          pending_prefill_count >= std::max(8, 2 * num_clouds)) ||
                                         (!decode_stream_observed && !has_active_decode_output() &&
                                          has_expensive_prefill_upload());
            if (strong_waiting_fallback_mode()) {
                double best_tie_time = 1e100;
                bool f = runtime_fallback_enabled ||
                         minimum_prefill_path_ms > tdr_slo_ms * (1. + distance_base) ||
                         (w_c >= .5 - 1e-12 && distance_base <= .25 + 1e-12);
                for (int id : ids) {
                    const Request& r = requests[id];
                    double m = task_cost(0, r.input_length) + 2 * transfer_cost_ms(r.input_length) +
                               task_cost(1, r.input_length) + task_cost(2, r.input_length),
                           x = f ? r.ready_since_ms : m, t = f ? 0. : r.arrival_time_ms;
                    if (x < best_rank - 1e-12 ||
                        (std::abs(x - best_rank) <= 1e-12 &&
                         (t < best_tie_time - 1e-12 ||
                          (std::abs(t - best_tie_time) <= 1e-12 &&
                           (choice.request_id < 0 || id < choice.request_id)))))
                        best_rank = x, best_tie_time = t,
                        chosen_key = prefill_priority_key(id, m, 0), choice.request_id = id;
                }
                choice.priority_key = chosen_key;
                choice.is_valid = true;
                return choice;
            }
            if (modeled_cloud_prefix_mode()) {
                const int c = choose_modeled_cloud(choose_modeled_cloud_count());
                auto v = ids;
                std::sort(v.begin(), v.end(), [&](int x, int y) {
                    return requests[x].arrival_time_ms != requests[y].arrival_time_ms
                               ? requests[x].arrival_time_ms < requests[y].arrival_time_ms
                               : x < y;
                });
                int z = 0;
                for (int id : v) {
                    if (z >= 12)
                        break;
                    const auto& r = requests[id];
                    const double remaining =
                        task_cost(0, r.input_length) + 2. * transfer_cost_ms(r.input_length) +
                        task_cost(1, r.input_length) + task_cost(2, r.input_length);
                    const double key = prefill_priority_key(id, remaining, 0);
                    double rank = (predicted_prefill_completion_time(id, c) - r.arrival_time_ms) /
                                      std::max(1e-9, tdr_slo_ms) +
                                  .02 * z + 1e-9 * c;
                    if (rank < best_rank - 1e-12) {
                        best_rank = rank;
                        chosen_key = key;
                        choice.request_id = id;
                        choice.cloud_id = c;
                    }
                    ++z;
                }
                choice.priority_key = chosen_key;
                choice.is_valid = choice.request_id >= 0;
                return choice;
            }
            for (int id : ids) {
                const Request& r = requests[id];
                const double remaining =
                    task_cost(0, r.input_length) + 2. * transfer_cost_ms(r.input_length) +
                    task_cost(1, r.input_length) + task_cost(2, r.input_length);
                const double key = prefill_priority_key(id, remaining, 0);
                const double restraint =
                    legacy_pressure ? 1. : prefill_uplink_restraint_strength(id);
                const double srpt_rank = remaining / std::max(1e-9, tdr_slo_ms);
                const double rank =
                    w_tp < .5 - 1e-12 ? srpt_rank
                    : latency_dominant_objective_band()
                        ? remaining
                        : ((objective_band_code() || w_tp == w_c && throughput_upper_bound <= .01 &&
                                                         produced_token_count == 0)
                               ? key
                           : objective_band_code()
                               ? key
                               : (runtime_fallback_active()
                                      ? r.ready_since_ms
                                      : (1. - restraint) * key + restraint * srpt_rank));
                if (rank < best_rank - 1e-12 ||
                    (std::abs(rank - best_rank) <= 1e-12 &&
                     (choice.request_id < 0 || id < choice.request_id))) {
                    best_rank = rank;
                    chosen_key = key;
                    choice.request_id = id;
                }
            }
            choice.priority_key = chosen_key;
            choice.is_valid = true;
            return choice;
        }

        bool schedule_edge_task(std::string& task) {
            std::array<EdgeTaskChoice, 4> choices = {make_decode_post_choice(),
                                                     make_prefill_post_choice(),
                                                     make_decode_pre_choice(),
                                                     make_prefill_pre_choice()};
            EdgeTaskChoice* best = nullptr;
            const bool hot_decode_ready =
                (choices[0].is_valid && group_contains_started_decode(choices[0].request_ids)) ||
                (choices[2].is_valid && group_contains_started_decode(choices[2].request_ids));
            const bool hold_prefill_up =
                choices[3].is_valid && should_hold_prefill_pre(choices[3].request_id);
            EdgeTaskChoice* urgent_decode_choice = nullptr;
            if (runtime_fallback_active() || latency_dominant_objective_band()) {
                const double cycle = task_cost(3, 1) + transfer_cost_ms(1) + task_cost(4, 1) +
                                     transfer_cost_ms(1) + task_cost(5, 1);
                const double limit = std::max(tpot_slo_ms, cycle) *
                                     (latency_dominant_objective_band() ? 1. : 1. + 2. * w_tp);
                for (int index : {0, 2}) {
                    if (!choices[index].is_valid)
                        continue;
                    const double fraction =
                        latency_dominant_objective_band() ? .3 : (index == 0 ? 1. : .75);
                    double prefill_delay =
                        latency_dominant_objective_band()
                            ? (choices[1].is_valid
                                   ? task_cost(2, requests[choices[1].request_id].input_length)
                               : choices[3].is_valid
                                   ? task_cost(0, requests[choices[3].request_id].input_length)
                                   : 0.)
                            : 0.;
                    if (std::any_of(choices[index].request_ids.begin(),
                                    choices[index].request_ids.end(),
                                    [&](int id) {
                                        return requests[id].tokens_produced > 0 &&
                                               current_time_ms + prefill_delay -
                                                       requests[id].last_token_time_ms >=
                                                   fraction * limit;
                                    })) {
                        urgent_decode_choice = &choices[index];
                        break;
                    }
                }
            }
            const auto waiting_guards = waiting_guard();
            const double waiting_risk = std::hypot(std::max(0., waiting_guards.first - 1.),
                                                   std::max(0., waiting_guards.second - 1.));
            double population_per_cloud =
                double(std::max(0, arrived_count - finished_count)) / std::max(1, num_clouds);
            double admission_reduction = std::clamp((population_per_cloud - 8) / 8, 0., 1.) *
                                         std::clamp((8192 - distance_base) / 7168, 0., 1.) *
                                         std::clamp((.98 - w_tp) / .03, 0., 1.);
            int adaptive_admission_cap =
                static_cast<int>(std::lround((8 - 5 * admission_reduction) * num_clouds));
            const int startup_admission_cap =
                std::min({startup_decode_admission_cap,
                          adaptive_admission_cap,
                          unopened_decode_ready_count + std::max(0, pending_prefill_count)});
            const bool hold_for_startup_cohort =
                startup_admission_cap >= 2 && produced_token_count == 0 && !hot_decode_ready &&
                choices[2].is_valid && pending_prefill_count > 0 &&
                unopened_decode_ready_count < startup_admission_cap &&
                (choices[1].is_valid || choices[3].is_valid || has_internal_future()) &&
                ((distance_base <= 1e-15 && waiting_risk <= 1e-12) ||
                 (distance_base > 1e-15 && waiting_risk < .25 * distance_base));
            const bool startup_decode_release_gain_domain =
                (w_tp >= .20 && w_tp < .30) || w_tp >= .88;
            const bool non_q2_startup_phase_opportunity =
                startup_decode_release_gain_domain && !throughput_synchronized_q2_domain() &&
                produced_token_count == 0 && choices[2].is_valid && pending_prefill_count > 0;
            if (non_q2_startup_phase_opportunity) {
                best = &choices[2];
            } else if (modeled_cloud_prefix_mode()) {
                for (auto& x : choices)
                    if (x.is_valid && (best == nullptr ||
                                       edge_choice_score(x) > edge_choice_score(*best) + 1e-12))
                        best = &x;
            } else if (strong_waiting_fallback_mode()) {
                auto keep_started_decode_only = [&](int j) {
                    std::vector<int> u =
                        j ? collect_ready_requests(open_decode_pre_queue,
                                                   RequestPhase::decode_pre_ready)
                          : collect_ready_requests(decode_post_ready_queue,
                                                   RequestPhase::decode_post_ready);
                    u.erase(
                        std::remove_if(u.begin(),
                                       u.end(),
                                       [&](int id) { return requests[id].tokens_produced == 0; }),
                        u.end());
                    if (!u.empty())
                        u.resize(group_size(j ? 0 : 2, static_cast<int>(u.size())));
                    choices[j ? 2 : 0].request_ids = std::move(u);
                    choices[j ? 2 : 0].is_valid = !choices[j ? 2 : 0].request_ids.empty();
                };
                auto started_decode_is_urgent = [&](int j, double f, double x, double m) {
                    int b = -1;
                    double r = std::numeric_limits<double>::infinity();
                    RequestPhase s =
                        j ? RequestPhase::decode_pre_ready : RequestPhase::decode_post_ready;
                    for (int id = 0; id < static_cast<int>(requests.size()); ++id)
                        if (requests[id].phase == s && requests[id].tokens_produced > 0 &&
                            (requests[id].ready_since_ms < r - 1e-12 ||
                             (std::abs(requests[id].ready_since_ms - r) <= 1e-12 &&
                              (b < 0 || id < b))))
                            r = requests[id].ready_since_ms, b = id;
                    double c = std::max(tpot_slo_ms,
                                        task_cost(3, 1) + transfer_cost_ms(1) + task_cost(4, 1) +
                                            transfer_cost_ms(1) + task_cost(5, 1));
                    return b >= 0 &&
                           current_time_ms + x - requests[b].last_token_time_ms >= f * m * c;
                };
                bool prefill_path_exceeds_budget =
                         minimum_prefill_path_ms > tdr_slo_ms * (1. + distance_base),
                     tight_distance_regime = w_c >= .5 - 1e-12 && distance_base <= .25 + 1e-12,
                     high_wait_weight = w_c >= .8 - 1e-12;
                double x = choices[1].is_valid
                               ? task_cost(2, requests[choices[1].request_id].input_length)
                           : choices[3].is_valid
                               ? task_cost(0, requests[choices[3].request_id].input_length)
                               : 0.;
                if (prefill_path_exceeds_budget || runtime_fallback_enabled) {
                    double m = 1 + 2 * w_tp;
                    if (!runtime_fallback_enabled && started_decode_is_urgent(0, 1., 0, m))
                        best = &choices[0];
                    else if (choices[1].is_valid)
                        best = &choices[1];
                    else if (!runtime_fallback_enabled && started_decode_is_urgent(1, .75, 0, m))
                        best = &choices[2];
                    else if (choices[3].is_valid)
                        best = &choices[3];
                    else if (choices[0].is_valid)
                        best = &choices[0];
                    else if (choices[2].is_valid)
                        best = &choices[2];
                } else {
                    double m = high_wait_weight ? 1. : 1 + .75 * w_tp,
                           a = tight_distance_regime ? .45
                               : high_wait_weight    ? .3
                                                     : .75,
                           b = tight_distance_regime ? .45
                               : high_wait_weight    ? .3
                                                     : .55;
                    if (started_decode_is_urgent(0, a, x, m)) {
                        if (!tight_distance_regime)
                            keep_started_decode_only(0);
                        best = &choices[0];
                    } else if (started_decode_is_urgent(1, b, x, m)) {
                        if (!tight_distance_regime)
                            keep_started_decode_only(1);
                        best = &choices[2];
                    } else if (choices[1].is_valid)
                        best = &choices[1];
                    else if (choices[3].is_valid)
                        best = &choices[3];
                    else if (choices[0].is_valid)
                        best = &choices[0];
                    else if (choices[2].is_valid)
                        best = &choices[2];
                }
            } else if (hold_for_startup_cohort) {
                if (choices[1].is_valid || choices[3].is_valid) {
                    best = choices[1].is_valid ? &choices[1] : &choices[3];
                } else if (has_internal_future()) {
                    prefill_post_skip_count = 0;
                    prefill_pre_skip_count = 0;
                    return false;
                }
            } else if (protected_startup_prefill_guard() && !hot_decode_ready &&
                       (choices[1].is_valid || choices[3].is_valid)) {
                best = choices[1].is_valid ? &choices[1] : &choices[3];
            } else if (urgent_decode_choice != nullptr) {
                best = urgent_decode_choice;
            } else if (latency_dominant_objective_band() &&
                       (choices[1].is_valid || choices[3].is_valid)) {
                best = choices[1].is_valid ? &choices[1] : &choices[3];
            } else if (runtime_fallback_active() && (choices[1].is_valid || choices[3].is_valid)) {
                best = choices[1].is_valid ? &choices[1] : &choices[3];
            } else if (pure_waiting_objective() && !hot_decode_ready &&
                       (choices[1].is_valid || choices[3].is_valid)) {
                best = choices[1].is_valid ? &choices[1] : &choices[3];
            } else if (objective_band_code() > 1 && (choices[1].is_valid || choices[3].is_valid)) {
                best = choices[1].is_valid ? &choices[1] : &choices[3];
            } else if (!w_c) {
                for (int index : {3, 0, 1, 2}) {
                    if (!choices[index].is_valid)
                        continue;
                    best = &choices[index];
                    break;
                }
            } else if (hold_prefill_up) {
                EdgeTaskChoice* non_up = nullptr;
                for (int index : {0, 1}) {
                    if (!choices[index].is_valid)
                        continue;
                    if (non_up == nullptr ||
                        choices[index].priority_key < non_up->priority_key - 1e-12 ||
                        (std::abs(choices[index].priority_key - non_up->priority_key) <= 1e-12 &&
                         choices[index].tie_breaker < non_up->tie_breaker)) {
                        non_up = &choices[index];
                    }
                }
                if (non_up != nullptr) {
                    const double service =
                        non_up->task_kind == EdgeTaskKind::decode_post
                            ? task_cost(5, static_cast<int>(non_up->request_ids.size()))
                            : task_cost(2, requests[non_up->request_id].input_length);
                    const double prepare =
                        task_cost(0, requests[choices[3].request_id].input_length);
                    if (current_time_ms + service + prepare <=
                        link_available_time_ms[0] +
                            1e-12 * std::max(1., std::abs(link_available_time_ms[0]))) {
                        best = non_up;
                    } else {
                        best = &choices[3];
                    }
                } else {
                    prefill_post_skip_count = 0;
                    prefill_pre_skip_count = 0;
                    return false;
                }
            } else if (synchronized_decode_active() && choices[0].is_valid) {
                best = &choices[0];
            } else if (synchronized_decode_active() && choices[2].is_valid &&
                       std::any_of(choices[2].request_ids.begin(),
                                   choices[2].request_ids.end(),
                                   [&](int id) { return requests[id].decode_admitted; })) {
                best = &choices[2];
            } else if (latency_round_robin_mode() && !choices[1].is_valid && !choices[3].is_valid) {
                for (int d = 0; d < 2; ++d) {
                    const int cls = (edge_decode_round_robin_class + d) % 2;
                    const int index = cls == 0 ? 0 : 2;
                    if (!choices[index].is_valid)
                        continue;
                    best = &choices[index];
                    edge_decode_round_robin_class = (cls + 1) % 2;
                    break;
                }
            } else if (!tiny_wait_weight_mode() && !long_prefill_risk_mode() &&
                       choices[1].is_valid &&
                       prefill_post_skip_count >= prefill_post_skip_limit()) {
                best = &choices[1];
            } else if (!tiny_wait_weight_mode() && !long_prefill_risk_mode() &&
                       choices[3].is_valid && prefill_pre_skip_count >= prefill_work_skip_limit()) {
                best = &choices[3];
            } else {
                for (EdgeTaskChoice& choice : choices) {
                    if (!choice.is_valid)
                        continue;
                    if (best == nullptr || choice.priority_key < best->priority_key - 1e-12 ||
                        (std::abs(choice.priority_key - best->priority_key) <= 1e-12 &&
                         choice.tie_breaker < best->tie_breaker)) {
                        best = &choice;
                    }
                }
            }
            if (best == nullptr) {
                prefill_post_skip_count = 0;
                prefill_pre_skip_count = 0;
                return false;
            }
            update_skip_counter(prefill_post_skip_count,
                                choices[1].is_valid,
                                best->task_kind == EdgeTaskKind::prefill_post);
            update_skip_counter(prefill_pre_skip_count,
                                choices[3].is_valid,
                                best->task_kind == EdgeTaskKind::prefill_pre);
            if (best->task_kind == EdgeTaskKind::decode_post) {
                task = "E D POST -1";
                append_request_group(task, best->request_ids);
                for (int id : best->request_ids) {
                    const int w = requests[id].decode_wave_id;
                    if (w >= 0 && w < static_cast<int>(decode_waves.size())) {
                        --decode_waves[w].remaining_members;
                        --decode_waves[w].ready_members;
                    }
                    requests[id].decode_wave_id = -1;
                    set_request_phase(id, RequestPhase::decode_post_running);
                }
            } else if (best->task_kind == EdgeTaskKind::prefill_post) {
                Request& r = requests[best->request_id];
                task = "E P POST " + std::to_string(r.cloud_id) + " " +
                       std::to_string(best->request_id);
                set_request_phase(best->request_id, RequestPhase::prefill_post_running);
            } else if (best->task_kind == EdgeTaskKind::decode_pre) {
                task = "E D PRE -1";
                append_request_group(task, best->request_ids);
                bool sync = synchronized_decode_active() || modeled_cloud_prefix_mode();
                if (!sync && continuation_pair_wave_domain() && best->request_ids.size() == 2 &&
                    requests[best->request_ids[0]].cloud_id !=
                        requests[best->request_ids[1]].cloud_id) {
                    const double saved_post_service = 2. * task_cost(5, 1) - task_cost(5, 2);
                    sync = transfer_cost_ms(1) <= saved_post_service + 1e-12;
                }
                const int wave_id = sync ? static_cast<int>(decode_waves.size()) : -1;
                if (sync)
                    decode_waves.push_back({static_cast<int>(best->request_ids.size()), 0});
                for (int id : best->request_ids) {
                    Request& r = requests[id];
                    r.decode_wave_id = wave_id;
                    if (!r.decode_admitted) {
                        if (r.tokens_produced == 0 && unopened_decode_ready_count > 0)
                            --unopened_decode_ready_count;
                        r.decode_admitted = true;
                        ++active_decode_requests;
                        ++cloud_decode_load[r.cloud_id];
                    }
                    set_request_phase(id, RequestPhase::decode_pre_running);
                }
            } else {
                Request& r = requests[best->request_id];
                best->cloud_id =
                    best->cloud_id >= 0 ? best->cloud_id : choose_rollout_cloud(best->request_id);
                r.cloud_id = best->cloud_id;
                r.counted_in_cloud_load = true;
                ++cloud_request_load[r.cloud_id];
                cloud_prefill_work_ms[r.cloud_id] += task_times.duration(1, r.input_length);
                task = "E P PRE " + std::to_string(r.cloud_id) + " " +
                       std::to_string(best->request_id);
                set_request_phase(best->request_id, RequestPhase::prefill_pre_running);
            }
            edge_busy = true;
            return true;
        }

        int choose_prefill_proc_request(int cloud, double& key) {
            const std::vector<int> ids = collect_ready_requests(prefill_proc_ready_queues[cloud],
                                                                RequestPhase::prefill_proc_ready);
            int best_id = -1;
            key = 1e100;
            double best_rank = 1e100, best_tie_time = 1e100;
            bool use_ready_order = strong_waiting_fallback_mode() &&
                                   (runtime_fallback_enabled ||
                                    minimum_prefill_path_ms > tdr_slo_ms * (1. + distance_base) ||
                                    (w_c >= .5 - 1e-12 && distance_base <= .25 + 1e-12));
            for (int id : ids) {
                const Request& request = requests[id];
                double remaining_fraction =
                           static_cast<double>(num_layers - request.next_prefill_layer) /
                           num_layers,
                       remaining_cost =
                           task_setup_ms +
                           remaining_fraction * task_times.duration(1, request.input_length) +
                           transfer_cost_ms(request.input_length) +
                           task_cost(2, request.input_length),
                       item_key = prefill_priority_key(id, remaining_cost, .15 + .10 * w_c),
                       rank = strong_waiting_fallback_mode()
                                  ? (use_ready_order ? request.ready_since_ms : remaining_cost)
                              : tiny_wait_weight_mode() ? request.arrival_time_ms
                              : objective_band_code() > 1
                                  ? item_key
                                  : (runtime_fallback_active()
                                         ? request.ready_since_ms
                                         : (startup_srpt_active()
                                                ? remaining_cost
                                                : (protected_startup_chunk_and_prior_mode() &&
                                                           produced_token_count == 0
                                                       ? remaining_cost / std::max(1e-9, tdr_slo_ms)
                                                       : item_key))),
                       tie_time = strong_waiting_fallback_mode() && !use_ready_order
                                      ? request.arrival_time_ms
                                      : 0.;
                if (rank < best_rank - 1e-12 || (std::abs(rank - best_rank) <= 1e-12 &&
                                                 (tie_time < best_tie_time - 1e-12 ||
                                                  (std::abs(tie_time - best_tie_time) <= 1e-12 &&
                                                   (best_id < 0 || id < best_id)))))
                    best_id = id, best_rank = rank, best_tie_time = tie_time, key = item_key;
            }
            return best_id;
        }

        std::vector<int> build_decode_proc_group(int cloud, double& key) {
            std::vector<int> ids = collect_ready_requests(decode_proc_ready_queues[cloud],
                                                          RequestPhase::decode_proc_ready);
            if (ids.empty()) {
                key = 1e100;
                return ids;
            }
            if (tiny_wait_weight_mode())
                std::sort(ids.begin(), ids.end(), [&](int x, int y) {
                    return requests[x].last_token_time_ms != requests[y].last_token_time_ms
                               ? requests[x].last_token_time_ms < requests[y].last_token_time_ms
                               : x < y;
                });
            else
                std::sort(ids.begin(), ids.end(), [&](int x, int y) {
                    const bool left_started = requests[x].tokens_produced > 0;
                    const bool right_started = requests[y].tokens_produced > 0;
                    if (left_started != right_started)
                        return left_started > right_started;
                    if (left_started &&
                        requests[x].last_token_time_ms != requests[y].last_token_time_ms) {
                        return requests[x].last_token_time_ms < requests[y].last_token_time_ms;
                    }
                    if (requests[x].tokens_produced != requests[y].tokens_produced)
                        return requests[x].tokens_produced < requests[y].tokens_produced;
                    return x < y;
                });
            if (should_hold_for_next_transfer(1,
                                              static_cast<int>(ids.size()),
                                              cloud_decode_population(cloud),
                                              next_predicted_decode_transfer(0, cloud))) {
                key = 1e100;
                return {};
            }
            if (legacy_grouping_mode()) {
                if (distance_base < 64.)
                    ids.resize(throughput_batch_threshold(1, static_cast<int>(ids.size()), 5));
                if (should_hold_for_known_transfer(1,
                                                   static_cast<int>(ids.size()),
                                                   next_predicted_decode_transfer(0, cloud))) {
                    key = 1e100;
                    return {};
                }
            } else {
                bool whole_wave = synchronized_decode_active();
                if (whole_wave || continuation_pair_wave_domain()) {
                    int wave_id = -1;
                    for (int id : ids) {
                        const int w = requests[id].decode_wave_id;
                        if (w >= 0 && (wave_id < 0 || w < wave_id))
                            wave_id = w;
                    }
                    if (wave_id >= 0) {
                        whole_wave = true;
                        ids.erase(std::remove_if(ids.begin(),
                                                 ids.end(),
                                                 [&](int id) {
                                                     return requests[id].decode_wave_id != wave_id;
                                                 }),
                                  ids.end());
                    }
                }
                if (!whole_wave) {
                    ids.resize(tiny_wait_weight_mode() ? aged_batch_size(1, ids)
                                                       : dynamic_group_size(1, ids));
                    if (!tiny_wait_weight_mode() &&
                        should_hold_for_known_transfer(1,
                                                       static_cast<int>(ids.size()),
                                                       next_predicted_decode_transfer(0, cloud))) {
                        key = 1e100;
                        return {};
                    }
                }
            }
            const int batch_size = static_cast<int>(ids.size());
            const double finish = current_time_ms + task_cost(4, batch_size) +
                                  transfer_cost_ms(batch_size) + task_cost(5, batch_size);
            bool has_open = false;
            key = 1e100;
            for (int id : ids) {
                if (requests[id].tokens_produced == 0)
                    continue;
                has_open = true;
                key = std::min(
                    key, (requests[id].last_token_time_ms + tpot_slo_ms - finish) / tpot_slo_ms);
            }
            if (has_open) {
                key -= 0.30 + 0.15 * w_tp;
            } else {
                key = .25 + 0.15 * w_c - .25 * w_tp;
            }
            key -= age_bonus(ids, has_open ? tpot_slo_ms : tdr_slo_ms);
            key -= 0.025 * std::log2(static_cast<double>(batch_size) + 1.);
            return ids;
        }

        bool strong_waiting_prefers_prefill(int cloud,
                                            int prefill_id,
                                            const std::vector<int>& decode_ids) {
            Request& prefill_request = requests[prefill_id];
            int decode_batch_size = static_cast<int>(decode_ids.size());
            double link_wait = std::max(0., link_available_time_ms[1] - current_time_ms),
                   prefill_service =
                       task_setup_ms +
                       task_times.duration(1, prefill_request.input_length) *
                           static_cast<double>(num_layers - prefill_request.next_prefill_layer) /
                           num_layers +
                       link_wait + transfer_cost_ms(prefill_request.input_length) +
                       task_cost(2, prefill_request.input_length),
                   decode_service = std::max(task_cost(4, decode_batch_size),
                                             transfer_cost_ms(decode_batch_size)) +
                                    link_wait + transfer_cost_ms(decode_batch_size) +
                                    task_cost(5, decode_batch_size),
                   throughput_marginal =
                       w_tp * strong_waiting_max_decode_rate /
                       std::max(1e-15, throughput_upper_bound - throughput_baseline),
                   waiting_weight = w_c / std::max(1e-15, distance_base), max_decode_age = 0.;
            for (int id : decode_ids)
                max_decode_age =
                    std::max(max_decode_age, current_time_ms - requests[id].last_token_time_ms);
            double prefill_gain = throughput_marginal +
                                  waiting_weight *
                                      std::max(0.,
                                               (current_time_ms - prefill_request.arrival_time_ms) /
                                                       tdr_slo_ms -
                                                   1.),
                   decode_gain = throughput_marginal +
                                 waiting_weight * std::max(0., max_decode_age / tpot_slo_ms - 1.);
            int prefill_ready_count =
                    static_cast<int>(collect_ready_requests(prefill_proc_ready_queues[cloud],
                                                            RequestPhase::prefill_proc_ready)
                                         .size()),
                active_population = active_decode_requests + unopened_decode_ready_count;
            return prefill_gain * prefill_ready_count * active_population * decode_service >
                   decode_gain * decode_proc_ready_count[cloud] * decode_batch_size *
                       pending_prefill_count * prefill_service;
        }

        bool long_risk_prefers_prefill(int cloud,
                                       int prefill_id,
                                       const std::vector<int>& decode_ids) {
            Request& prefill_request = requests[prefill_id];
            double link_wait = link_available_time_ms[1] - current_time_ms;
            double prefill_service = task_setup_ms +
                                     task_times.duration(1, prefill_request.input_length) *
                                         (num_layers - prefill_request.next_prefill_layer) /
                                         num_layers +
                                     link_wait + transfer_cost_ms(prefill_request.input_length) +
                                     task_cost(2, prefill_request.input_length);
            int decode_batch_size = decode_ids.size(), best_cohort = best_rate_cohort.back();
            double decode_service = task_cost(4, decode_batch_size) + link_wait +
                                    transfer_cost_ms(decode_batch_size) +
                                    task_cost(5, decode_batch_size);
            double throughput_marginal = w_tp * best_cohort / cohort_cycle_ms[best_cohort] /
                                         (throughput_upper_bound - throughput_baseline);
            double waiting_weight = w_c / distance_base;
            double max_decode_age = 0.;
            for (int id : decode_ids) {
                max_decode_age =
                    std::max(max_decode_age, current_time_ms - requests[id].last_token_time_ms);
            }
            double prefill_gain =
                throughput_marginal +
                waiting_weight *
                    std::max(0.,
                             (current_time_ms - prefill_request.arrival_time_ms) / tdr_slo_ms - 1.);
            double decode_gain = throughput_marginal +
                                 waiting_weight * std::max(0., max_decode_age / tpot_slo_ms - 1.);
            int prefill_ready_count = collect_ready_requests(prefill_proc_ready_queues[cloud],
                                                             RequestPhase::prefill_proc_ready)
                                          .size();
            return prefill_gain * prefill_ready_count * active_decode_requests * decode_service >
                   decode_gain * decode_proc_ready_count[cloud] * decode_batch_size *
                       pending_prefill_count * prefill_service;
        }

        bool schedule_cloud_task(int cloud, std::string& task, bool& is_decode) {
            double decode_key = 0, prefill_key = 0;
            std::vector<int> decode_ids = build_decode_proc_group(cloud, decode_key);
            const int prefill_id = choose_prefill_proc_request(cloud, prefill_key);
            if (decode_ids.empty() && prefill_id < 0) {
                if (cloud_decode_load[cloud] > 0 &&
                    current_time_ms != last_cloud_starvation_time_ms[cloud]) {
                    last_cloud_starvation_time_ms[cloud] = current_time_ms;
                    record_controller_opportunity(0, true);
                }
                return false;
            }
            bool run_decode = !decode_ids.empty() &&
                              (prefill_id < 0 ||
                               (strong_waiting_fallback_mode()
                                    ? !strong_waiting_prefers_prefill(cloud, prefill_id, decode_ids)
                                : long_prefill_risk_mode()
                                    ? !long_risk_prefers_prefill(cloud, prefill_id, decode_ids)
                                    : decode_key <= prefill_key + 1e-12));
            if (objective_band_code() > 1 && w_tp < w_c && prefill_id >= 0) {
                run_decode = false;
            } else if (!strong_waiting_fallback_mode() && tiny_wait_weight_mode() &&
                       prefill_id >= 0 && !decode_ids.empty()) {
                run_decode = prefer_decode_over_prefill(prefill_id, decode_ids);
            } else {
                if (!strong_waiting_fallback_mode() && protected_startup_prefill_guard() &&
                    prefill_id >= 0 && !group_contains_started_decode(decode_ids)) {
                    run_decode = false;
                } else if (!strong_waiting_fallback_mode() && runtime_fallback_active() &&
                           prefill_id >= 0 && !decode_ids.empty()) {
                    const int limit = w_c >= .5 - 1e-12 ? 2 : 4;
                    run_decode = decode_proc_streak[cloud] < limit;
                } else if (!strong_waiting_fallback_mode() && pure_waiting_objective() &&
                           prefill_id >= 0 && !group_contains_started_decode(decode_ids)) {
                    run_decode = false;
                }
                if (!strong_waiting_fallback_mode() && !runtime_fallback_active() &&
                    !long_prefill_risk_mode() && prefill_id >= 0 &&
                    prefill_proc_skip_count[cloud] >= prefill_work_skip_limit()) {
                    run_decode = false;
                }
            }
            if (pure_throughput_objective() && prefill_id >= 0 && !decode_ids.empty()) {
                const int prefill_end_layer = choose_prefill_proc_end_layer(prefill_id, cloud);
                const double prefill_service =
                    task_setup_ms +
                    task_times.duration(1, requests[prefill_id].input_length) *
                        static_cast<double>(prefill_end_layer -
                                            requests[prefill_id].next_prefill_layer) /
                        num_layers;
                const double decode_service = task_cost(4, static_cast<int>(decode_ids.size()));
                run_decode =
                    decode_service_debt_ms[cloud] + decode_service <= prefill_service + 1e-12;
            }
            update_skip_counter(prefill_proc_skip_count[cloud], prefill_id >= 0, !run_decode);
            if (run_decode) {
                cloud_predicted_busy_until_ms[cloud] =
                    current_time_ms + task_cost(4, static_cast<int>(decode_ids.size()));
                cloud_running_prefill_work_ms[cloud] = 0;
                decode_service_debt_ms[cloud] += task_cost(4, static_cast<int>(decode_ids.size()));
                ++decode_proc_streak[cloud];
                record_controller_opportunity(static_cast<int>(decode_ids.size()), false);
                is_decode = true;
                task = "C" + std::to_string(cloud) + " D PROC " + std::to_string(cloud);
                append_request_group(task, decode_ids);
                for (int id : decode_ids)
                    set_request_phase(id, RequestPhase::decode_proc_running);
            } else {
                decode_proc_streak[cloud] = 0;
                decode_service_debt_ms[cloud] = 0;
                const int end_layer = choose_prefill_proc_end_layer(prefill_id, cloud);
                if (!strong_waiting_fallback_mode() &&
                    should_defer_prefill_proc_for_decode_transfer(cloud, prefill_id, end_layer))
                    return false;
                cloud_running_prefill_work_ms[cloud] =
                    task_times.duration(1, requests[prefill_id].input_length) *
                    static_cast<double>(end_layer - requests[prefill_id].next_prefill_layer) /
                    num_layers;
                cloud_predicted_busy_until_ms[cloud] =
                    current_time_ms + task_setup_ms + cloud_running_prefill_work_ms[cloud];
                is_decode = false;
                task = "C" + std::to_string(cloud) + " P PROC " +
                       std::to_string(requests[prefill_id].next_prefill_layer) + " " +
                       std::to_string(end_layer) + " " + std::to_string(cloud) + " " +
                       std::to_string(prefill_id);
                requests[prefill_id].scheduled_prefill_layer_end = end_layer;
                set_request_phase(prefill_id, RequestPhase::prefill_proc_running);
            }
            cloud_busy[cloud] = true;
            return true;
        }

        std::vector<std::string> build_assignments() {
            update_runtime_fallback();
            if (has_active_decode_output())
                decode_stream_observed = true;
            std::vector<std::string> ans;
            ans.reserve(static_cast<std::size_t>(num_clouds) + 1);
            if (strong_waiting_fallback_mode()) {
                if (!edge_busy) {
                    std::string t;
                    if (schedule_edge_task(t))
                        ans.push_back(std::move(t));
                }
                for (int c = 0; c < num_clouds; ++c) {
                    if (cloud_busy[c])
                        continue;
                    std::string t;
                    bool d = false;
                    if (schedule_cloud_task(c, t, d))
                        ans.push_back(std::move(t));
                }
                return ans;
            }
            std::vector<std::string> p_ans;
            p_ans.reserve(num_clouds);
            for (int c = 0; c < num_clouds; ++c) {
                if (cloud_busy[c])
                    continue;
                std::string task;
                bool is_decode = false;
                if (!schedule_cloud_task(c, task, is_decode))
                    continue;
                if (is_decode)
                    ans.push_back(std::move(task));
                else
                    p_ans.push_back(std::move(task));
            }
            for (std::string& task : p_ans)
                ans.push_back(std::move(task));
            if (tiny_wait_weight_mode())
                std::sort(ans.begin(), ans.end(), [](const std::string& a, const std::string& b) {
                    return std::stoi(a.c_str() + 1) < std::stoi(b.c_str() + 1);
                });
            if (!edge_busy) {
                std::string task;
                if (schedule_edge_task(task)) {
                    if (tiny_wait_weight_mode())
                        ans.insert(ans.begin(), std::move(task));
                    else
                        ans.push_back(std::move(task));
                }
            }
            return ans;
        }
    };
}  // namespace

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int num_clouds = 0, bytes_per_token = 0, num_layers = 0;
    double task_setup_ms = 0, transfer_latency_ms = 0, bandwidth_gbps = 0;
    if (!(std::cin >> num_clouds >> task_setup_ms >> transfer_latency_ms >> bandwidth_gbps >>
          bytes_per_token >> num_layers)) {
        return 0;
    }
    double tdr_slo_ms = 0, tpot_slo_ms = 0, throughput_upper_bound = 0, throughput_baseline = 0;
    double distance_base = 0, w_tp = 0, w_c = 0;
    if (!(std::cin >> tdr_slo_ms >> tpot_slo_ms >> throughput_upper_bound >> throughput_baseline >>
          distance_base >> w_tp >> w_c)) {
        return 0;
    }
    int n = 0;
    if (!(std::cin >> n) || n < 0)
        return 0;
    TaskTimeTable task_times;
    for (int i = 0; i < n; ++i) {
        int size = 0;
        std::array<double, 6> value{};
        if (!(std::cin >> size))
            return 0;
        for (double& x : value) {
            if (!(std::cin >> x))
                return 0;
        }
        task_times.add_sample(size, value);
    }
    task_times.sort_samples();
    Scheduler sol(num_clouds,
                  num_layers,
                  bytes_per_token,
                  task_setup_ms,
                  transfer_latency_ms,
                  bandwidth_gbps,
                  tdr_slo_ms,
                  tpot_slo_ms,
                  throughput_upper_bound,
                  throughput_baseline,
                  distance_base,
                  w_tp,
                  w_c,
                  std::move(task_times));
    std::string header;
    while (std::cin >> header) {
        if (header == "END")
            return 0;
        char* end = nullptr;
        const double time = std::strtod(header.c_str(), &end);
        if (end == header.c_str() || *end != '\0' || !std::isfinite(time) || time < 0)
            return 0;
        sol.current_time_ms = time;
        int events = -1;
        if (!(std::cin >> events) || events < 0)
            return 0;
        std::vector<int> fin;
        for (int i = 0; i < events; ++i) {
            if (!sol.read_event(std::cin, fin))
                return 0;
        }
        if (!sol.finish_frame(fin))
            return 0;
        const std::vector<std::string> ans = sol.build_assignments();
        std::cout << ans.size() << "\n";
        for (const std::string& task : ans)
            std::cout << task << "\n";
        std::cout << std::flush;
        if (!std::cout)
            return 0;
    }
    return 0;
}
