///|
priv struct Batch {
  jobs : Array[Job]
  mut estimate : Int32
}

///|
fn group_jobs(jobs : Array[Job], default_duration : Int32) -> Array[Batch] {
  let groups : Map[String, Batch] = Map([])
  let batches : Array[Batch] = []
  for job in jobs {
    let estimate = job.duration_ms.unwrap_or(default_duration)
    if job.group is Some(name) && groups.get(name) is Some(batch) {
      batch.jobs.push(job)
      batch.estimate += estimate
    } else {
      let batch : Batch = { jobs: [job], estimate, }
      batches.push(batch)
      if job.group is Some(name) {
        groups[name] = batch
      }
    }
  }
  batches
}

///|
priv struct Placement {
  batch : Batch
  eligible : Array[Int32]
  mask : UInt32
}

///|
fn placements(
  batches : Array[Batch],
  workers : Array[Worker],
) -> Array[Placement] raise PlanError {
  // A worker occupies one bit. A batch must satisfy every job's labels.
  let label_workers : Map[String, UInt32] = Map([])
  let mut all_workers = 0U
  for i, worker in workers {
    let bit = 1U << i
    all_workers = all_workers | bit
    for label in worker.labels {
      label_workers[label] = label_workers.get(label).unwrap_or(0U) | bit
    }
  }
  // The candidate lists are shared read-only within this plan.
  let eligible_workers : Map[UInt32, Array[Int32]] = Map([])
  let result : Array[Placement] = []
  for batch in batches {
    let mut mask = all_workers
    for job in batch.jobs {
      for label in job.requires {
        mask = mask & label_workers.get(label).unwrap_or(0U)
      }
    }
    if mask == 0U {
      let first = batch.jobs[0]
      let label = match first.group {
        Some(group) => "group " + group
        None => "job " + first.id
      }
      raise PlanError("no eligible worker for " + label)
    }
    let eligible = match eligible_workers.get(mask) {
      Some(indices) => indices
      None => {
        let indices : Array[Int32] = []
        // Take the lowest set bit first to preserve runner tie-break order.
        let mut remaining = mask
        while remaining != 0U {
          indices.push(remaining.ctz())
          remaining = remaining & (remaining - 1U)
        }
        eligible_workers[mask] = indices
        indices
      }
    }
    result.push({ batch, eligible, mask, })
  }
  result.sort_by((a, b) => {
    let limit = a.eligible.length().compare(b.eligible.length())
    if limit != 0 {
      return limit
    }
    let duration = b.batch.estimate.compare(a.batch.estimate)
    if duration != 0 {
      return duration
    }
    a.batch.jobs[0].id.compare(b.batch.jobs[0].id)
  })
  result
}

///|
priv struct PoolWork {
  mut duration : Int32
  mut batches : Int32
  mut granularity : Int32
}

