-
Notifications
You must be signed in to change notification settings - Fork 87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Multiple winners in autopilot #2996
Merged
Merged
Changes from 12 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
00fb103
Add configuration for multiple winners
sunce86 2c92014
Merge branch 'main' into add-config-for-multiple-winners
sunce86 653ff47
Merge branch 'main' into add-config-for-multiple-winners
sunce86 ade37ba
Merge branch 'main' into add-config-for-multiple-winners
sunce86 348fd2c
multiple winners in autopilot runloop
sunce86 6ce3618
fix shadow
sunce86 7e7b9d9
self cr
sunce86 54b20a3
remove clone
sunce86 83f2b2b
remove clone 2
sunce86 90a743e
fix saving of solver competition table
sunce86 7bc7c92
Merge branch 'main' into add-config-for-multiple-winners
sunce86 561cec2
fix reference score
sunce86 db4e869
fix comments
sunce86 147e02a
Merge branch 'main' into add-config-for-multiple-winners
sunce86 ca768bc
flat map
sunce86 a9bfa4c
small refactor
sunce86 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -35,7 +35,7 @@ use { | |
rand::seq::SliceRandom, | ||
shared::token_list::AutoUpdatingTokenList, | ||
std::{ | ||
collections::{HashMap, HashSet}, | ||
collections::{HashMap, HashSet, VecDeque}, | ||
sync::Arc, | ||
time::{Duration, Instant}, | ||
}, | ||
|
@@ -52,6 +52,7 @@ pub struct Config { | |
/// allowed to start before it has to re-synchronize to the blockchain | ||
/// by waiting for the next block to appear. | ||
pub max_run_loop_delay: Duration, | ||
pub max_winners_per_auction: usize, | ||
} | ||
|
||
pub struct RunLoop { | ||
|
@@ -83,6 +84,13 @@ impl RunLoop { | |
liveness: Arc<Liveness>, | ||
maintenance: Arc<Maintenance>, | ||
) -> Self { | ||
// Added to make sure no more than one winner is activated by accident | ||
// Supposed to be removed after the implementation of "multiple winners per | ||
// auction" is done | ||
assert_eq!( | ||
config.max_winners_per_auction, 1, | ||
"only one winner is supported" | ||
); | ||
Self { | ||
config, | ||
eth, | ||
|
@@ -232,35 +240,36 @@ impl RunLoop { | |
let auction = self.remove_in_flight_orders(auction).await; | ||
|
||
let solutions = self.competition(&auction).await; | ||
if solutions.is_empty() { | ||
tracing::info!("no solutions for auction"); | ||
let winners = self.select_winners(&solutions); | ||
m-lord-renkse marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if winners.is_empty() { | ||
tracing::info!("no winners for auction"); | ||
return; | ||
} | ||
|
||
let competition_simulation_block = self.eth.current_block().borrow().number; | ||
let block_deadline = competition_simulation_block + self.config.submission_deadline; | ||
|
||
// Post-processing should not be executed asynchronously since it includes steps | ||
// of storing all the competition/auction-related data to the DB. | ||
if let Err(err) = self | ||
.post_processing( | ||
&auction, | ||
competition_simulation_block, | ||
// TODO: Support multiple winners | ||
// https://github.com/cowprotocol/services/issues/3021 | ||
&winners.first().expect("must exist").solution, | ||
&solutions, | ||
block_deadline, | ||
) | ||
.await | ||
{ | ||
tracing::error!(?err, "failed to post-process competition"); | ||
return; | ||
} | ||
|
||
// TODO: Keep going with other solutions until some deadline. | ||
if let Some(Participant { driver, solution }) = solutions.last() { | ||
for Participant { driver, solution } in winners { | ||
tracing::info!(driver = %driver.name, solution = %solution.id(), "winner"); | ||
m-lord-renkse marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
let block_deadline = competition_simulation_block + self.config.submission_deadline; | ||
|
||
// Post-processing should not be executed asynchronously since it includes steps | ||
// of storing all the competition/auction-related data to the DB. | ||
if let Err(err) = self | ||
.post_processing( | ||
&auction, | ||
competition_simulation_block, | ||
solution, | ||
&solutions, | ||
block_deadline, | ||
) | ||
.await | ||
{ | ||
tracing::error!(?err, "failed to post-process competition"); | ||
return; | ||
} | ||
|
||
self.start_settlement_execution( | ||
auction.id, | ||
single_run_start, | ||
|
@@ -368,15 +377,15 @@ impl RunLoop { | |
auction: &domain::Auction, | ||
competition_simulation_block: u64, | ||
winning_solution: &competition::Solution, | ||
solutions: &[Participant], | ||
solutions: &VecDeque<Participant>, | ||
block_deadline: u64, | ||
) -> Result<()> { | ||
let start = Instant::now(); | ||
let winner = winning_solution.solver().into(); | ||
let winning_score = winning_solution.score().get().0; | ||
let reference_score = solutions | ||
.iter() | ||
.nth_back(1) | ||
// todo multiple winners per auction | ||
.get(1) | ||
sunce86 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.map(|participant| participant.solution.score().get().0) | ||
.unwrap_or_default(); | ||
let participants = solutions | ||
|
@@ -420,6 +429,8 @@ impl RunLoop { | |
}, | ||
solutions: solutions | ||
.iter() | ||
// reverse as solver competition table is sorted from worst to best, so we need to keep the ordering for backwards compatibility | ||
.rev() | ||
.enumerate() | ||
.map(|(index, participant)| SolverSettlement { | ||
solver: participant.driver.name.clone(), | ||
|
@@ -483,8 +494,8 @@ impl RunLoop { | |
} | ||
|
||
/// Runs the solver competition, making all configured drivers participate. | ||
/// Returns all fair solutions sorted by their score (worst to best). | ||
async fn competition(&self, auction: &domain::Auction) -> Vec<Participant> { | ||
/// Returns all fair solutions sorted by their score (best to worst). | ||
async fn competition(&self, auction: &domain::Auction) -> VecDeque<Participant> { | ||
let request = solve::Request::new( | ||
auction, | ||
&self.market_makable_token_list.all(), | ||
|
@@ -508,11 +519,14 @@ impl RunLoop { | |
|
||
// Shuffle so that sorting randomly splits ties. | ||
solutions.shuffle(&mut rand::thread_rng()); | ||
solutions.sort_unstable_by_key(|participant| participant.solution.score().get().0); | ||
solutions.sort_unstable_by_key(|participant| { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems like shuffling and sorting by score would also fit into the shared function to pick a winner. |
||
std::cmp::Reverse(participant.solution.score().get().0) | ||
}); | ||
sunce86 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Make sure the winning solution is fair. | ||
while !Self::is_solution_fair(solutions.last(), &solutions, auction) { | ||
let unfair_solution = solutions.pop().expect("must exist"); | ||
let mut solutions = solutions.into_iter().collect::<VecDeque<_>>(); | ||
while !Self::is_solution_fair(solutions.front(), &solutions, auction) { | ||
let unfair_solution = solutions.pop_front().expect("must exist"); | ||
tracing::warn!( | ||
invalidated = unfair_solution.driver.name, | ||
"fairness check invalidated of solution" | ||
|
@@ -523,10 +537,39 @@ impl RunLoop { | |
solutions | ||
} | ||
|
||
/// Chooses the winners from the given participants. | ||
/// | ||
/// Participants are already sorted by their score (best to worst). | ||
/// | ||
/// Winners are selected one by one, starting from the best solution, | ||
/// until `max_winners_per_auction` is hit. The solution can become winner | ||
/// if it swaps tokens that are not yet swapped by any other already | ||
/// selected winner. | ||
fn select_winners<'a>(&self, participants: &'a VecDeque<Participant>) -> Vec<&'a Participant> { | ||
sunce86 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let mut winners = Vec::new(); | ||
let mut already_swapped_tokens = HashSet::new(); | ||
for participant in participants.iter() { | ||
let swapped_tokens = participant | ||
sunce86 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.solution | ||
.orders() | ||
.iter() | ||
.map(|(_, order)| (order.sell.token, order.buy.token)) | ||
.collect::<HashSet<_>>(); | ||
sunce86 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if swapped_tokens.is_disjoint(&already_swapped_tokens) { | ||
sunce86 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
winners.push(participant); | ||
already_swapped_tokens.extend(swapped_tokens); | ||
if winners.len() >= self.config.max_winners_per_auction { | ||
break; | ||
} | ||
} | ||
} | ||
winners | ||
} | ||
|
||
/// Records metrics, order events and logs for the given solutions. | ||
/// Expects the winning solution to be the last in the list. | ||
fn report_on_solutions(&self, solutions: &[Participant], auction: &domain::Auction) { | ||
let Some(winner) = solutions.last() else { | ||
/// Expects the winning solution to be the first in the list. | ||
fn report_on_solutions(&self, solutions: &VecDeque<Participant>, auction: &domain::Auction) { | ||
let Some(winner) = solutions.front() else { | ||
// no solutions means nothing to report | ||
return; | ||
}; | ||
|
@@ -545,7 +588,7 @@ impl RunLoop { | |
.flat_map(|solution| solution.solution.order_ids().copied()) | ||
.collect(); | ||
let winning_orders: HashSet<_> = solutions | ||
.last() | ||
.front() | ||
.into_iter() | ||
.flat_map(|solution| solution.solution.order_ids().copied()) | ||
.collect(); | ||
|
@@ -571,7 +614,7 @@ impl RunLoop { | |
/// Returns true if winning solution is fair or winner is None | ||
fn is_solution_fair( | ||
winner: Option<&Participant>, | ||
remaining: &Vec<Participant>, | ||
remaining: &VecDeque<Participant>, | ||
auction: &domain::Auction, | ||
) -> bool { | ||
let Some(winner) = winner else { return true }; | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Moved into a separate function because now it's called in two places (runloop and shadow)