From a710f5436241f7316870886c5ce4b4d58d1a6418 Mon Sep 17 00:00:00 2001 From: Hemmi Shinichi Date: Thu, 19 Nov 2026 11:21:02 +0900 Subject: [PATCH] Introduce builders for the storage implementations --- rustuna_core/src/storage.rs | 124 ++++++++++--------- rustuna_pyo3/src/storage/in_memory.rs | 23 ++-- rustuna_pyo3/src/storage/journal.rs | 17 ++- rustuna_pyo3/src/storage/sqlite3.rs | 17 ++- rustuna_pyo3/src/storage/to_rust.rs | 9 +- rustuna_sampler/src/tpe/sampler.rs | 8 +- rustuna_storage/src/cache.rs | 9 +- rustuna_storage/src/journal/storage.rs | 158 +++++++++++++++---------- rustuna_storage/src/sqlite3.rs | 154 +++++++++++++++--------- 9 files changed, 299 insertions(+), 220 deletions(-) diff --git a/rustuna_core/src/storage.rs b/rustuna_core/src/storage.rs index d239f302..8d4bf326 100644 --- a/rustuna_core/src/storage.rs +++ b/rustuna_core/src/storage.rs @@ -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. @@ -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, @@ -530,7 +561,7 @@ impl Storage for InMemoryStorage { param_name: &str, labels: Vec, ) -> 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) } @@ -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 { @@ -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 } } @@ -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)); @@ -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; @@ -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; @@ -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; diff --git a/rustuna_pyo3/src/storage/in_memory.rs b/rustuna_pyo3/src/storage/in_memory.rs index 924fe592..7a223e78 100644 --- a/rustuna_pyo3/src/storage/in_memory.rs +++ b/rustuna_pyo3/src/storage/in_memory.rs @@ -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; @@ -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 } } @@ -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( diff --git a/rustuna_pyo3/src/storage/journal.rs b/rustuna_pyo3/src/storage/journal.rs index 5b369ae2..e8fdeabe 100644 --- a/rustuna_pyo3/src/storage/journal.rs +++ b/rustuna_pyo3/src/storage/journal.rs @@ -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; @@ -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 }) } diff --git a/rustuna_pyo3/src/storage/sqlite3.rs b/rustuna_pyo3/src/storage/sqlite3.rs index 7809a3cb..82fe5953 100644 --- a/rustuna_pyo3/src/storage/sqlite3.rs +++ b/rustuna_pyo3/src/storage/sqlite3.rs @@ -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; @@ -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 { - 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:?}")) diff --git a/rustuna_pyo3/src/storage/to_rust.rs b/rustuna_pyo3/src/storage/to_rust.rs index 6c6a828b..2869d5e6 100644 --- a/rustuna_pyo3/src/storage/to_rust.rs +++ b/rustuna_pyo3/src/storage/to_rust.rs @@ -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}; @@ -38,10 +38,9 @@ impl ToRustStorage { pub fn new(obj: Py) -> 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(), } diff --git a/rustuna_sampler/src/tpe/sampler.rs b/rustuna_sampler/src/tpe/sampler.rs index dcddd744..921c25aa 100644 --- a/rustuna_sampler/src/tpe/sampler.rs +++ b/rustuna_sampler/src/tpe/sampler.rs @@ -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() diff --git a/rustuna_storage/src/cache.rs b/rustuna_storage/src/cache.rs index 78269191..6c22a796 100644 --- a/rustuna_storage/src/cache.rs +++ b/rustuna_storage/src/cache.rs @@ -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 } diff --git a/rustuna_storage/src/journal/storage.rs b/rustuna_storage/src/journal/storage.rs index 97dd9326..bd51c388 100644 --- a/rustuna_storage/src/journal/storage.rs +++ b/rustuna_storage/src/journal/storage.rs @@ -20,20 +20,6 @@ use rustuna_core::{Error, ErrorKind, Result}; use super::{JournalBackend, JournalLog, JournalOperation}; use crate::datetime::{journal_datetime_to_naive_utc, naive_utc_to_aware_utc, now_aware_utc}; -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] -/// Options for [`JournalStorage`]. -pub struct JournalStorageOptions { - /// If `true`, discarded trials are omitted when replaying the journal. - /// Discard logs are written regardless of this option. - pub apply_discard: bool, - /// Representation of attribute values. - /// - /// With [`AttrFormat::Json`], user and system attributes are written in Optuna's schema - /// (one `user_attr` / `system_attr` log per key with the raw JSON value), so Optuna can - /// read them. Logs written in either format are readable in both formats. - pub attr_format: AttrFormat, -} - /// Storage implementation backed by an append-only journal log. /// /// Similar in spirit to Optuna's `JournalStorage`, this storage writes every state-changing @@ -43,29 +29,93 @@ pub struct JournalStorage { replay: JournalReplayState, } -impl JournalStorage { - /// Creates a journal storage and synchronizes its in-memory replay state from the backend. - pub fn new(backend: Box) -> Result { - Self::new_with_options(backend, JournalStorageOptions::default()) +/// Builder for [`JournalStorage`], following the API style of [`std::thread::Builder`]. +/// +/// Settings are configured by chaining setter methods and the storage is created with +/// [`JournalStorageBuilder::build`]. +/// +/// # Examples +/// +/// ```no_run +/// use rustuna_storage::journal::file::JournalFileBackend; +/// use rustuna_storage::journal::storage::JournalStorageBuilder; +/// +/// # fn main() -> rustuna_core::Result<()> { +/// let path = std::env::temp_dir().join("journal.log"); +/// let backend = JournalFileBackend::new(&path, None)?; +/// let storage = JournalStorageBuilder::new(Box::new(backend)) +/// .apply_discard(true) +/// .build()?; +/// # let _ = storage; +/// # Ok(()) +/// # } +/// ``` +pub struct JournalStorageBuilder { + backend: Box, + apply_discard: bool, + attr_format: AttrFormat, +} +impl std::fmt::Debug for JournalStorageBuilder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("JournalStorageBuilder") + .field("apply_discard", &self.apply_discard) + .field("attr_format", &self.attr_format) + .finish_non_exhaustive() + } +} +impl JournalStorageBuilder { + /// Creates a builder backed by `backend`. + pub fn new(backend: Box) -> Self { + Self { + backend, + apply_discard: false, + attr_format: AttrFormat::default(), + } } - /// Creates a journal storage and synchronizes its in-memory replay state from the backend. - pub fn new_with_options( - backend: Box, - options: JournalStorageOptions, - ) -> Result { + /// Sets whether discarded trials are omitted when replaying the journal. + /// + /// Discard logs are written regardless of this setting. Defaults to `false`. + pub fn apply_discard(self, apply_discard: bool) -> Self { + Self { + apply_discard, + ..self + } + } + + /// Sets the representation of attribute values. + /// + /// With [`AttrFormat::Json`], user and system attributes are written in Optuna's schema + /// (one `user_attr` / `system_attr` log per key with the raw JSON value), so Optuna can + /// read them. Logs written in either format are readable in both formats. Defaults to + /// [`AttrFormat::Plain`]. + pub fn attr_format(self, attr_format: AttrFormat) -> Self { + Self { + attr_format, + ..self + } + } + + /// Builds the storage and synchronizes its in-memory replay state from the backend. + pub fn build(self) -> Result { let worker_id_prefix = format!("{}-{}-", unique_prefix(), std::process::id()); let mut storage = JournalStorage { - backend, - replay: JournalReplayState::new( - worker_id_prefix, - options.apply_discard, - options.attr_format, - ), + backend: self.backend, + replay: JournalReplayState::new(worker_id_prefix, self.apply_discard, self.attr_format), }; storage.sync_with_backend()?; Ok(storage) } +} + +impl JournalStorage { + /// Creates a journal storage with the default configuration and synchronizes its in-memory + /// replay state from the backend. + /// + /// Use [`JournalStorageBuilder`] to configure the storage. + pub fn new(backend: Box) -> Result { + JournalStorageBuilder::new(backend).build() + } fn worker_id(&self) -> String { format!( @@ -2450,13 +2500,9 @@ mod tests { } let backend = InMemoryJournalBackend { logs: logs.clone() }; - let mut reloaded = JournalStorage::new_with_options( - Box::new(backend), - JournalStorageOptions { - apply_discard: true, - ..Default::default() - }, - )?; + let mut reloaded = JournalStorageBuilder::new(Box::new(backend)) + .apply_discard(true) + .build()?; let trials = reloaded.get_trials(study_id)?; assert!(trials[0].is_none()); Ok(()) @@ -2571,13 +2617,9 @@ mod tests { storage.discard_trials(&[trial_id])?; let backend = InMemoryJournalBackend { logs: logs.clone() }; - let mut storage2 = JournalStorage::new_with_options( - Box::new(backend), - JournalStorageOptions { - apply_discard: false, - ..Default::default() - }, - )?; + let mut storage2 = JournalStorageBuilder::new(Box::new(backend)) + .apply_discard(false) + .build()?; let trials = storage2.get_trials(study_id)?; assert_eq!(trials.len(), 1); assert_eq!(trials[0].as_ref().unwrap().id, trial_id); @@ -2591,13 +2633,9 @@ mod tests { let backend = InMemoryJournalBackend { logs: Arc::new(Mutex::new(Vec::new())), }; - let mut storage = JournalStorage::new_with_options( - Box::new(backend), - JournalStorageOptions { - apply_discard, - ..Default::default() - }, - )?; + let mut storage = JournalStorageBuilder::new(Box::new(backend)) + .apply_discard(apply_discard) + .build()?; assert_eq!(storage.may_omit_trials(), apply_discard); let study_id = storage.create_new_study("s", vec![Direction::Minimize])?.id; @@ -2612,13 +2650,9 @@ mod tests { fn get_n_trials_counts_states_including_discarded_trials() -> Result<()> { let logs = Arc::new(Mutex::new(Vec::new())); let backend = InMemoryJournalBackend { logs }; - let mut storage = JournalStorage::new_with_options( - Box::new(backend), - JournalStorageOptions { - apply_discard: true, - ..Default::default() - }, - )?; + let mut storage = JournalStorageBuilder::new(Box::new(backend)) + .apply_discard(true) + .build()?; let study_id = storage.create_new_study("s", vec![Direction::Minimize])?.id; let running_trial_id = storage.create_new_trial(study_id)?.id; let complete_trial_id = storage.create_new_trial(study_id)?.id; @@ -2893,13 +2927,9 @@ mod tests { attr_format: AttrFormat, ) -> Result { let backend = InMemoryJournalBackend { logs: logs.clone() }; - JournalStorage::new_with_options( - Box::new(backend), - JournalStorageOptions { - attr_format, - ..Default::default() - }, - ) + JournalStorageBuilder::new(Box::new(backend)) + .attr_format(attr_format) + .build() } fn user_attr(trial: &PersistedTrial, key: &str) -> Option { diff --git a/rustuna_storage/src/sqlite3.rs b/rustuna_storage/src/sqlite3.rs index f4d2adea..312e7fae 100644 --- a/rustuna_storage/src/sqlite3.rs +++ b/rustuna_storage/src/sqlite3.rs @@ -13,26 +13,10 @@ use rustuna_core::trial::{PersistedTrial, TrialState, TrialStateValues}; use rustuna_core::{Error, ErrorKind, Result}; use serde_json::{json, Number, Value}; use std::collections::HashMap; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; -/// Options for [`SQLite3Storage`]. -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] -pub struct SQLite3StorageOptions { - /// If `true`, discarded trials are omitted from subsequent reads. - /// - /// As in `JournalStorageOptions`, this only gates reads: `discard_trials` marks the trials - /// in the database regardless of this option. - pub apply_discard: bool, - /// Representation of user and system attribute values. - /// - /// Both formats write valid JSON into `value_json`, so Optuna can always read the values. - /// With [`AttrFormat::Plain`], strings are JSON-encoded on write and unquoted on read. With - /// [`AttrFormat::Json`], values must already be JSON texts and are stored as-is, which is the - /// same representation as Optuna's `RDBStorage`. - pub attr_format: AttrFormat, -} - /// SQLite-backed storage backend. /// /// This backend persists studies and trials in a local SQLite database and is typically wrapped @@ -40,7 +24,8 @@ pub struct SQLite3StorageOptions { /// `rustuna_core`. pub struct SQLite3Storage { conn: Mutex, - options: SQLite3StorageOptions, + apply_discard: bool, + attr_format: AttrFormat, has_discarded_at_column: AtomicBool, } @@ -53,40 +38,97 @@ const TRIALS_DISCARDED_AT_INDEX_SQL: &str = type TrialRow = (u32, u32, String, Option, Option); -impl SQLite3Storage { - /// Opens a SQLite database file. - pub fn new(file_path: &str) -> Result { - Self::new_with_option(file_path, SQLite3StorageOptions::default()) +/// Builder for [`SQLite3Storage`], following the API style of [`std::thread::Builder`]. +/// +/// Settings are configured by chaining setter methods and the storage is created with +/// [`SQLite3StorageBuilder::build`]. +/// +/// # Examples +/// +/// ``` +/// use rustuna_storage::sqlite3::SQLite3StorageBuilder; +/// +/// let storage = SQLite3StorageBuilder::new(":memory:") +/// .apply_discard(true) +/// .build() +/// .unwrap(); +/// storage.create_database().unwrap(); +/// storage.validate_discard_support().unwrap(); +/// ``` +#[derive(Clone, Debug)] +pub struct SQLite3StorageBuilder { + file_path: PathBuf, + apply_discard: bool, + attr_format: AttrFormat, +} +impl SQLite3StorageBuilder { + /// Creates a builder that opens the SQLite database file at `file_path`. + pub fn new(file_path: impl AsRef) -> Self { + Self { + file_path: file_path.as_ref().to_path_buf(), + apply_discard: false, + attr_format: AttrFormat::default(), + } } - /// Opens a SQLite database file with the given options. + /// Sets whether discarded trials are omitted from subsequent reads. /// - /// When `apply_discard` is enabled, call [`Self::validate_discard_support`] after - /// [`Self::create_database`] to reject databases whose schema predates the discard column. - pub fn new_with_option( - file_path: &str, - options: SQLite3StorageOptions, - ) -> Result { - let conn = Connection::open(file_path).map_err(|e| { + /// This only gates reads: `discard_trials` marks the trials in the database regardless of + /// this setting. When it is enabled, call [`SQLite3Storage::validate_discard_support`] after + /// [`SQLite3Storage::create_database`] to reject databases whose schema predates the discard + /// column. Defaults to `false`. + pub fn apply_discard(self, apply_discard: bool) -> Self { + Self { + apply_discard, + ..self + } + } + + /// Sets the representation of user and system attribute values. + /// + /// Both formats write valid JSON into `value_json`, so Optuna can always read the values. + /// With [`AttrFormat::Plain`] (the default), strings are JSON-encoded on write and unquoted + /// on read. With [`AttrFormat::Json`], values must already be JSON texts and are stored + /// as-is, which is the same representation as Optuna's `RDBStorage`. + pub fn attr_format(self, attr_format: AttrFormat) -> Self { + Self { + attr_format, + ..self + } + } + + /// Opens the database file and builds the storage. + pub fn build(self) -> Result { + let conn = Connection::open(&self.file_path).map_err(|e| { Error::with_reason( ErrorKind::StorageError, - format!("Failed to open {file_path}: {e}"), + format!("Failed to open {}: {e}", self.file_path.display()), ) })?; - let has_discarded_at_column = Self::has_discarded_at_column(&conn)?; + let has_discarded_at_column = SQLite3Storage::has_discarded_at_column(&conn)?; Ok(SQLite3Storage { conn: Mutex::new(conn), - options, + apply_discard: self.apply_discard, + attr_format: self.attr_format, has_discarded_at_column: AtomicBool::new(has_discarded_at_column), }) } +} + +impl SQLite3Storage { + /// Opens a SQLite database file with the default configuration. + /// + /// Use [`SQLite3StorageBuilder`] to configure the storage. + pub fn new(file_path: &str) -> Result { + SQLite3StorageBuilder::new(file_path).build() + } /// Returns an error when discards were requested but the database cannot record them. /// /// [`Self::create_database`] migrates the column in, so this only fails for databases opened /// without initialization. pub fn validate_discard_support(&self) -> Result<()> { - if self.options.apply_discard && !self.has_discarded_at_column.load(Ordering::Acquire) { + if self.apply_discard && !self.has_discarded_at_column.load(Ordering::Acquire) { return Err(Error::with_reason( ErrorKind::StorageError, "apply_discard requires the Rustuna-specific `discarded_at` column on the \ @@ -247,7 +289,7 @@ impl SQLite3Storage { impl SQLite3Storage { fn encode_attr(&self, value: String) -> String { - match self.options.attr_format { + match self.attr_format { AttrFormat::Plain => plain_to_json(&value), // TODO: Values are not validated. A non-JSON text passed through the Rust API is // stored as-is and only fails when it is decoded (e.g. by Optuna's `json.loads`). @@ -256,7 +298,7 @@ impl SQLite3Storage { } fn decode_attr(&self, value: String) -> String { - match self.options.attr_format { + match self.attr_format { AttrFormat::Plain => json_to_plain(&value), AttrFormat::Json => value, } @@ -265,11 +307,11 @@ impl SQLite3Storage { impl CachedStorageBackend for SQLite3Storage { fn apply_discard(&self) -> bool { - self.options.apply_discard + self.apply_discard } fn attr_format(&self) -> AttrFormat { - self.options.attr_format + self.attr_format } fn discard_trials(&mut self, trial_ids: &[u32]) -> Result<()> { @@ -1024,7 +1066,7 @@ impl CachedStorageBackend for SQLite3Storage { let (_, labels) = json_to_distribution(&distribution_json)?; if let Some(labels) = labels { for (key, value) in - category_labels_to_attrs(¶m_name, &labels, self.options.attr_format) + category_labels_to_attrs(¶m_name, &labels, self.attr_format) { attrs.entry(key).or_insert(value); } @@ -1538,7 +1580,7 @@ impl CachedStorageBackend for SQLite3Storage { let select_columns = "SELECT trial_id, number, state, datetime_start, datetime_complete FROM trials"; let discard_condition = - if self.options.apply_discard && self.has_discarded_at_column.load(Ordering::Acquire) { + if self.apply_discard && self.has_discarded_at_column.load(Ordering::Acquire) { " AND discarded_at IS NULL" } else { "" @@ -2197,7 +2239,7 @@ mod tests { use rustuna_core::study::{create_study, Direction}; fn init_storage() -> Result { - init_storage_with_option(SQLite3StorageOptions::default()) + init_storage_with_option(false, AttrFormat::default()) } /// Reads SQLite's own idea of the current UTC time, truncated to whole seconds. @@ -2270,8 +2312,14 @@ mod tests { Ok(()) } - fn init_storage_with_option(options: SQLite3StorageOptions) -> Result { - let storage = SQLite3Storage::new_with_option(":memory:", options)?; + fn init_storage_with_option( + apply_discard: bool, + attr_format: AttrFormat, + ) -> Result { + let storage = SQLite3StorageBuilder::new(":memory:") + .apply_discard(apply_discard) + .attr_format(attr_format) + .build()?; storage.create_database()?; storage.validate_discard_support()?; Ok(storage) @@ -2345,10 +2393,7 @@ mod tests { #[test] fn discard_trials_are_omitted_by_cached_storage() -> Result<()> { - let backend = init_storage_with_option(SQLite3StorageOptions { - apply_discard: true, - ..Default::default() - })?; + let backend = init_storage_with_option(true, AttrFormat::default())?; let mut storage = CachedStorage::new(Box::new(backend)); assert!(storage.may_omit_trials()); @@ -2370,13 +2415,9 @@ mod tests { } fn open_file_storage(path: &str, apply_discard: bool) -> Result { - let backend = SQLite3Storage::new_with_option( - path, - SQLite3StorageOptions { - apply_discard, - ..Default::default() - }, - )?; + let backend = SQLite3StorageBuilder::new(path) + .apply_discard(apply_discard) + .build()?; backend.create_database()?; backend.validate_discard_support()?; Ok(CachedStorage::new(Box::new(backend))) @@ -3268,10 +3309,7 @@ mod tests { (AttrFormat::Plain, "123", "\"123\""), (AttrFormat::Json, "[1, 2]", "[1, 2]"), ] { - let mut storage = init_storage_with_option(SQLite3StorageOptions { - attr_format: format, - ..Default::default() - })?; + let mut storage = init_storage_with_option(false, format)?; let study_id = storage .create_new_study("example", vec![Direction::Minimize])? .id;