use proptest::collection::vec;
use proptest::prelude::*;
use task_allocation::cbba::{Agent, Replan};
use task_allocation::centralized::optimal;
use task_allocation::sim::{Clusters, Network, Partition, Simulation, Topology};
use task_allocation::{AgentId, Assignment, TaskId, Valuation};
use crate::bundle::gains_replay;
use crate::support::{self, Instance, instance_sized, instance_with, is_greedy_outcome};
pub const MAX_TEAM: usize = 6;
pub const SETTLE_TICKS: u64 = 2_000;
fn partition(agents: usize) -> impl Strategy<Value = Partition> {
(0_u64..40, 1_u64..60, vec(0_usize..3, agents)).prop_map(|(from, length, groups)| Partition {
from,
until: from + length,
groups,
})
}
pub fn topology(agents: usize) -> impl Strategy<Value = Topology> {
let parents = (1..agents.max(2)).map(|agent| 0..agent).collect::<Vec<_>>();
let tree = parents.prop_map(|parents| {
parents
.into_iter()
.enumerate()
.map(|(index, parent)| (AgentId(parent), AgentId(index + 1)))
.collect::<Vec<_>>()
});
let extra = vec((0..agents, 0..agents), 0..agents);
let sparse = (tree, extra).prop_map(|(mut links, extra)| {
links.extend(extra.into_iter().map(|(a, b)| (AgentId(a), AgentId(b))));
Topology::Links(links)
});
prop_oneof![Just(Topology::Complete), sparse]
}
pub fn network(agents: usize) -> impl Strategy<Value = Network> {
(
(any::<u64>(), 0_u64..=5, 0_u16..=500),
topology(agents),
vec(partition(agents), 0..=3),
any::<bool>(),
proptest::option::of(clusters(agents)),
)
.prop_map(
|((seed, max_delay, loss_per_mille), topology, partitions, collisions, clusters)| {
Network {
seed,
max_delay,
loss_per_mille,
topology,
partitions,
collisions,
clusters,
}
},
)
}
fn clusters(agents: usize) -> impl Strategy<Value = Clusters> {
(vec(0_usize..3, agents), 1_u64..=8).prop_map(|(groups, period)| Clusters { groups, period })
}
fn scenario() -> impl Strategy<Value = (Instance, Network)> {
with_network(instance_with(MAX_TEAM))
}
fn with_network(
instances: impl Strategy<Value = Instance>,
) -> impl Strategy<Value = (Instance, Network)> {
instances.prop_flat_map(|instance| {
let agents = instance.agents.len();
(Just(instance), network(agents))
})
}
fn team(instance: &Instance, replan: Replan) -> Vec<Agent<support::Agent>> {
let size = instance.agents.len();
instance
.agents
.iter()
.cloned()
.enumerate()
.map(|(id, valuation)| {
Agent::new(
AgentId(id),
size,
instance.tasks,
instance.capacity,
valuation,
)
.with_replan(replan)
})
.collect()
}
fn run(instance: &Instance, network: Network) -> Option<Simulation<Agent<support::Agent>>> {
run_with(instance, network, Replan::Keep)
}
fn run_with(
instance: &Instance,
network: Network,
replan: Replan,
) -> Option<Simulation<Agent<support::Agent>>> {
let healed = network
.partitions
.iter()
.map(|partition| partition.until)
.max()
.unwrap_or(0);
let mut simulation = Simulation::new(team(instance, replan), network);
simulation.run_until_settled(healed + SETTLE_TICKS)?;
Some(simulation)
}
fn agrees_with(
simulation: &Simulation<Agent<support::Agent>>,
assignment: &Assignment,
) -> Result<(), TestCaseError> {
for agent in simulation.agents() {
for (task, winner) in agent.winners().enumerate() {
let task = TaskId(task);
prop_assert_eq!(winner, assignment.holder(task));
let recorded = winner.and_then(|holder| {
assignment
.bundle(holder)
.entries()
.find(|(held, _)| **held == task)
.map(|(_, gain)| gain)
});
prop_assert_eq!(agent.winning_bid(task), recorded.unwrap_or(0));
}
}
Ok(())
}
fn nobody_can_outbid(
simulation: &Simulation<Agent<support::Agent>>,
instance: &Instance,
) -> Result<(), TestCaseError> {
for agent in simulation.agents() {
let bundle = agent.bundle();
if bundle.len() >= instance.capacity {
continue;
}
for task in (0..instance.tasks)
.map(TaskId)
.filter(|task| !bundle.contains(task))
{
let Some(insertion) = agent.valuation().best_insertion(bundle.path(), &task) else {
continue;
};
let winning = agent.winning_bid(task);
let beats = match agent.winner(task) {
None => insertion.gain > 0,
Some(winner) => {
insertion.gain > winning || (insertion.gain == winning && agent.id() < winner)
}
};
prop_assert!(
!beats,
"{:?} could outbid {:?} on {:?}",
agent.id(),
agent.winner(task),
task
);
}
}
Ok(())
}
pub fn stable(
simulation: &Simulation<Agent<support::Agent>>,
instance: &Instance,
) -> Result<(), TestCaseError> {
let assignment = simulation.assignment();
prop_assert!(assignment.is_conflict_free());
agrees_with(simulation, &assignment)?;
nobody_can_outbid(simulation, instance)?;
for (agent, valuation) in instance.agents.iter().enumerate() {
prop_assert!(assignment.bundle(AgentId(agent)).len() <= instance.capacity);
gains_replay(valuation, assignment.bundle(AgentId(agent)))?;
}
Ok(())
}
fn stays_settled(simulation: &mut Simulation<Agent<support::Agent>>) -> Result<(), TestCaseError> {
let assignment = simulation.assignment();
for _ in 0..20 {
simulation.step();
prop_assert!(simulation.is_settled());
}
prop_assert_eq!(simulation.assignment(), assignment);
Ok(())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn settles_on_a_stable_assignment((instance, network) in scenario()) {
let Some(simulation) = run(&instance, network) else {
return Err(TestCaseError::fail("did not settle"));
};
let assignment = simulation.assignment();
prop_assert!(assignment.is_conflict_free());
agrees_with(&simulation, &assignment)?;
nobody_can_outbid(&simulation, &instance)?;
for (agent, valuation) in instance.agents.iter().enumerate() {
prop_assert!(assignment.bundle(AgentId(agent)).len() <= instance.capacity);
gains_replay(valuation, assignment.bundle(AgentId(agent)))?;
}
let best = optimal(&instance.agents, instance.tasks, instance.capacity);
prop_assert!(assignment.value() <= best.value());
}
#[test]
fn larger_instances_settle((instance, network) in with_network(instance_sized(MAX_TEAM, 14))) {
let Some(simulation) = run(&instance, network) else {
return Err(TestCaseError::fail("did not settle"));
};
let assignment = simulation.assignment();
prop_assert!(assignment.is_conflict_free());
agrees_with(&simulation, &assignment)?;
nobody_can_outbid(&simulation, &instance)?;
for (agent, valuation) in instance.agents.iter().enumerate() {
gains_replay(valuation, assignment.bundle(AgentId(agent)))?;
}
}
#[test]
fn full_replan_reaches_a_greedy_outcome((instance, network) in scenario()) {
let Some(mut simulation) = run_with(&instance, network, Replan::Full) else {
return Err(TestCaseError::fail("did not settle"));
};
stable(&simulation, &instance)?;
stays_settled(&mut simulation)?;
let holders = holders(&simulation.assignment(), instance.tasks);
prop_assert!(is_greedy_outcome(&instance, &holders), "{:?}", holders);
}
#[test]
fn partial_replan_settles((instance, network) in scenario(), last in 1_usize..4) {
let Some(mut simulation) = run_with(&instance, network, Replan::Last(last)) else {
return Err(TestCaseError::fail("did not settle"));
};
stable(&simulation, &instance)?;
stays_settled(&mut simulation)?;
}
#[test]
fn budgeted_runs_settle((instance, network) in scenario(), budget in 1_usize..3) {
let team = instance.agents.len();
let agents = instance
.agents
.iter()
.cloned()
.enumerate()
.map(|(id, valuation)| {
Agent::new(AgentId(id), team, instance.tasks, instance.capacity, valuation)
.with_bundle_budget(budget)
})
.collect();
let healed = network.partitions.iter().map(|partition| partition.until).max().unwrap_or(0);
let mut simulation = Simulation::new(agents, network);
let Some(_) = simulation.run_until_settled(healed + SETTLE_TICKS) else {
return Err(TestCaseError::fail("did not settle"));
};
stable(&simulation, &instance)?;
stays_settled(&mut simulation)?;
}
#[test]
fn settled_teams_stay_settled((instance, network) in scenario()) {
let Some(mut simulation) = run(&instance, network) else {
return Err(TestCaseError::fail("did not settle"));
};
let assignment = simulation.assignment();
for _ in 0..20 {
simulation.step();
prop_assert!(simulation.is_settled());
}
prop_assert_eq!(simulation.assignment(), assignment);
}
}
fn holders(assignment: &Assignment, tasks: usize) -> Vec<Option<AgentId>> {
(0..tasks)
.map(|task| assignment.holder(TaskId(task)))
.collect()
}
#[test]
fn blocked_slot_differs_from_greedy() {
let instance = blocked_slot_instance();
let simulation = run(&instance, Network::default()).expect("settles");
let greedy = task_allocation::centralized::sequential_greedy(&instance.agents, 5, 4);
let cbba = simulation.assignment();
let (a, b) = (Some(AgentId(0)), Some(AgentId(1)));
assert_eq!(holders(&greedy, 5), [b, b, a, None, a]);
assert_eq!(holders(&cbba, 5), [b, a, b, None, a]);
assert_eq!((greedy.value(), cbba.value()), (131, 129));
}
#[test]
fn tied_gains_can_differ_from_greedy() {
let site = |position, duration, deadline| support::Site {
position,
duration,
deadline,
};
let instance = Instance {
agents: vec![
support::Agent::Courier(task_allocation::BestInsertion(support::Courier {
start: 27,
sites: vec![
site(36, 12, 108),
site(83, 11, 66),
site(28, 19, 20),
site(1, 15, 263),
site(34, 13, 108),
site(74, 7, 93),
],
rewards: vec![25, 29, 27, 25, 26, 3],
})),
support::Agent::Coverage(support::Coverage {
covers: vec![76, 46, 70, 124, 12, 79],
weights: vec![16, 19, 13, 14, 15, 11, 7, 5],
allowed: 2_458_217_047,
}),
support::Agent::Coverage(support::Coverage {
covers: vec![198, 43, 46, 145, 40, 155],
weights: vec![8, 9, 3, 10, 1, 18, 13, 17],
allowed: 3_524_159_223,
}),
],
tasks: 6,
capacity: 6,
};
let network = Network {
seed: 1_086_238_513_920_705_783,
loss_per_mille: 129,
..Network::default()
};
let simulation = run(&instance, network).expect("settles");
let greedy = task_allocation::centralized::sequential_greedy(&instance.agents, 6, 6);
let cbba = simulation.assignment();
assert_eq!(greedy.holder(TaskId(0)), Some(AgentId(0)));
assert_eq!(cbba.holder(TaskId(0)), Some(AgentId(2)));
assert_eq!(holders(&greedy, 6)[1..], holders(&cbba, 6)[1..]);
}
#[test]
fn full_replan_frees_the_blocked_slot() {
let instance = blocked_slot_instance();
let simulation = run_with(&instance, Network::default(), Replan::Full).expect("settles");
let greedy = task_allocation::centralized::sequential_greedy(&instance.agents, 5, 4);
assert_eq!(holders(&simulation.assignment(), 5), holders(&greedy, 5));
assert_eq!(simulation.assignment().value(), 131);
}
fn blocked_slot_instance() -> Instance {
Instance {
agents: vec![
support::Agent::Coverage(support::Coverage {
covers: vec![81, 172, 156, 182, 141],
weights: vec![15, 14, 3, 8, 11, 10, 14, 12],
allowed: 2_422_693_623,
}),
support::Agent::Coverage(support::Coverage {
covers: vec![107, 198, 184, 161, 28],
weights: vec![18, 19, 10, 1, 9, 8, 15, 11],
allowed: 2_274_905_959,
}),
],
tasks: 5,
capacity: 4,
}
}
fn connected_without(topology: &Topology, agents: usize, leaving: AgentId) -> bool {
let Topology::Links(links) = topology else {
return true;
};
let start = (0..agents).find(|&agent| agent != leaving.index());
let Some(start) = start else {
return true;
};
let mut reached = vec![false; agents];
reached[start] = true;
let mut frontier = vec![start];
while let Some(agent) = frontier.pop() {
for &(a, b) in links {
let next = if a.index() == agent {
b.index()
} else if b.index() == agent {
a.index()
} else {
continue;
};
if next < agents && next != leaving.index() && !reached[next] {
reached[next] = true;
frontier.push(next);
}
}
}
(0..agents)
.filter(|&agent| agent != leaving.index())
.all(|agent| reached[agent])
}
fn grew_from(
before: &task_allocation::Bundle<TaskId>,
after: &task_allocation::Bundle<TaskId>,
) -> bool {
before.len() <= after.len()
&& before
.entries()
.zip(after.entries())
.all(|(old, new)| old == new)
}
fn stable_among_active(
simulation: &Simulation<Agent<support::Agent>>,
tasks: usize,
capacity: usize,
) -> Result<(), TestCaseError> {
let active: Vec<&Agent<support::Agent>> = simulation
.agents()
.iter()
.filter(|agent| !agent.has_left())
.collect();
let assignment = simulation.assignment();
prop_assert!(assignment.is_conflict_free());
for agent in &active {
prop_assert!(agent.is_consistent());
for task in (0..tasks).map(TaskId) {
let holder = assignment.holder(task);
prop_assert_eq!(agent.winner(task), holder);
let recorded = holder.and_then(|holder| {
assignment
.bundle(holder)
.entries()
.find(|(held, _)| **held == task)
.map(|(_, gain)| gain)
});
prop_assert_eq!(agent.winning_bid(task), recorded.unwrap_or(0));
}
let bundle = agent.bundle();
prop_assert!(
bundle.len() <= capacity,
"{:?} holds {} tasks",
agent.id(),
bundle.len()
);
gains_replay(agent.valuation(), bundle)?;
if bundle.len() == capacity {
continue;
}
for task in (0..tasks).map(TaskId).filter(|task| !bundle.contains(task)) {
let Some(insertion) = agent.valuation().best_insertion(bundle.path(), &task) else {
continue;
};
let winning = agent.winning_bid(task);
let beats = match agent.winner(task) {
None => insertion.gain > 0,
Some(winner) => {
insertion.gain > winning || (insertion.gain == winning && agent.id() < winner)
}
};
prop_assert!(!beats, "{:?} could outbid on {:?}", agent.id(), task);
}
}
Ok(())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn added_tasks_disturb_nothing_else((instance, network) in scenario()) {
prop_assume!(instance.tasks >= 2);
let team = instance.agents.len();
let agents = instance
.agents
.iter()
.cloned()
.enumerate()
.map(|(id, valuation)| Agent::new(AgentId(id), team, instance.tasks - 1, instance.capacity, valuation))
.collect();
let healed = network.partitions.iter().map(|partition| partition.until).max().unwrap_or(0);
let mut simulation = Simulation::new(agents, network);
prop_assert!(simulation.run_until_settled(healed + SETTLE_TICKS).is_some());
let before: Vec<_> = simulation.agents().iter().map(|agent| agent.bundle().clone()).collect();
for agent in simulation.agents_mut() {
prop_assert_eq!(agent.add_task(), TaskId(instance.tasks - 1));
}
prop_assert!(simulation.run_until_settled(SETTLE_TICKS).is_some(), "did not settle again");
stable_among_active(&simulation, instance.tasks, instance.capacity)?;
let mut changed = 0;
for (agent, old) in simulation.agents().iter().zip(&before) {
prop_assert!(grew_from(old, agent.bundle()), "{:?} lost tasks", agent.id());
changed += usize::from(agent.bundle() != old);
}
prop_assert!(changed <= 1, "{} plans changed", changed);
}
#[test]
fn departures_only_free_their_tasks((instance, network) in scenario(), leaving in 0_usize..MAX_TEAM) {
let leaving = AgentId(leaving % instance.agents.len());
prop_assume!(connected_without(&network.topology, instance.agents.len(), leaving));
let healed = network.partitions.iter().map(|partition| partition.until).max().unwrap_or(0);
let mut simulation = Simulation::new(team(&instance, Replan::Keep), network);
prop_assert!(simulation.run_until_settled(healed + SETTLE_TICKS).is_some());
let before: Vec<_> = simulation.agents().iter().map(|agent| agent.bundle().clone()).collect();
for agent in simulation.agents_mut() {
if agent.id() == leaving {
agent.leave();
} else {
agent.forget_agent(leaving);
}
}
prop_assert!(simulation.run_until_settled(SETTLE_TICKS).is_some(), "did not settle again");
stable_among_active(&simulation, instance.tasks, instance.capacity)?;
prop_assert!(simulation.agents()[leaving.index()].bundle().is_empty());
for (agent, old) in simulation.agents().iter().zip(&before).filter(|(agent, _)| agent.id() != leaving) {
prop_assert!(grew_from(old, agent.bundle()), "{:?} lost tasks", agent.id());
}
}
}