Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 9 additions & 23 deletions rustuna_core/src/study.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub fn create_study<S: Storage + Send + Sync + 'static, T: Sampler + 'static>(
let study_id = storage.create_new_study(study_name, directions.clone())?.id;
let storage = Arc::new(RwLock::new(storage));
let sampler: Arc<dyn Sampler> = Arc::new(sampler);
let queue = Arc::new(RwLock::new(InMemoryTrialQueue::new()));
let queue = Arc::new(InMemoryTrialQueue::new());
Ok(Study::new(
study_id,
study_name.to_string(),
Expand All @@ -45,7 +45,7 @@ pub fn create_study_with_arc(
})?;
let study_id = guard.create_new_study(study_name, directions.clone())?.id;
drop(guard);
let queue = Arc::new(RwLock::new(InMemoryTrialQueue::new()));
let queue = Arc::new(InMemoryTrialQueue::new());
Ok(Study::new(
study_id,
study_name.to_string(),
Expand All @@ -70,7 +70,7 @@ pub struct Study {
pub directions: Vec<Direction>,
pub storage: Arc<RwLock<dyn Storage>>,
pub sampler: Arc<dyn Sampler>,
pub queue: Arc<RwLock<dyn TrialQueue>>,
pub queue: Arc<dyn TrialQueue>,
}
impl Study {
/// Constructs a study from fully initialized components.
Expand All @@ -80,7 +80,7 @@ impl Study {
directions: Vec<Direction>,
storage: Arc<RwLock<dyn Storage>>,
sampler: Arc<dyn Sampler>,
queue: Arc<RwLock<dyn TrialQueue>>,
queue: Arc<dyn TrialQueue>,
) -> Self {
Study {
id,
Expand Down Expand Up @@ -108,7 +108,7 @@ impl Study {
let name = study.name.clone();
let directions = study.directions.clone();
drop(guard);
let queue = Arc::new(RwLock::new(InMemoryTrialQueue::new()));
let queue = Arc::new(InMemoryTrialQueue::new());
Ok(Study::new(id, name, directions, storage, sampler, queue))
}

Expand All @@ -132,7 +132,7 @@ impl Study {
let study_id = study.id;
let directions = study.directions.clone();
drop(guard);
let queue = Arc::new(RwLock::new(InMemoryTrialQueue::new()));
let queue = Arc::new(InMemoryTrialQueue::new());
Ok(Study::new(
study_id, name, directions, storage, sampler, queue,
))
Expand All @@ -141,13 +141,7 @@ impl Study {
/// Creates or dequeues the next trial to evaluate.
pub fn ask(&self) -> Result<Trial> {
let queued_trial_id = {
let mut queue_guard = self.queue.write().map_err(|e| {
Error::with_reason(
ErrorKind::Unexpected,
format!("Failed to acquire a queue guard: {e}"),
)
})?;
match queue_guard.dequeue() {
match self.queue.dequeue() {
Ok(trial_id) => Some(trial_id),
Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => None,
Err(error) => return Err(error),
Expand All @@ -167,8 +161,7 @@ impl Study {
Ok(trial) => trial,
Err(e) => {
// Push the trial_id back to the queue on storage error
let mut queue_guard = self.queue.write().expect("queue lock poisoned");
if let Err(queue_err) = queue_guard.enqueue(trial_id) {
if let Err(queue_err) = self.queue.enqueue(trial_id) {
return Err(Error::with_reason(
ErrorKind::Unexpected,
format!(
Expand Down Expand Up @@ -408,14 +401,7 @@ impl Study {
let trial_id = trial.id;
drop(guard);

let mut queue_guard = self.queue.write().map_err(|e| {
Error::with_reason(
ErrorKind::Unexpected,
format!("Failed to acquire a queue guard: {e}"),
)
})?;
queue_guard.enqueue(trial_id)?;

self.queue.enqueue(trial_id)?;
Ok(())
}
}
Expand Down
23 changes: 13 additions & 10 deletions rustuna_core/src/trial_queue.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::collections::VecDeque;
use std::sync::Mutex;

use crate::{Error, ErrorKind, Result};

Expand All @@ -8,34 +9,36 @@ use crate::{Error, ErrorKind, Result};
/// not pay coordination overhead on every trial creation.
pub trait TrialQueue: Send + Sync {
/// Pushes a trial ID into the queue.
fn enqueue(&mut self, trial_id: u32) -> Result<()>;
fn enqueue(&self, trial_id: u32) -> Result<()>;
/// Pops the next queued trial ID.
fn dequeue(&mut self) -> Result<u32>;
fn dequeue(&self) -> Result<u32>;
}

/// In-memory queue implementation used by default.
#[derive(Default)]
pub struct InMemoryTrialQueue {
queue: VecDeque<u32>,
queue: Mutex<VecDeque<u32>>,
}

impl InMemoryTrialQueue {
/// Creates an empty queue.
pub fn new() -> Self {
Self {
queue: VecDeque::new(),
queue: Mutex::new(VecDeque::new()),
}
}
}

impl TrialQueue for InMemoryTrialQueue {
fn enqueue(&mut self, trial_id: u32) -> Result<()> {
self.queue.push_back(trial_id);
fn enqueue(&self, trial_id: u32) -> Result<()> {
let mut guard = self.queue.lock().expect("queue guard poisoned");
guard.push_back(trial_id);
Ok(())
}

fn dequeue(&mut self) -> Result<u32> {
self.queue
fn dequeue(&self) -> Result<u32> {
let mut guard = self.queue.lock().expect("queue guard poisoned");
guard
.pop_front()
.ok_or_else(|| Error::new(ErrorKind::TrialQueueEmpty))
}
Expand All @@ -47,7 +50,7 @@ mod tests {

#[test]
fn test_enqueue_and_dequeue() {
let mut queue = InMemoryTrialQueue::new();
let queue = InMemoryTrialQueue::new();

assert!(queue.enqueue(1).is_ok());
assert!(queue.enqueue(2).is_ok());
Expand All @@ -60,7 +63,7 @@ mod tests {

#[test]
fn test_dequeue_empty_queue() {
let mut queue = InMemoryTrialQueue::new();
let queue = InMemoryTrialQueue::new();
assert!(queue.dequeue().is_err());
}
}
7 changes: 3 additions & 4 deletions rustuna_pyo3/src/study.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use crate::trial_queue::to_rust::ToRustTrialQueue;

type SharedStorage = Arc<RwLock<dyn Storage>>;
type SharedSampler = Arc<dyn Sampler>;
type SharedTrialQueue = Arc<RwLock<dyn rustuna_core::trial_queue::TrialQueue>>;
type SharedTrialQueue = Arc<dyn rustuna_core::trial_queue::TrialQueue>;

mod py_exceptions {
pyo3::import_exception!(rustuna.exceptions, TrialPruned);
Expand Down Expand Up @@ -173,9 +173,8 @@ fn into_trial_queue_pyobj(
trial_queue.clone_ref(py),
))
} else {
let queue: SharedTrialQueue = Arc::new(RwLock::new(ToRustTrialQueue::new(
trial_queue.clone_ref(py),
)));
let queue: SharedTrialQueue =
Arc::new(ToRustTrialQueue::new(trial_queue.clone_ref(py)));
Ok((queue, trial_queue.clone_ref(py)))
}
}
Expand Down
26 changes: 8 additions & 18 deletions rustuna_pyo3/src/trial_queue/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ use pyo3::prelude::*;
use rustuna_core::trial_queue::TrialQueue;
use rustuna_core::ErrorKind;
use rustuna_storage::directory_queue::DirectoryTrialQueue;
use std::sync::{Arc, RwLock};
use std::sync::Arc;

use crate::exception::err_to_exceptions;

#[derive(Clone)]
#[pyclass(name = "DirectoryTrialQueue", from_py_object)]
#[pyo3(module = "rustuna")]
pub struct PyDirectoryTrialQueue {
pub queue: Arc<RwLock<DirectoryTrialQueue>>,
pub queue: Arc<DirectoryTrialQueue>,
}

#[pymethods]
Expand All @@ -27,29 +27,19 @@ impl PyDirectoryTrialQueue {
))
})?;
Ok(Self {
queue: Arc::new(RwLock::new(queue)),
queue: Arc::new(queue),
})
}

fn enqueue(&self, py: Python<'_>, trial_id: u32) -> PyResult<()> {
py.detach(|| {
let mut guard = self.queue.write().map_err(|error| {
PyRuntimeError::new_err(format!("Failed to acquire trial queue lock: {error}"))
})?;
guard.enqueue(trial_id).map_err(err_to_exceptions)
})
py.detach(|| self.queue.enqueue(trial_id).map_err(err_to_exceptions))
}

fn dequeue(&self, py: Python<'_>) -> PyResult<Option<u32>> {
py.detach(|| {
let mut guard = self.queue.write().map_err(|error| {
PyRuntimeError::new_err(format!("Failed to acquire trial queue lock: {error}"))
})?;
match guard.dequeue() {
Ok(trial_id) => Ok(Some(trial_id)),
Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => Ok(None),
Err(error) => Err(err_to_exceptions(error)),
}
py.detach(|| match self.queue.dequeue() {
Ok(trial_id) => Ok(Some(trial_id)),
Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => Ok(None),
Err(error) => Err(err_to_exceptions(error)),
})
}
}
27 changes: 8 additions & 19 deletions rustuna_pyo3/src/trial_queue/inmemory.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use rustuna_core::trial_queue::{InMemoryTrialQueue, TrialQueue};
use rustuna_core::ErrorKind;
use std::sync::{Arc, RwLock};
use std::sync::Arc;

use crate::exception::err_to_exceptions;

#[derive(Clone)]
#[pyclass(name = "InMemoryTrialQueue", from_py_object)]
#[pyo3(module = "rustuna")]
pub struct PyInMemoryTrialQueue {
pub queue: Arc<RwLock<InMemoryTrialQueue>>,
pub queue: Arc<InMemoryTrialQueue>,
}

impl Default for PyInMemoryTrialQueue {
Expand All @@ -22,7 +21,7 @@ impl Default for PyInMemoryTrialQueue {
impl PyInMemoryTrialQueue {
pub fn new() -> Self {
Self {
queue: Arc::new(RwLock::new(InMemoryTrialQueue::new())),
queue: Arc::new(InMemoryTrialQueue::new()),
}
}
}
Expand All @@ -35,24 +34,14 @@ impl PyInMemoryTrialQueue {
}

fn enqueue(&self, py: Python<'_>, trial_id: u32) -> PyResult<()> {
py.detach(|| {
let mut guard = self.queue.write().map_err(|error| {
PyRuntimeError::new_err(format!("Failed to acquire trial queue lock: {error}"))
})?;
guard.enqueue(trial_id).map_err(err_to_exceptions)
})
py.detach(|| self.queue.enqueue(trial_id).map_err(err_to_exceptions))
}

fn dequeue(&self, py: Python<'_>) -> PyResult<Option<u32>> {
py.detach(|| {
let mut guard = self.queue.write().map_err(|error| {
PyRuntimeError::new_err(format!("Failed to acquire trial queue lock: {error}"))
})?;
match guard.dequeue() {
Ok(trial_id) => Ok(Some(trial_id)),
Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => Ok(None),
Err(error) => Err(err_to_exceptions(error)),
}
py.detach(|| match self.queue.dequeue() {
Ok(trial_id) => Ok(Some(trial_id)),
Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => Ok(None),
Err(error) => Err(err_to_exceptions(error)),
})
}
}
26 changes: 8 additions & 18 deletions rustuna_pyo3/src/trial_queue/sqlite3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ use pyo3::prelude::*;
use rustuna_core::trial_queue::TrialQueue;
use rustuna_core::ErrorKind;
use rustuna_storage::sqlite3_queue::SQLite3TrialQueue;
use std::sync::{Arc, RwLock};
use std::sync::Arc;

use crate::exception::err_to_exceptions;

#[derive(Clone)]
#[pyclass(name = "SQLite3TrialQueue", from_py_object)]
#[pyo3(module = "rustuna")]
pub struct PySQLite3TrialQueue {
pub queue: Arc<RwLock<SQLite3TrialQueue>>,
pub queue: Arc<SQLite3TrialQueue>,
}

#[pymethods]
Expand All @@ -27,29 +27,19 @@ impl PySQLite3TrialQueue {
))
})?;
Ok(Self {
queue: Arc::new(RwLock::new(queue)),
queue: Arc::new(queue),
})
}

fn enqueue(&self, py: Python<'_>, trial_id: u32) -> PyResult<()> {
py.detach(|| {
let mut guard = self.queue.write().map_err(|error| {
PyRuntimeError::new_err(format!("Failed to acquire trial queue lock: {error}"))
})?;
guard.enqueue(trial_id).map_err(err_to_exceptions)
})
py.detach(|| self.queue.enqueue(trial_id).map_err(err_to_exceptions))
}

fn dequeue(&self, py: Python<'_>) -> PyResult<Option<u32>> {
py.detach(|| {
let mut guard = self.queue.write().map_err(|error| {
PyRuntimeError::new_err(format!("Failed to acquire trial queue lock: {error}"))
})?;
match guard.dequeue() {
Ok(trial_id) => Ok(Some(trial_id)),
Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => Ok(None),
Err(error) => Err(err_to_exceptions(error)),
}
py.detach(|| match self.queue.dequeue() {
Ok(trial_id) => Ok(Some(trial_id)),
Err(error) if matches!(error.kind, ErrorKind::TrialQueueEmpty) => Ok(None),
Err(error) => Err(err_to_exceptions(error)),
})
}
}
4 changes: 2 additions & 2 deletions rustuna_pyo3/src/trial_queue/to_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl ToRustTrialQueue {
}

impl TrialQueue for ToRustTrialQueue {
fn enqueue(&mut self, trial_id: u32) -> Result<()> {
fn enqueue(&self, trial_id: u32) -> Result<()> {
Python::attach(|py| {
self.obj
.call_method1(py, "enqueue", (trial_id,))
Expand All @@ -34,7 +34,7 @@ impl TrialQueue for ToRustTrialQueue {
})
}

fn dequeue(&mut self) -> Result<u32> {
fn dequeue(&self) -> Result<u32> {
Python::attach(|py| {
let trial_id = self
.obj
Expand Down
Loading
Loading