Skip to content
Draft
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
124 changes: 70 additions & 54 deletions rustuna_core/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,15 +170,6 @@ pub trait Storage: Send + Sync {
}
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
/// Options for [`InMemoryStorage`].
pub struct InMemoryStorageOptions {
pub apply_discard: bool,
/// Representation of attribute values. The storage does not interpret the values; this
/// only tells the callers (e.g. the Python bindings) how to encode and decode them.
pub attr_format: AttrFormat,
}

/// In-memory storage implementation used by default in Rust code and tests.
///
/// This implementation keeps all studies, trials, and caches in process memory.
Expand All @@ -193,36 +184,76 @@ pub struct InMemoryStorage {
// Supports the state-counting API required when `discard_trials` removes trials.
// Storing only discarded trials' states avoids tracking state transitions and keeps this simple.
discarded_state_counts: HashMap<(u32, TrialState), u32>,
option: InMemoryStorageOptions,
apply_discard: bool,
attr_format: AttrFormat,
}
impl InMemoryStorage {
/// Creates an empty in-memory storage.
pub fn new() -> InMemoryStorage {
InMemoryStorage {
studies: vec![],
trials: HashMap::new(),
trial_id_number_map: TrialIdNumberHashMap::new(),
study_caches: HashMap::new(),
next_study_id: 0,
next_trial_id: 0,
discarded_state_counts: HashMap::new(),
option: InMemoryStorageOptions::default(),
/// Builder for [`InMemoryStorage`], following the API style of [`std::thread::Builder`].
///
/// Settings are configured by chaining setter methods and the storage is created with
/// [`InMemoryStorageBuilder::build`].
///
/// # Examples
///
/// ```
/// use rustuna_core::attr::AttrFormat;
/// use rustuna_core::storage::InMemoryStorageBuilder;
///
/// let storage = InMemoryStorageBuilder::new()
/// .apply_discard(true)
/// .attr_format(AttrFormat::Json)
/// .build();
/// # let _ = storage;
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct InMemoryStorageBuilder {
apply_discard: bool,
attr_format: AttrFormat,
}
impl InMemoryStorageBuilder {
/// Creates a builder with the default configuration.
pub fn new() -> Self {
Self::default()
}

/// Sets whether [`Storage::discard_trials`] removes trials from this storage.
///
/// When this is `false` (the default), discarding is a no-op. When this is `true`,
/// discarded trials are omitted from subsequent reads.
pub fn apply_discard(self, apply_discard: bool) -> Self {
Self {
apply_discard,
..self
}
}

/// Sets the representation of attribute values.
///
/// The storage does not interpret the values; this only tells the callers (e.g. the
/// Python bindings) how to encode and decode them. Defaults to [`AttrFormat::Plain`].
pub fn attr_format(self, attr_format: AttrFormat) -> Self {
Self {
attr_format,
..self
}
}

/// Creates an empty in-memory storage.
pub fn new_with_option(option: InMemoryStorageOptions) -> InMemoryStorage {
/// Builds the storage.
pub fn build(self) -> InMemoryStorage {
InMemoryStorage {
studies: vec![],
trials: HashMap::new(),
trial_id_number_map: TrialIdNumberHashMap::new(),
study_caches: HashMap::new(),
next_study_id: 0,
next_trial_id: 0,
discarded_state_counts: HashMap::new(),
option,
apply_discard: self.apply_discard,
attr_format: self.attr_format,
..InMemoryStorage::default()
}
}
}

impl InMemoryStorage {
/// Creates an empty in-memory storage with the default configuration.
///
/// Use [`InMemoryStorageBuilder`] to configure the storage.
pub fn new() -> InMemoryStorage {
InMemoryStorageBuilder::new().build()
}

pub fn insert_study_with_id(
&mut self,
Expand Down Expand Up @@ -530,7 +561,7 @@ impl Storage for InMemoryStorage {
param_name: &str,
labels: Vec<CategoryLabel>,
) -> Result<()> {
let attrs = category_labels_to_attrs(param_name, &labels, self.option.attr_format);
let attrs = category_labels_to_attrs(param_name, &labels, self.attr_format);
self.set_study_attrs(study_id, attrs, true)
}

Expand Down Expand Up @@ -635,7 +666,7 @@ impl Storage for InMemoryStorage {
}

fn discard_trials(&mut self, trial_ids: &[u32]) -> Result<()> {
if !self.option.apply_discard {
if !self.apply_discard {
return Ok(());
}
for trial_id in trial_ids {
Expand All @@ -660,11 +691,11 @@ impl Storage for InMemoryStorage {
}

fn may_omit_trials(&self) -> bool {
self.option.apply_discard
self.apply_discard
}

fn attr_format(&self) -> AttrFormat {
self.option.attr_format
self.attr_format
}
}

Expand All @@ -674,12 +705,6 @@ struct TrialIdNumberHashMap {
study_number_to_trial_id: HashMap<(u32, u32), u32>,
}
impl TrialIdNumberHashMap {
fn new() -> Self {
Self {
trial_id_to_study_number: HashMap::new(),
study_number_to_trial_id: HashMap::new(),
}
}
fn insert(&mut self, study_id: u32, trial_id: u32, trial_number: u32) {
self.trial_id_to_study_number
.insert(trial_id, (study_id, trial_number));
Expand Down Expand Up @@ -820,10 +845,7 @@ mod tests {

#[test]
fn delete_study_removes_discarded_trial_mappings() -> Result<()> {
let mut storage = InMemoryStorage::new_with_option(InMemoryStorageOptions {
apply_discard: true,
..Default::default()
});
let mut storage = InMemoryStorageBuilder::new().apply_discard(true).build();
let study_id = storage
.create_new_study("study", vec![Direction::Minimize])?
.id;
Expand Down Expand Up @@ -928,10 +950,7 @@ mod tests {

#[test]
fn discard_trials_omits_trials() -> Result<()> {
let mut storage = InMemoryStorage::new_with_option(InMemoryStorageOptions {
apply_discard: true,
..Default::default()
});
let mut storage = InMemoryStorageBuilder::new().apply_discard(true).build();
let study_id = storage
.create_new_study("study", vec![Direction::Minimize])?
.id;
Expand All @@ -952,10 +971,7 @@ mod tests {

#[test]
fn get_n_trials_counts_states() -> Result<()> {
let mut storage = InMemoryStorage::new_with_option(InMemoryStorageOptions {
apply_discard: true,
..Default::default()
});
let mut storage = InMemoryStorageBuilder::new().apply_discard(true).build();
let study_id = storage
.create_new_study("study", vec![Direction::Minimize])?
.id;
Expand Down
23 changes: 10 additions & 13 deletions rustuna_pyo3/src/storage/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::sync::{Arc, RwLock};
use pyo3::prelude::*;

use rustuna_core::attr::AttrFormat;
use rustuna_core::storage::{InMemoryStorage, InMemoryStorageOptions, Storage};
use rustuna_core::storage::{InMemoryStorageBuilder, Storage};

use crate::distribution::PyDistribution;
use crate::storage::binding::StorageBinding;
Expand All @@ -20,18 +20,18 @@ pub struct PyInMemoryStorage {
impl Default for PyInMemoryStorage {
/// The default storage of the Python API, which uses Optuna-compatible attributes.
fn default() -> Self {
Self::new(InMemoryStorageOptions {
attr_format: AttrFormat::Json,
..InMemoryStorageOptions::default()
})
Self::new(false)
}
}

impl PyInMemoryStorage {
pub fn new(option: InMemoryStorageOptions) -> Self {
let binding = StorageBinding::new(Arc::new(RwLock::new(InMemoryStorage::new_with_option(
option,
))));
/// Creates an in-memory storage that uses Optuna-compatible (JSON) attributes.
pub fn new(apply_discard: bool) -> Self {
let storage = InMemoryStorageBuilder::new()
.apply_discard(apply_discard)
.attr_format(AttrFormat::Json)
.build();
let binding = StorageBinding::new(Arc::new(RwLock::new(storage)));
PyInMemoryStorage { binding }
}

Expand All @@ -45,10 +45,7 @@ impl PyInMemoryStorage {
#[new]
#[pyo3(signature = (*, apply_discard = false))]
fn py_new(apply_discard: bool) -> Self {
PyInMemoryStorage::new(InMemoryStorageOptions {
apply_discard,
attr_format: AttrFormat::Json,
})
PyInMemoryStorage::new(apply_discard)
}

fn create_new_study(
Expand Down
17 changes: 8 additions & 9 deletions rustuna_pyo3/src/storage/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use pyo3::prelude::*;
use rustuna_core::attr::AttrFormat;
use rustuna_core::storage::Storage;
use rustuna_storage::journal::file::JournalFileBackend;
use rustuna_storage::journal::storage::{JournalStorage, JournalStorageOptions};
use rustuna_storage::journal::storage::JournalStorageBuilder;

use crate::distribution::PyDistribution;
use crate::storage::binding::StorageBinding;
Expand Down Expand Up @@ -34,14 +34,13 @@ impl PyJournalFileStorage {
let backend = JournalFileBackend::new(file_path, None).map_err(|e| {
PyRuntimeError::new_err(format!("Failed to create journal file: {e:?}"))
})?;
let storage = JournalStorage::new_with_options(
Box::new(backend),
JournalStorageOptions {
apply_discard,
attr_format: AttrFormat::Json,
},
)
.map_err(|e| PyRuntimeError::new_err(format!("Failed to create journal storage: {e:?}")))?;
let storage = JournalStorageBuilder::new(Box::new(backend))
.apply_discard(apply_discard)
.attr_format(AttrFormat::Json)
.build()
.map_err(|e| {
PyRuntimeError::new_err(format!("Failed to create journal storage: {e:?}"))
})?;
let binding = StorageBinding::new(Arc::new(RwLock::new(storage)));
Ok(PyJournalFileStorage { binding })
}
Expand Down
17 changes: 8 additions & 9 deletions rustuna_pyo3/src/storage/sqlite3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use pyo3::prelude::*;
use rustuna_core::attr::AttrFormat;
use rustuna_core::storage::Storage;
use rustuna_storage::cache::CachedStorage;
use rustuna_storage::sqlite3::{SQLite3Storage, SQLite3StorageOptions};
use rustuna_storage::sqlite3::SQLite3StorageBuilder;

use crate::distribution::PyDistribution;
use crate::storage::binding::StorageBinding;
Expand All @@ -31,14 +31,13 @@ impl PySQLite3Storage {
#[new]
#[pyo3(signature = (file_path, *, create_database = true, apply_discard = false))]
fn py_new(file_path: &str, create_database: bool, apply_discard: bool) -> PyResult<Self> {
let backend = SQLite3Storage::new_with_option(
file_path,
SQLite3StorageOptions {
apply_discard,
attr_format: AttrFormat::Json,
},
)
.map_err(|e| PyRuntimeError::new_err(format!("Failed to open the SQLite3 file: {e:?}")))?;
let backend = SQLite3StorageBuilder::new(file_path)
.apply_discard(apply_discard)
.attr_format(AttrFormat::Json)
.build()
.map_err(|e| {
PyRuntimeError::new_err(format!("Failed to open the SQLite3 file: {e:?}"))
})?;
if create_database {
backend.create_database().map_err(|e| {
PyRuntimeError::new_err(format!("Failed to create the database: {e:?}"))
Expand Down
9 changes: 4 additions & 5 deletions rustuna_pyo3/src/storage/to_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
use rustuna_core::attr::{AttrFormat, AttrKey, Attrs, CategoryLabel};
use rustuna_core::distribution::Distribution;
use rustuna_core::storage::{InMemoryStorage, InMemoryStorageOptions, Storage};
use rustuna_core::storage::{InMemoryStorage, InMemoryStorageBuilder, Storage};
use rustuna_core::study::{Direction, PersistedStudy};
use rustuna_core::trial::{PersistedTrial, TrialState, TrialStateValues};
use rustuna_core::{Error, ErrorKind};
Expand Down Expand Up @@ -38,10 +38,9 @@ impl ToRustStorage {
pub fn new(obj: Py<PyAny>) -> Self {
ToRustStorage {
obj,
cache: InMemoryStorage::new_with_option(InMemoryStorageOptions {
attr_format: AttrFormat::Json,
..Default::default()
}),
cache: InMemoryStorageBuilder::new()
.attr_format(AttrFormat::Json)
.build(),
cache_study_to_src_study: HashMap::new(),
src_study_to_cache_study: HashMap::new(),
}
Expand Down
8 changes: 3 additions & 5 deletions rustuna_sampler/src/tpe/sampler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1563,11 +1563,9 @@ mod tests {

#[test]
fn study_columns_preserve_pending_trials_constraints_and_immutable_snapshots() {
let mut storage =
InMemoryStorage::new_with_option(rustuna_core::storage::InMemoryStorageOptions {
apply_discard: true,
..Default::default()
});
let mut storage = rustuna_core::storage::InMemoryStorageBuilder::new()
.apply_discard(true)
.build();
let study_id = storage
.create_new_study("history", vec![Direction::Minimize; 2])
.unwrap()
Expand Down
9 changes: 6 additions & 3 deletions rustuna_storage/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,12 @@ pub trait CachedStorageBackend: Send + Sync {
) -> Result<()>;
/// Whether reads from this backend omit discarded trials.
///
/// This mirrors `InMemoryStorageOptions::apply_discard` and
/// `JournalStorageOptions::apply_discard`: [`Self::discard_trials`] persists the discard
/// regardless of this flag, which only decides whether reads apply it.
/// This mirrors
/// [`JournalStorageBuilder::apply_discard`](crate::journal::storage::JournalStorageBuilder::apply_discard):
/// [`Self::discard_trials`] persists the discard regardless of this flag, which only decides
/// whether reads apply it. Note that this differs from
/// [`InMemoryStorageBuilder::apply_discard`](rustuna_core::storage::InMemoryStorageBuilder::apply_discard),
/// where discarding is a no-op when the flag is `false`.
fn apply_discard(&self) -> bool {
false
}
Expand Down
Loading