///|
fn dense_workloads(
  workloads : Map[UInt32, PoolWork],
  worker_count : Int32,
) -> Array[Int32]? {
  // Keep the table small, and use it only when repeated scans cost more.
  if worker_count > 12 {
    return None
  }
  let size = 1 << worker_count
  let distinct = workloads.length()
  if distinct * distinct < 2 * worker_count * size {
    return None
  }
  let totals = Array::make(size, 0)
  for mask, workload in workloads {
    totals[mask.reinterpret_as_int()] = workload.duration
  }
  // Process two runner bits per pass. Each group of four cells has the
  // same other bits, so the both-set cell adds the other three subtotals.
  for pair in 0..<(worker_count / 2) {
    let step = 1 << (2 * pair)
    let stride = step * 4
    let mut start = 0
    while start < size {
      for lower in start..<(start + step) {
        let first = lower + step
        let second = first + step
        let both = second + step
        let neither = totals[lower]
        let second_only = totals[second]
        let first_sum = totals[first] + neither
        totals[first] = first_sum
        totals[second] = second_only + neither
        totals[both] += first_sum + second_only
      }
      start += stride
    }
  }
  // With an odd runner count, the highest bit needs one final pass.
  if worker_count % 2 == 1 {
    let half = size / 2
    for lower in 0.. SparseWork {
  let distinct = workloads.length()
  if distinct < 64 {
    let entries : Array[(UInt32, Int32)] = []
    for mask, workload in workloads {
      entries.push((mask, workload.duration))
    }
    return { entries, ends_by_count: [], }
  }
  // Entry ranges are ordered by cardinality. A query only needs the
  // prefix whose masks have at most as many workers as the query mask.
  let ends_by_count = Array::make(worker_count + 1, 0)
  for mask in workloads.keys() {
    ends_by_count[mask.popcnt()] += 1
  }
  for count in 1..<=worker_count {
    ends_by_count[count] += ends_by_count[count - 1]
  }
  let cursors = ends_by_count.copy()
  let entries = Array::make(distinct, (0U, 0))
  for mask, workload in workloads {
    let count = mask.popcnt()
    cursors[count] -= 1
    entries[cursors[count]] = (mask, workload.duration)
  }
  { entries, ends_by_count, }
}

///|
fn work_bound(
  mask : UInt32,
  sparse : SparseWork,
  totals : Array[Int32]?,
  workloads : Map[UInt32, PoolWork],
) -> Int32 {
  let count = mask.popcnt()
  let work = if totals is Some(dense) {
    dense[mask.reinterpret_as_int()]
  } else if count <= 5 && (1 << count) * 4 <= sparse.entries.length() {
    // Keep hash lookups to at most 31 per query. A contiguous scan is
    // less expensive when there are few sparse entries or more workers.
    let mut sum = 0
    let mut subset = mask
    while subset != 0U {
      if workloads.get(subset) is Some(workload) {
        sum += workload.duration
      }
      subset = (subset - 1U) & mask
    }
    sum
  } else {
    let (end, exact) = if sparse.ends_by_count.is_empty() {
      (sparse.entries.length(), 0)
    } else {
      let exact = workloads.get(mask).map(workload => workload.duration)
      // An equal-size subset can only be the mask itself.
      (sparse.ends_by_count[count - 1], exact.unwrap_or(0))
    }
    let mut sum = exact
    for entry in sparse.entries[0:end] {
      let (candidate, duration) = entry
      if (candidate & mask) == candidate {
        sum += duration
      }
    }
    sum
  }
  (work + count - 1) / count
}

///|
fn pool_durations(
  pools : Array[UInt32],
  options : Array[Placement],
  worker_count : Int32,
) -> Array[Array[Int32]] {
  let durations = pools.map(_ => [])
  let by_worker = Array::make(worker_count, -1)
  let mut has_multi_worker_pool = false
  for i, mask in pools {
    if mask.popcnt() <= 1 {
      continue
    }
    has_multi_worker_pool = true
    let mut remaining = mask
    while remaining != 0U {
      by_worker[remaining.ctz()] = i
      remaining = remaining & (remaining - 1U)
    }
  }
  if has_multi_worker_pool {
    for option in options {
      let pool = by_worker[option.eligible[0]]
      // Fully flexible batches can span distinct pools or unused workers.
      if pool >= 0 && (option.mask & pools[pool]) == option.mask {
        durations[pool].push(option.batch.estimate)
      }
    }
  }
  durations
}

///|
fn pool_bounds(
  worker_count : Int32,
  durations : Array[Int32],
  average : Int32,
) -> (Int32, Int32) {
  let mut granularity = 0
  for duration in durations {
    if granularity == 1 {
      break
    }
    if granularity != duration {
      granularity = duration_gcd(granularity, duration)
    }
  }
  let mut lower = average
  if durations.length() > worker_count {
    durations.sort_by((a, b) => b.compare(a))
    for i in worker_count.. (Int32, Int32) {
  let workloads : Map[UInt32, PoolWork] = Map([])
  let mut lower = 0
  for option in options {
    let mask = option.mask
    let duration = option.batch.estimate
    let workload = match workloads.get(mask) {
      Some(entry) => entry
      None => {
        let entry : PoolWork = {
          duration: 0,
          batches: 0,
          granularity: duration,
        }
        workloads[mask] = entry
        entry
      }
    }
    if workload.granularity != 1 && workload.granularity != duration {
      workload.granularity = duration_gcd(workload.granularity, duration)
    }
    // Within one mask, options are sorted from longest to shortest. If k
    // batches share m runners, some runner must execute at least ceil(k/m).
    workload.duration += duration
    let per_runner = workload.batches / option.eligible.length() + 1
    workload.batches += 1
    lower = lower.max(per_runner * duration)
  }
  let totals = dense_workloads(workloads, worker_count)
  let sparse = if totals is None {
    sparse_workloads(workloads, worker_count)
  } else {
    { entries: [], ends_by_count: [], }
  }
  let pools : Array[UInt32] = []
  let constrained : Array[UInt32] = []
  let mut rounded_pools = 0
  for mask, workload in workloads {
    let count = mask.popcnt()
    lower = lower.max(work_bound(mask, sparse, totals, workloads))
    if count > 1 && workload.batches > count && workload.granularity > 1 {
      // Round only the work with this exact mask. A different mask's
      // batches might have durations outside this cohort's granularity.
      let average = (workload.duration + count - 1) / count
      rounded_pools = rounded_pools.max(
        round_bound(average, workload.granularity),
      )
    }
    // Fully flexible work can run outside any constrained pool.
    if count == worker_count {
      continue
    }
    // A singleton cannot overlap another mask without being a subset.
    if count > 1 {
      constrained.push(mask)
    }
    let mut merged = mask
    let mut i = 0
    while i < pools.length() {
      if (pools[i] & merged) == 0U {
        i += 1
      } else {
        merged = merged | pools.remove(i)
      }
    }
    pools.push(merged)
  }
  let durations = pool_durations(pools, options, worker_count)
  for i, mask in pools {
    let (pool_lower, rounded) = pool_bounds(
      mask.popcnt(),
      durations[i],
      work_bound(mask, sparse, totals, workloads),
    )
    lower = lower.max(pool_lower)
    rounded_pools = rounded_pools.max(rounded)
  }
  // A light batch can connect a busy subpool to an otherwise idle runner.
  // Check overlapping mask pairs as well as the fully connected pools.
  let checked : Map[UInt32, Bool] = Map([])
  let mut remaining_pairs = 512
  for i, left in constrained {
    for j in (i + 1).. Schedule {
  let worker_of : Array[Int32] = []
  let loads = Array::make(worker_count, 0)
  let mut makespan = 0
  for option in options {
    let mut best = option.eligible[0]
    for index in option.eligible {
      if loads[index] < loads[best] {
        best = index
      }
    }
    loads[best] += option.batch.estimate
    makespan = makespan.max(loads[best])
    worker_of.push(best)
  }
  { options, worker_of, loads, makespan, }
}

///|
fn exchange(schedule : Schedule, busiest : Int32, other_max : Int32) -> Bool {
  let loads = schedule.loads
  let worker_of = schedule.worker_of
  let options = schedule.options
  let busiest_bit = 1U << busiest
  let departures : Array[Int32] = []
  let arrivals : Array[Int32] = []
  for i, option in options {
    if worker_of[i] == busiest {
      if option.eligible.length() > 1 {
        departures.push(i)
      }
    } else if (option.mask & busiest_bit) != 0U {
      arrivals.push(i)
    }
  }
  // Limit the search in large manifests while retaining deterministic order.
  let pair_budget = 2048
  let mut evaluated = 0
  let mut best = schedule.makespan
  let mut swap : (Int32, Int32, Int32)? = None
  for i in departures {
    if evaluated == pair_budget {
      break
    }
    let outgoing = options[i]
    for j in arrivals {
      if evaluated == pair_budget {
        break
      }
      evaluated += 1
      let destination = worker_of[j]
      let delta = outgoing.batch.estimate - options[j].batch.estimate
      if delta <= 0 || (outgoing.mask & (1U << destination)) == 0U {
        continue
      }
      // The destination's load increases, so other_max remains a valid
      // baseline even when that load is the old second-largest one.
      let candidate = other_max
        .max(loads[busiest] - delta)
        .max(loads[destination] + delta)
      if candidate < best {
        best = candidate
        swap = Some((i, j, delta))
      }
    }
  }
  guard swap is Some((i, j, delta)) else { return false }
  let destination = worker_of[j]
  loads[busiest] -= delta
  loads[destination] += delta
  worker_of[i] = destination
  worker_of[j] = busiest
  schedule.makespan = best
  true
}

///|
fn improve(schedule : Schedule, lower_bound : Int32) -> Unit {
  let loads = schedule.loads
  // Each pass tries a move first, then a bounded exchange if moves stall.
  for _ in 0..<16 {
    if schedule.makespan <= lower_bound {
      break
    }
    let mut busiest = 0
    let mut other_max = 0
    for i in 1.. loads[busiest] {
        other_max = loads[busiest]
        busiest = i
      } else {
        other_max = other_max.max(loads[i])
      }
    }
    // A move or exchange cannot strictly lower tied maximum loads.
    if other_max == schedule.makespan {
      break
    }
    let mut best = schedule.makespan
    let mut relocation : (Int32, Int32)? = None
    for i, option in schedule.options {
      if schedule.worker_of[i] != busiest {
        continue
      }
      let estimate = option.batch.estimate
      let baseline = other_max.max(loads[busiest] - estimate)
      for destination in option.eligible {
        if destination == busiest {
          continue
        }
        let candidate = baseline.max(loads[destination] + estimate)
        if candidate < best {
          best = candidate
          relocation = Some((i, destination))
        }
      }
    }
    guard relocation is Some((i, destination)) else {
      if exchange(schedule, busiest, other_max) {
        continue
      }
      break
    }
    let estimate = schedule.options[i].batch.estimate
    loads[busiest] -= estimate
    loads[destination] += estimate
    schedule.worker_of[i] = destination
    schedule.makespan = best
  }
}

///|
fn lightest_receivers(
  option : Placement,
  loads : Array[Int32],
  excluded : UInt32,
) -> Array[Int32] {
  let mut first = -1
  let mut second = -1
  for worker in option.eligible {
    if (excluded & (1U << worker)) != 0U {
      continue
    }
    if first < 0 || loads[worker] < loads[first] {
      second = first
      first = worker
    } else if second < 0 || loads[worker] < loads[second] {
      second = worker
    }
  }
  if second >= 0 {
    [first, second]
  } else if first >= 0 {
    [first]
  } else {
    []
  }
}

///|
fn relieve_tied_workers(schedule : Schedule, lower_bound : Int32) -> Bool {
  let loads = schedule.loads
  let options = schedule.options
  let worker_of = schedule.worker_of
  let peak = schedule.makespan
  let mut first = -1
  let mut second = -1
  let mut other_max = 0
  for worker, load in loads {
    if load < peak {
      other_max = other_max.max(load)
    } else if first < 0 {
      first = worker
    } else if second < 0 {
      second = worker
    } else {
      // Relocating two batches cannot lower three or more tied peaks.
      return false
    }
  }
  if second < 0 || loads.length() < 3 {
    return false
  }
  let excluded = (1U << first) | (1U << second)
  let from_first : Array[(Int32, Array[Int32])] = []
  let from_second : Array[(Int32, Array[Int32])] = []
  for i, option in options {
    if option.eligible.length() <= 1 {
      continue
    }
    if worker_of[i] == first {
      from_first.push((i, lightest_receivers(option, loads, excluded)))
    } else if worker_of[i] == second {
      from_second.push((i, lightest_receivers(option, loads, excluded)))
    }
  }
  let mut remaining_pairs = 2048
  let mut best = peak
  let mut relocation : (Int32, Int32, Int32)? = None
  let mut split_best = peak
  let mut split_relocation : (Int32, Int32, Int32, Int32)? = None
  for entry in from_first {
    let (i, first_receivers) = entry
    if remaining_pairs == 0 || best <= lower_bound {
      break
    }
    let outgoing = options[i]
    for entry in from_second {
      let (j, second_receivers) = entry
      if remaining_pairs == 0 || best <= lower_bound {
        break
      }
      remaining_pairs -= 1
      if first_receivers.is_empty() || second_receivers.is_empty() {
        continue
      }
      let partner = options[j]
      let first_load = loads[first_receivers[0]]
      let second_load = loads[second_receivers[0]]
      let baseline = other_max
        .max(peak - outgoing.batch.estimate)
        .max(peak - partner.batch.estimate)
      let combined = outgoing.batch.estimate + partner.batch.estimate
      // A shared receiver cannot be lighter than either batch's own
      // lightest eligible receiver. Keep counting all considered pairs.
      if baseline.max(first_load.max(second_load) + combined) < best {
        let mut shared = outgoing.mask & partner.mask & excluded.lnot()
        while shared != 0U {
          let destination = shared.ctz()
          shared = shared & (shared - 1U)
          let candidate = baseline.max(loads[destination] + combined)
          if candidate < best {
            best = candidate
            relocation = Some((i, j, destination))
          }
        }
      }
      // Prefer the existing shared-receiver move. For distinct receivers,
      // at most one batch needs its second choice to avoid a conflict.
      if relocation is None &&
        split_best > lower_bound &&
        baseline
        .max(first_load + outgoing.batch.estimate)
        .max(second_load + partner.batch.estimate) <
        split_best {
        for left in first_receivers {
          for right in second_receivers {
            if left == right {
              continue
            }
            let candidate = baseline
              .max(loads[left] + outgoing.batch.estimate)
              .max(loads[right] + partner.batch.estimate)
            if candidate < split_best {
              split_best = candidate
              split_relocation = Some((i, j, left, right))
            }
          }
        }
      }
    }
  }
  let (i, j, left, right, improved) = if relocation is Some((i, j, destination)) {
    (i, j, destination, destination, best)
  } else if split_relocation is Some((i, j, left, right)) {
    (i, j, left, right, split_best)
  } else {
    return false
  }
  let first_estimate = options[i].batch.estimate
  let second_estimate = options[j].batch.estimate
  loads[first] -= first_estimate
  loads[second] -= second_estimate
  loads[left] += first_estimate
  loads[right] += second_estimate
  worker_of[i] = left
  worker_of[j] = right
  schedule.makespan = improved
  true
}

///|
fn relocate_chain(schedule : Schedule, lower_bound : Int32) -> Bool {
  let loads = schedule.loads
  if loads.length() < 3 {
    return false
  }
  let mut busiest = -1
  for worker, load in loads {
    if load == schedule.makespan {
      if busiest >= 0 {
        return false
      }
      busiest = worker
    }
  }
  let busiest_bit = 1U << busiest
  let departures : Array[Int32] = []
  let releases : Array[(Int32, Int32)] = []
  for i, option in schedule.options {
    let worker = schedule.worker_of[i]
    if option.eligible.length() <= 1 {
      continue
    }
    if worker == busiest {
      departures.push(i)
    } else {
      let excluded = busiest_bit | (1U << worker)
      let receivers = lightest_receivers(option, loads, excluded)
      if !receivers.is_empty() {
        releases.push((i, receivers[0]))
      }
    }
  }
  if departures.is_empty() || releases.is_empty() {
    return false
  }
  // The intermediate runner can become lighter. Exclude its old load.
  let unaffected = Array::makei(loads.length(), middle => {
    let mut maximum = 0
    for worker, load in loads {
      if worker != busiest && worker != middle {
        maximum = maximum.max(load)
      }
    }
    maximum
  })
  let mut best = schedule.makespan
  let mut remaining_pairs = 2048
  let mut relocation : (Int32, Int32, Int32)? = None
  for i in departures {
    if remaining_pairs == 0 || best <= lower_bound {
      break
    }
    let outgoing = schedule.options[i]
    for entry in releases {
      if remaining_pairs == 0 || best <= lower_bound {
        break
      }
      remaining_pairs -= 1
      let (j, destination) = entry
      let middle = schedule.worker_of[j]
      if (outgoing.mask & (1U << middle)) == 0U {
        continue
      }
      let incoming = outgoing.batch.estimate
      let released = schedule.options[j].batch.estimate
      let candidate = unaffected[middle]
        .max(loads[busiest] - incoming)
        .max(loads[middle] + incoming - released)
        .max(loads[destination] + released)
      if candidate < best {
        best = candidate
        relocation = Some((i, j, destination))
      }
    }
  }
  guard relocation is Some((i, j, destination)) else { return false }
  let middle = schedule.worker_of[j]
  let incoming = schedule.options[i].batch.estimate
  let released = schedule.options[j].batch.estimate
  loads[busiest] -= incoming
  loads[middle] += incoming - released
  loads[destination] += released
  schedule.worker_of[i] = middle
  schedule.worker_of[j] = destination
  schedule.makespan = best
  true
}

///|
priv enum BudgetSearch {
  Found
  NoSolution
  LimitReached
}

///|
priv trait BudgetParents {
  fn remember(Self, Int32, Int32, Int32) -> Bool
  fn predecessor(Self, Int32) -> (Int32, Int32)
}

///|
impl BudgetParents for FixedArray[Int32] with fn remember(
  self,
  total,
  batch,
  previous,
) {
  if self[total] != 0 {
    return false
  }
  // Indexed sums fit in 16 bits. Batch indices are below the 1,024-job
  // limit, so store their one-based values above the sum and reserve zero.
  self[total] = ((batch + 1) << 16) | previous
  true
}

///|
impl BudgetParents for FixedArray[Int32] with fn predecessor(self, total) {
  let state = self[total]
  ((state >> 16) - 1, state & 0xffff)
}

///|
impl BudgetParents for Map[Int32, (Int32, Int32)] with fn remember(
  self,
  total,
  batch,
  previous,
) {
  if self.contains(total) {
    return false
  }
  self[total] = (batch, previous)
  true
}

///|
impl BudgetParents for Map[Int32, (Int32, Int32)] with fn predecessor(
  self,
  total,
) {
  self[total]
}

///|
fn choose_budget_subset(
  options : Array[Placement],
  flexible : Array[Int32],
  minimum : Int32,
  maximum : Int32,
  chosen : Array[Int32],
  granularity : Int32,
) -> BudgetSearch {
  if minimum > maximum {
    return NoSolution
  }
  if minimum == 0 {
    return Found
  }
  // Every reachable sum is a multiple of the flexible batches' GCD.
  // Rounded endpoints retain exactly the same set of feasible sums.
  let unit = granularity.max(1)
  let last = maximum / unit
  if last < 65536 {
    let first = round_bound(minimum, unit) / unit
    let parents = FixedArray::make(last + 1, 0)
    search_budget_subset(options, flexible, first, last, chosen, parents, unit)
  } else {
    let parents = Map([(0, (-1, 0))])
    search_budget_subset(
      options, flexible, minimum, maximum, chosen, parents, 1,
    )
  }
}

///|
fn[Parents : BudgetParents] search_budget_subset(
  options : Array[Placement],
  flexible : Array[Int32],
  minimum : Int32,
  maximum : Int32,
  chosen : Array[Int32],
  parents : Parents,
  unit : Int32,
) -> BudgetSearch {
  let reachable = [0]
  let mut remaining = 65536
  let mut target = 0
  for i, index in flexible {
    let duration = options[index].batch.estimate / unit
    // Only extend totals from before this batch, so it can be selected once.
    let previous_count = reachable.length()
    for j in 0.. maximum || !parents.remember(next, i, previous) {
        continue
      }
      if next >= minimum {
        target = next
        break
      }
      reachable.push(next)
    }
    if target > 0 {
      break
    }
  }
  if target == 0 {
    return NoSolution
  }
  while target > 0 {
    let (i, previous) = parents.predecessor(target)
    chosen[i] = 0
    target = previous
  }
  Found
}

///|
fn half_subsets(
  options : Array[Placement],
  flexible : Array[Int32],
  start : Int32,
  count : Int32,
  maximum : Int32,
) -> Array[(Int32, Int32)] {
  let subsets = [(0, 0)]
  for i in 0.. Bool {
  // The caller limits each half to 14 batches, at most 16,384 subsets.
  let split = flexible.length() / 2
  let right_count = flexible.length() - split
  let left = half_subsets(options, flexible, 0, split, maximum)
  let right = half_subsets(options, flexible, split, right_count, maximum)
  right.sort_by((a, b) => {
    let by_sum = a.0.compare(b.0)
    if by_sum != 0 {
      by_sum
    } else {
      a.1.compare(b.1)
    }
  })
  for entry in left {
    let (left_sum, left_mask) = entry
    let mut low = 0
    let mut high = right.length()
    while low < high {
      let middle = (low + high) / 2
      if left_sum + right[middle].0 < minimum {
        low = middle + 1
      } else {
        high = middle
      }
    }
    if low == right.length() || left_sum + right[low].0 > maximum {
      continue
    }
    let right_mask = right[low].1
    for i in 0.. Unit {
  let loads = [0, 0]
  let flexible : Array[Int32] = []
  let mut granularity = 0
  for i, option in schedule.options {
    let duration = option.batch.estimate
    if option.eligible.length() == 1 {
      loads[schedule.worker_of[i]] += duration
    } else {
      flexible.push(i)
      if granularity != 1 && granularity != duration {
        granularity = duration_gcd(granularity, duration)
      }
    }
  }
  let total = schedule.loads[0] + schedule.loads[1]
  let minimum = (total - budget - loads[0]).max(0)
  let maximum = budget - loads[0]
  // Only flexible batches can change the first runner's load. Their
  // combined duration must be a multiple of their common divisor.
  if round_bound(minimum, granularity) > maximum {
    return
  }
  let chosen = Array::make(flexible.length(), 1)
  fn visit(i : Int32, left : Int32, right : Int32) -> Bool {
    if left > budget || right > budget {
      return false
    }
    if i == flexible.length() {
      return true
    }
    let duration = schedule.options[flexible[i]].batch.estimate
    if visit(i + 1, left + duration, right) {
      chosen[i] = 0
      true
    } else if visit(i + 1, left, right + duration) {
      chosen[i] = 1
      true
    } else {
      false
    }
  }
  let found = if flexible.length() <= 16 {
    // At most 2^16 complete assignments, with early pruning on each load.
    visit(0, loads[0], loads[1])
  } else {

    // Keep existing solutions and skip a second search if the first one
    // already established that no subset can fit.
    match
      choose_budget_subset(
        schedule.options,
        flexible,
        minimum,
        maximum,
        chosen,
        granularity,
      ) {
      Found => true
      NoSolution => false
      LimitReached =>
        flexible.length() <= 28 &&
        choose_budget_halves(
          schedule.options,
          flexible,
          minimum,
          maximum,
          chosen,
        )
    }
  }
  if !found {
    return
  }
  for i, index in flexible {
    let worker = chosen[i]
    schedule.worker_of[index] = worker
    loads[worker] += schedule.options[index].batch.estimate
  }
  schedule.loads[0] = loads[0]
  schedule.loads[1] = loads[1]
  schedule.makespan = loads[0].max(loads[1])
}

///|
fn make_shards(schedule : Schedule, workers : Array[Worker]) -> Array[Shard] {
  let assignments : Array[Array[String]] = Array::makei(workers.length(), _ => {
    []
  })
  for i, option in schedule.options {
    let jobs = assignments[schedule.worker_of[i]]
    for job in option.batch.jobs {
      jobs.push(job.id)
    }
  }
  workers.mapi((i, worker) => {
    worker: worker.id,
    jobs: assignments[i],
    estimated_ms: schedule.loads[i],
  })
}

///|
fn duration_gcd(left : Int32, right : Int32) -> Int32 {
  let mut first = left
  let mut second = right
  while second > 0 {
    let remainder = first % second
    first = second
    second = remainder
  }
  first
}

///|
fn round_bound(lower : Int32, granularity : Int32) -> Int32 {
  if granularity > 1 {
    (lower + granularity - 1) / granularity * granularity
  } else {
    lower
  }
}

///|
/// Select a deterministic initial assignment and improve it with whole-group moves and exchanges.
pub fn plan(request : Request) -> Plan raise PlanError {
  validate(request)
  let jobs = request.jobs.copy()
  let workers = request.workers.copy()
  jobs.sort_by_key(job => job.id)
  workers.sort_by_key(worker => worker.id)
  let batches = group_jobs(jobs, request.default_duration_ms)
  let options = placements(batches, workers)
  let mut total = 0
  let mut largest = 0
  let mut granularity = 0
  for option in options {
    let duration = option.batch.estimate
    total += duration
    largest = largest.max(duration)
    if granularity != 1 {
      granularity = duration_gcd(granularity, duration)
    }
  }
  let (eligibility_lower, rounded_pools) = eligibility_bound(
    options,
    workers.length(),
  )
  let lower = largest
    .max((total + workers.length() - 1) / workers.length())
    .max(eligibility_lower)
  let first = assign(options, workers.length())
  let (preferred, alternate) = if first.makespan > lower &&
    options.length() > 1 &&
    options[0].eligible.length() !=
    options[options.length() - 1].eligible.length() {
    let duration_first = options.copy()
    duration_first.sort_by((a, b) => {
      let duration = b.batch.estimate.compare(a.batch.estimate)
      if duration != 0 {
        duration
      } else {
        a.batch.jobs[0].id.compare(b.batch.jobs[0].id)
      }
    })
    let alternative = assign(duration_first, workers.length())
    if alternative.makespan < first.makespan {
      (alternative, Some(first))
    } else {
      (first, Some(alternative))
    }
  } else {
    (first, None)
  }
  // The shorter greedy result may stop at a worse local optimum.
  improve(preferred, lower)
  let schedule = if preferred.makespan > lower && alternate is Some(other) {
    improve(other, lower)
    if other.makespan < preferred.makespan {
      other
    } else {
      preferred
    }
  } else {
    preferred
  }
  if schedule.makespan > lower && relieve_tied_workers(schedule, lower) {
    improve(schedule, lower)
  }
  if schedule.makespan > lower && relocate_chain(schedule, lower) {
    improve(schedule, lower)
  }
  if workers.length() == 2 &&
    request.budget_ms is Some(budget) &&
    budget >= lower &&
    schedule.makespan > budget {
    fit_two_worker_budget(schedule, budget)
  }
  let makespan = schedule.makespan
  // Leave search thresholds unchanged. A reported finish time is a multiple
  // of the granularity because each runner executes whole batches.
  let lower_bound = round_bound(lower, granularity).max(rounded_pools)
  {
    shards: make_shards(schedule, workers),
    estimated_jobs: jobs
    .filter(job => job.duration_ms is None)
    .map(job => job.id),
    makespan_ms: makespan,
    lower_bound_ms: lower_bound,
    within_budget: request.budget_ms.map(budget => makespan <= budget),
  }
}