Skip to content

Commit

Permalink
add a default implementation for BanditCache
Browse files Browse the repository at this point in the history
  • Loading branch information
misaniwere committed Dec 11, 2024
1 parent 1e65010 commit c92a669
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions components/relevancy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ use rand_distr::{Beta, Distribution};
pub use db::RelevancyDb;
pub use error::{ApiResult, Error, RelevancyApiError, Result};
pub use interest::{Interest, InterestVector};
pub use ranker::score;
use parking_lot::Mutex;
pub use ranker::score;

use error_support::handle_error;

Expand Down Expand Up @@ -129,11 +129,7 @@ impl RelevancyStore {
/// database, creates a Beta distribution, and samples from it to estimate the arm's probability
/// of success. The arm with the highest sampled probability is selected and returned.
#[handle_error(Error)]
pub fn bandit_select(
&self,
bandit: String,
arms: &[String],
) -> ApiResult<String> {
pub fn bandit_select(&self, bandit: String, arms: &[String]) -> ApiResult<String> {
let mut cache = self.cache.lock();
let mut best_sample = f64::MIN;
let mut selected_arm = String::new();
Expand Down Expand Up @@ -167,7 +163,9 @@ impl RelevancyStore {
pub fn bandit_update(&self, bandit: String, arm: String, selected: bool) -> ApiResult<()> {
let mut cache = self.cache.lock();

cache.clear(&bandit, &arm).expect("failed to clear cached distribution");
cache
.clear(&bandit, &arm)
.expect("failed to clear cached distribution");

self.db
.read_write(|dao| dao.update_bandit_arm_data(&bandit, &arm, selected))?;
Expand All @@ -180,6 +178,12 @@ pub struct BanditCache {
cache: HashMap<(String, String), (usize, usize)>,
}

impl Default for BanditCache {
fn default() -> Self {
Self::new()
}
}

impl BanditCache {
/// Creates a new, empty `BanditCache`.
///
Expand Down Expand Up @@ -222,11 +226,7 @@ impl BanditCache {
///
/// This removes the cached values for the specified `bandit` and `arm` from the cache.
/// Use this method if the cached parameters are no longer valid or need to be refreshed.
pub fn clear(
&mut self,
bandit: &str,
arm: &str,
) -> Result<()> {
pub fn clear(&mut self, bandit: &str, arm: &str) -> Result<()> {
let key = (bandit.to_string(), arm.to_string());

self.cache.remove(&key);
Expand Down

0 comments on commit c92a669

Please sign in to comment.