use crate::blackbox::{write_blackbox_report, BlackboxReportOptions, BlackboxRunStatus};
use crate::embedded_store::{EmbeddedStore, EmbeddedStoreOpenOptions, EmbeddedStoreOpenReport};
use crate::store::DurabilityPolicy;
use crate::{
AdaptiveVectorBackendPolicy, Database, DatabaseConfig, DatabaseReadTransaction, HawDBError,
QueryOutput, QueryStreamOptions, Result, RetainedQueryCursor, RetainedQueryError,
RetainedQueryOptions, RuntimeCapabilities, SearchIndex, SearchRangeReadConfig, Value,
};
use hawdb_core::{RuntimeCancellationReason, RuntimeTaskContext};
use hawdb_qos::{
IoConcurrencyBudget, ProcessMemoryPolicy, RuntimeAdmissionError, RuntimeGovernor,
RuntimeGovernorConfig, RuntimeMemorySnapshot, RuntimeResourceBudget, RuntimeResourceSnapshot,
StorageDeviceProfile, StorageMediaKind,
};
#[cfg(test)]
use hawdb_readiness::embedded_query_path::EMBEDDED_QUERY_PATH_READINESS_PROTOCOL;
use hawdb_readiness::embedded_query_path::{EmbeddedQueryEntrypoint, EmbeddedQueryPathReadiness};
use hawdb_storage::scan::SegmentReadScheduler;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EmbeddedDeploymentProfile {
#[default]
SharedHost,
MobileEmbedded,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmbeddedRuntimeResources {
pub cpu: RuntimeResourceBudget,
pub memory: RuntimeMemorySnapshot,
pub storage_device: StorageDeviceProfile,
pub storage_io: IoConcurrencyBudget,
}
impl EmbeddedRuntimeResources {
pub fn foreground_segment_read_scheduler(
self,
max_coalesced_bytes: NonZeroU64,
) -> SegmentReadScheduler {
SegmentReadScheduler::new(self.storage_io.foreground_depth, max_coalesced_bytes)
}
pub fn background_segment_read_scheduler(
self,
max_coalesced_bytes: NonZeroU64,
) -> SegmentReadScheduler {
SegmentReadScheduler::new(self.storage_io.background_depth, max_coalesced_bytes)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HawDBEmbeddedOpenOptions {
pub path: PathBuf,
pub config: DatabaseConfig,
pub durability: DurabilityPolicy,
pub deployment_profile: EmbeddedDeploymentProfile,
pub storage_device: Option<StorageDeviceProfile>,
pub storage_io: Option<IoConcurrencyBudget>,
pub resource_snapshot: Option<RuntimeResourceSnapshot>,
pub runtime_governor_config: Option<RuntimeGovernorConfig>,
}
#[derive(Debug)]
pub struct HawDBEmbedded {
path: PathBuf,
database: Database,
deployment_profile: EmbeddedDeploymentProfile,
runtime_resources: EmbeddedRuntimeResources,
runtime_governor: RuntimeGovernor,
transaction: Option<EmbeddedTransaction>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmbeddedQueryError {
Database(HawDBError),
Admission(RuntimeAdmissionError),
Stopped(RuntimeCancellationReason),
}
impl Display for EmbeddedQueryError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Database(error) => Display::fmt(error, formatter),
Self::Admission(error) => Display::fmt(error, formatter),
Self::Stopped(reason) => write!(formatter, "runtime task stopped: {reason}"),
}
}
}
impl Error for EmbeddedQueryError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Database(error) => Some(error),
Self::Admission(error) => Some(error),
Self::Stopped(reason) => Some(reason),
}
}
}
impl From<HawDBError> for EmbeddedQueryError {
fn from(error: HawDBError) -> Self {
Self::Database(error)
}
}
impl From<RuntimeAdmissionError> for EmbeddedQueryError {
fn from(error: RuntimeAdmissionError) -> Self {
Self::Admission(error)
}
}
pub(crate) fn admit_prepared<T>(
governor: &RuntimeGovernor,
prepared: T,
request: impl Fn(hawdb_qos::RuntimeGovernorSnapshot, Option<&T>) -> hawdb_qos::RuntimeWorkRequest,
) -> std::result::Result<(Option<T>, hawdb_qos::RuntimePermit), EmbeddedQueryError> {
match admit_query(governor, request(governor.snapshot(), Some(&prepared))) {
Ok(permit) => Ok((Some(prepared), permit)),
Err(_) => {
drop(prepared);
let permit = admit_query(governor, request(governor.snapshot(), None))?;
Ok((None, permit))
}
}
}
pub(crate) fn admit_query(
governor: &RuntimeGovernor,
request: hawdb_qos::RuntimeWorkRequest,
) -> std::result::Result<hawdb_qos::RuntimePermit, EmbeddedQueryError> {
match governor.try_admit(request) {
Ok(permit) => Ok(permit),
Err(error) => {
if error.is_retryable() {
governor.record_admission_wait(request, error.code, 0);
}
Err(EmbeddedQueryError::Admission(error))
}
}
}
pub(crate) fn check_query_context(
governor: &RuntimeGovernor,
context: &RuntimeTaskContext,
) -> std::result::Result<(), EmbeddedQueryError> {
context.checkpoint().map_err(|reason| {
governor.record_cancellation(reason);
EmbeddedQueryError::Stopped(reason)
})
}
impl HawDBEmbeddedOpenOptions {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self::for_profile(path, EmbeddedDeploymentProfile::SharedHost)
}
pub fn mobile(path: impl Into<PathBuf>) -> Self {
Self::for_profile(path, EmbeddedDeploymentProfile::MobileEmbedded)
}
pub fn for_profile(
path: impl Into<PathBuf>,
deployment_profile: EmbeddedDeploymentProfile,
) -> Self {
Self {
path: path.into(),
config: default_database_config(deployment_profile),
durability: DurabilityPolicy::default(),
deployment_profile,
storage_device: None,
storage_io: None,
resource_snapshot: None,
runtime_governor_config: None,
}
}
pub fn with_config(mut self, config: DatabaseConfig) -> Self {
self.config = config;
self
}
pub fn with_durability(mut self, durability: DurabilityPolicy) -> Self {
self.durability = durability;
self
}
pub fn with_runtime_capabilities(mut self, capabilities: RuntimeCapabilities) -> Self {
self.config.runtime_capabilities = capabilities;
self
}
pub fn with_storage_io_budget(mut self, storage_io: IoConcurrencyBudget) -> Self {
self.storage_io = Some(storage_io);
self
}
pub fn with_storage_device_profile(mut self, storage_device: StorageDeviceProfile) -> Self {
self.storage_device = Some(storage_device);
self
}
pub fn with_resource_snapshot(mut self, resource_snapshot: RuntimeResourceSnapshot) -> Self {
self.resource_snapshot = Some(resource_snapshot);
self
}
pub fn with_runtime_governor_config(
mut self,
runtime_governor_config: RuntimeGovernorConfig,
) -> Self {
self.runtime_governor_config = Some(runtime_governor_config);
self
}
}
struct EmbeddedRuntimeSetup {
runtime_governor: RuntimeGovernor,
runtime_resources: EmbeddedRuntimeResources,
}
fn embedded_runtime_setup(
deployment_profile: EmbeddedDeploymentProfile,
storage_device: StorageDeviceProfile,
storage_io: Option<IoConcurrencyBudget>,
resource_snapshot: Option<RuntimeResourceSnapshot>,
governor_config: Option<RuntimeGovernorConfig>,
process_memory_policy: Option<ProcessMemoryPolicy>,
) -> EmbeddedRuntimeSetup {
let resource_snapshot_pinned = resource_snapshot.is_some();
let resource_snapshot = resource_snapshot.unwrap_or_else(RuntimeResourceSnapshot::detect);
let cpu = resource_snapshot.cpu;
let storage_io =
storage_io.unwrap_or_else(|| default_io_budget(deployment_profile, storage_device));
let governor_config =
governor_config.unwrap_or_else(|| default_runtime_governor_config(deployment_profile));
let runtime_governor = match process_memory_policy {
Some(policy) => RuntimeGovernor::new_with_process_memory_policy(
governor_config,
resource_snapshot,
storage_io,
policy,
),
None => RuntimeGovernor::new(governor_config, resource_snapshot, storage_io),
};
if resource_snapshot_pinned {
runtime_governor.pin_resources();
}
EmbeddedRuntimeSetup {
runtime_governor,
runtime_resources: EmbeddedRuntimeResources {
cpu,
memory: resource_snapshot.memory,
storage_device,
storage_io,
},
}
}
impl HawDBEmbedded {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::open_with_options(HawDBEmbeddedOpenOptions::new(path.as_ref().to_path_buf()))
}
pub fn open_with_options(options: HawDBEmbeddedOpenOptions) -> Result<Self> {
Self::open_with_runtime_policy(options, None)
}
pub fn open_with_process_memory_policy(
options: HawDBEmbeddedOpenOptions,
process_memory_policy: ProcessMemoryPolicy,
) -> Result<Self> {
Self::open_with_runtime_policy(options, Some(process_memory_policy))
}
fn open_with_runtime_policy(
options: HawDBEmbeddedOpenOptions,
process_memory_policy: Option<ProcessMemoryPolicy>,
) -> Result<Self> {
let storage_device = options
.storage_device
.unwrap_or_else(|| StorageDeviceProfile::detect(&options.path));
let setup = embedded_runtime_setup(
options.deployment_profile,
storage_device,
options.storage_io,
options.resource_snapshot,
options.runtime_governor_config,
process_memory_policy,
);
let mut database = Database::open_with_durability_and_config(
&options.path,
options.durability,
options.config,
)?;
database.set_runtime_governor(setup.runtime_governor.clone());
Ok(Self {
path: options.path,
database,
deployment_profile: options.deployment_profile,
runtime_resources: setup.runtime_resources,
runtime_governor: setup.runtime_governor,
transaction: None,
})
}
pub fn open_in_memory() -> Self {
Self::open_in_memory_with_config(DatabaseConfig::default())
}
pub fn open_in_memory_with_config(config: DatabaseConfig) -> Self {
Self::open_in_memory_with_runtime_governor_config(config, None)
}
pub fn open_in_memory_with_runtime_governor_config(
config: DatabaseConfig,
runtime_governor_config: Option<RuntimeGovernorConfig>,
) -> Self {
let deployment_profile = EmbeddedDeploymentProfile::SharedHost;
let storage_device = StorageDeviceProfile::host_provided(StorageMediaKind::Memory, None);
let setup = embedded_runtime_setup(
deployment_profile,
storage_device,
None,
None,
runtime_governor_config,
None,
);
let mut database = Database::new_with_config(config);
database.set_runtime_governor(setup.runtime_governor.clone());
Self {
path: PathBuf::new(),
database,
deployment_profile,
runtime_resources: setup.runtime_resources,
runtime_governor: setup.runtime_governor,
transaction: None,
}
}
pub fn open_embedded_store(
options: EmbeddedStoreOpenOptions,
) -> Result<(EmbeddedStore, EmbeddedStoreOpenReport)> {
EmbeddedStore::open_with_options(options)
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn is_in_memory(&self) -> bool {
self.path.as_os_str().is_empty()
}
pub fn deployment_profile(&self) -> EmbeddedDeploymentProfile {
self.deployment_profile
}
pub fn runtime_resources(&self) -> EmbeddedRuntimeResources {
let resources = self.runtime_governor.snapshot().resources;
EmbeddedRuntimeResources {
cpu: resources.cpu,
memory: resources.memory,
..self.runtime_resources
}
}
pub fn runtime_governor(&self) -> &RuntimeGovernor {
&self.runtime_governor
}
pub(crate) fn bind_runtime(&mut self, binding: &crate::api::EmbeddedRuntimeBinding) {
self.database.bind_embedded_runtime(binding);
self.runtime_governor = binding.governor().clone();
}
pub fn refresh_runtime_resources(&mut self) -> bool {
self.runtime_governor.refresh_from_host()
}
pub fn update_runtime_resources(&mut self, resources: RuntimeResourceSnapshot) -> bool {
self.runtime_governor.update_resources(resources)
}
pub(crate) fn runtime_capabilities(&self) -> RuntimeCapabilities {
self.database.runtime_capabilities()
}
pub fn admitted_query_path_readiness(&self) -> EmbeddedQueryPathReadiness {
EmbeddedQueryPathReadiness::admitted(EmbeddedQueryEntrypoint::AdmittedSync)
}
pub fn raw_database_query_path_readiness() -> EmbeddedQueryPathReadiness {
EmbeddedQueryPathReadiness::raw_database()
}
pub fn query_admitted(
&mut self,
cypher_text: &str,
) -> std::result::Result<QueryOutput, EmbeddedQueryError> {
self.query_with_params_admitted_context(
cypher_text,
&BTreeMap::new(),
&RuntimeTaskContext::default(),
)
}
pub fn query_with_params_admitted(
&mut self,
cypher_text: &str,
parameters: &BTreeMap<String, Value>,
) -> std::result::Result<QueryOutput, EmbeddedQueryError> {
self.query_with_params_admitted_context(
cypher_text,
parameters,
&RuntimeTaskContext::default(),
)
}
pub fn query_with_params_retained(
&self,
cypher_text: &str,
parameters: &BTreeMap<String, Value>,
options: RetainedQueryOptions,
) -> std::result::Result<RetainedQueryCursor, RetainedQueryError> {
if self.transaction.is_some() {
return Err(HawDBError::Execution(
"a user transaction is open on this database".into(),
)
.into());
}
self.database
.query_with_params_retained(cypher_text, parameters, options)
}
pub fn query_with_params_retained_node(
&self,
cypher_text: &str,
parameters: &BTreeMap<String, Value>,
options: RetainedQueryOptions,
) -> std::result::Result<crate::RetainedNodeCursor, RetainedQueryError> {
if self.transaction.is_some() {
return Err(HawDBError::Execution(
"a user transaction is open on this database".into(),
)
.into());
}
self.database
.query_with_params_retained_node(cypher_text, parameters, options)
}
pub fn query_with_params_admitted_context(
&mut self,
cypher_text: &str,
parameters: &BTreeMap<String, Value>,
task_context: &RuntimeTaskContext,
) -> std::result::Result<QueryOutput, EmbeddedQueryError> {
self.query_request_admitted(
crate::QueryRequest::new(cypher_text)
.with_params(parameters)
.with_task_context(task_context),
)
}
pub fn query_request_admitted(
&mut self,
query: crate::QueryRequest<'_>,
) -> std::result::Result<QueryOutput, EmbeddedQueryError> {
let default_context = RuntimeTaskContext::default();
let task_context = query.task_context.unwrap_or(&default_context);
if self.transaction.is_some() {
return Err(EmbeddedQueryError::Database(HawDBError::Execution(
"a user transaction is open on this database".into(),
)));
}
self.check_admitted_query_context(task_context)?;
let planning_request = crate::api::runtime_planning_request(
query.cypher.len(),
hawdb_qos::RuntimeWorkPriority::Foreground,
);
let prepared = {
let planning_permit = self.try_admit_query(planning_request)?;
let prepared = self.database.prepare_runtime_request(query)?;
prepared.with_planning_memory(
planning_permit
.into_retained_memory()
.expect("control work owns a fixed memory reservation"),
)
};
let admission = prepared.admission().clone();
self.check_admitted_query_context(task_context)?;
let result_budget_bytes = self.admitted_result_budget_bytes();
let is_mutation = admission.is_mutation;
let streaming_eligible = admission.streaming_eligible;
let (prepared, permit) = self.try_admit_prepared(prepared, |snapshot, prepared| {
let request =
admission.runtime_work_request_for_snapshot(result_budget_bytes, snapshot);
request
.with_memory_bytes(request.memory_bytes.max(planning_request.memory_bytes))
.with_retained_memory_bytes(
prepared.map_or(0, |value| value.planning_memory_bytes()),
)
})?;
let request = permit.request();
let prepared = match prepared {
Some(prepared) => prepared,
None => self.database.prepare_runtime_request(query)?,
};
if prepared.admission() != &admission {
return Err(HawDBError::Execution(
"query admission changed during preparation rebuild; retry the query".into(),
)
.into());
}
let execution_task_context = permit.bind_task_context(task_context.clone());
let _permit = permit;
let query = query.with_task_context(&execution_task_context);
let result = if is_mutation || !streaming_eligible {
self.database.query_prepared_request(prepared, query)
} else {
let max_payload_bytes = usize::try_from(request.result_bytes).unwrap_or(usize::MAX);
self.database
.begin_read_transaction_with_shared_plan_cache()?
.query_prepared_request(
prepared,
query.with_restrictive_output_limits(QueryStreamOptions {
max_rows: self.database.config().read_result_row_limit(),
max_payload_bytes: Some(max_payload_bytes),
}),
)
.map(|result| result.output)
};
if !is_mutation {
self.check_admitted_query_context(task_context)?;
} else if result.is_err()
&& let Err(reason) = task_context.checkpoint()
{
self.runtime_governor.record_cancellation(reason);
return Err(EmbeddedQueryError::Stopped(reason));
}
result.map_err(EmbeddedQueryError::Database)
}
pub fn query_sql_request_admitted(
&mut self,
query: crate::SqlQueryRequest<'_>,
) -> std::result::Result<QueryOutput, EmbeddedQueryError> {
self.query_sql_request_admitted_with_result(query)
.map(|result| result.output)
}
pub fn query_sql_request_admitted_with_result(
&mut self,
query: crate::SqlQueryRequest<'_>,
) -> std::result::Result<crate::SqlStatementResult, EmbeddedQueryError> {
if self.transaction.is_some() {
return Err(HawDBError::Execution(
"a user transaction is open on this database".into(),
)
.into());
}
let default_context = RuntimeTaskContext::default();
let context = query.task_context.unwrap_or(&default_context);
self.check_admitted_query_context(context)?;
let planning_request = crate::api::runtime_planning_request(
query.sql.len(),
hawdb_qos::RuntimeWorkPriority::Foreground,
);
let prepared = {
let permit = self.try_admit_query(planning_request)?;
self.database
.runtime_sql_planning_snapshot()
.prepare(query.sql)?
.with_planning_memory(
permit
.into_retained_memory()
.expect("control work owns fixed memory"),
)
};
let uses_snapshot = prepared.uses_snapshot();
let admitted_request = prepared.work_request(self.admitted_result_budget_bytes());
let request = admitted_request.with_memory_bytes(
admitted_request
.memory_bytes
.max(planning_request.memory_bytes),
);
let (prepared, permit) = self.try_admit_prepared(prepared, |_, prepared| {
request.with_retained_memory_bytes(
prepared.map_or(0, |value| value.planning_memory_bytes()),
)
})?;
let prepared = match prepared {
Some(prepared) => prepared,
None => self
.database
.runtime_sql_planning_snapshot()
.prepare(query.sql)?,
};
if prepared.work_request(admitted_request.result_bytes) != admitted_request {
return Err(HawDBError::Execution(
"SQL admission changed during preparation rebuild; retry the query".into(),
)
.into());
}
let context = permit.bind_task_context(context.clone());
self.check_admitted_query_context(&context)?;
let (prepared, _planning_memory) = prepared.into_statement(&self.database)?;
let query = query.with_task_context(&context);
let reads_snapshot =
uses_snapshot && !matches!(prepared.statement(), crate::sql::SqlStatement::Branch(_));
let result = if reads_snapshot {
let started = hawdb_core::time::Instant::now();
let statement_kind = crate::api::sql_statement_kind(prepared.statement());
let result = self
.database
.begin_read_transaction_with_shared_plan_cache()
.and_then(|snapshot| snapshot.query_sql_with_prepared_request(query, prepared));
self.database
.finish_snapshot_sql_read(query.sql, statement_kind, started, &result);
result.map(|output| crate::SqlStatementResult {
output,
mutation: None,
})
} else {
self.database
.query_sql_with_prepared_request_with_result(query, prepared)
};
if uses_snapshot {
self.check_admitted_query_context(&context)?;
}
result.map_err(EmbeddedQueryError::Database)
}
fn try_admit_prepared<T>(
&self,
prepared: T,
request: impl Fn(
hawdb_qos::RuntimeGovernorSnapshot,
Option<&T>,
) -> hawdb_qos::RuntimeWorkRequest,
) -> std::result::Result<(Option<T>, hawdb_qos::RuntimePermit), EmbeddedQueryError> {
admit_prepared(&self.runtime_governor, prepared, request)
}
fn try_admit_query(
&self,
request: hawdb_qos::RuntimeWorkRequest,
) -> std::result::Result<hawdb_qos::RuntimePermit, EmbeddedQueryError> {
admit_query(&self.runtime_governor, request)
}
pub(crate) fn admitted_result_budget_bytes(&self) -> u64 {
crate::api::runtime_result_memory_budget(
self.database.config(),
self.runtime_governor.snapshot().limits.result_budget_bytes,
)
}
fn check_admitted_query_context(
&self,
task_context: &RuntimeTaskContext,
) -> std::result::Result<(), EmbeddedQueryError> {
check_query_context(&self.runtime_governor, task_context)
}
pub fn database(&self) -> &Database {
&self.database
}
pub fn database_mut(&mut self) -> &mut Database {
&mut self.database
}
pub fn configure_search_index(&self, search_index: &mut SearchIndex) {
search_index.set_runtime_capabilities(self.runtime_capabilities());
let config = match self.deployment_profile {
EmbeddedDeploymentProfile::SharedHost => {
SearchRangeReadConfig::shared_host(self.runtime_resources.storage_io)
}
EmbeddedDeploymentProfile::MobileEmbedded => {
SearchRangeReadConfig::mobile_embedded(self.runtime_resources.storage_io)
}
};
search_index.set_range_read_config(config);
}
pub fn into_database(self) -> Database {
self.database
}
pub fn begin_transaction(&mut self) -> Result<()> {
if self.transaction.is_some() {
return Err(HawDBError::Execution(
"a user transaction is already open on this database".into(),
));
}
let (runtime, state) = self.database.transaction_parts()?;
self.transaction = Some(EmbeddedTransaction { runtime, state });
Ok(())
}
pub fn transaction_active(&self) -> bool {
self.transaction.is_some()
}
pub fn transaction_query_with_params(
&mut self,
cypher_text: &str,
parameters: &BTreeMap<String, Value>,
) -> Result<QueryOutput> {
self.transaction_query_request(
crate::QueryRequest::new(cypher_text).with_params(parameters),
)
}
pub fn transaction_query_request(
&mut self,
request: crate::QueryRequest<'_>,
) -> Result<QueryOutput> {
let transaction = self.transaction_mut()?;
let result = crate::api::execute_concurrent_graph_transaction_request(
&transaction.runtime,
&mut transaction.state,
request,
None,
)
.map(|outcome| outcome.output);
if result.is_err() {
transaction.state.fail_read_dependencies();
}
result
}
pub fn transaction_query_sql_with_params(
&mut self,
sql_text: &str,
parameters: &[Value],
) -> Result<QueryOutput> {
self.transaction_query_sql_request(
crate::SqlQueryRequest::new(sql_text).with_params(parameters),
)
}
pub fn transaction_query_sql_request(
&mut self,
request: crate::SqlQueryRequest<'_>,
) -> Result<QueryOutput> {
self.transaction_query_sql_request_with_result(request)
.map(|result| result.output)
}
pub fn transaction_query_sql_with_result_and_params(
&mut self,
sql_text: &str,
parameters: &[Value],
) -> Result<crate::SqlStatementResult> {
self.transaction_query_sql_request_with_result(
crate::SqlQueryRequest::new(sql_text).with_params(parameters),
)
}
pub fn transaction_query_sql_request_with_result(
&mut self,
request: crate::SqlQueryRequest<'_>,
) -> Result<crate::SqlStatementResult> {
let transaction = self.transaction.as_mut().ok_or_else(no_user_transaction)?;
crate::api::execute_recorded_database_transaction_sql_request(
&self.database,
&transaction.runtime,
&mut transaction.state,
request,
None,
)
}
pub fn transaction_query_sql_request_admitted(
&mut self,
request: crate::SqlQueryRequest<'_>,
) -> std::result::Result<QueryOutput, EmbeddedQueryError> {
self.transaction_query_sql_request_admitted_with_result(request)
.map(|result| result.output)
}
pub fn transaction_query_sql_request_admitted_with_result(
&mut self,
query: crate::SqlQueryRequest<'_>,
) -> std::result::Result<crate::SqlStatementResult, EmbeddedQueryError> {
if self.transaction.is_none() {
return Err(no_user_transaction().into());
}
let default_context = RuntimeTaskContext::default();
let context = query.task_context.unwrap_or(&default_context);
self.check_admitted_query_context(context)?;
let planning_request = crate::api::runtime_planning_request(
query.sql.len(),
hawdb_qos::RuntimeWorkPriority::Foreground,
);
let prepared = {
let permit = self.try_admit_query(planning_request)?;
let prepared = self
.database
.runtime_sql_planning_snapshot()
.prepare(query.sql);
self.fail_transaction_on_error(prepared)?
.with_planning_memory(
permit
.into_retained_memory()
.expect("control work owns fixed memory"),
)
};
let admitted_request = prepared.work_request(self.admitted_result_budget_bytes());
let request = admitted_request.with_memory_bytes(
admitted_request
.memory_bytes
.max(planning_request.memory_bytes),
);
let (prepared, permit) = self.try_admit_prepared(prepared, |_, prepared| {
request.with_retained_memory_bytes(
prepared.map_or(0, |value| value.planning_memory_bytes()),
)
})?;
let prepared = match prepared {
Some(prepared) => prepared,
None => {
let prepared = self
.database
.runtime_sql_planning_snapshot()
.prepare(query.sql);
self.fail_transaction_on_error(prepared)?
}
};
if prepared.work_request(admitted_request.result_bytes) != admitted_request {
return Err(HawDBError::Execution(
"SQL admission changed during preparation rebuild; retry the query".into(),
)
.into());
}
let uses_snapshot = prepared.uses_snapshot();
let context = permit.bind_task_context(context.clone());
let _permit = permit;
self.check_admitted_query_context(&context)?;
let (prepared, _planning_memory) = prepared.into_statement(&self.database)?;
let transaction = self.transaction.as_mut().ok_or_else(no_user_transaction)?;
let result = crate::api::execute_recorded_database_transaction_sql_request(
&self.database,
&transaction.runtime,
&mut transaction.state,
query.with_task_context(&context),
Some(prepared),
);
if uses_snapshot {
self.check_admitted_query_context(&context)?;
}
result.map_err(EmbeddedQueryError::Database)
}
fn fail_transaction_on_error<T>(&mut self, result: Result<T>) -> Result<T> {
if result.is_err()
&& let Some(transaction) = &mut self.transaction
{
transaction.state.fail_read_dependencies();
}
result
}
pub fn commit_transaction(&mut self) -> Result<QueryOutput> {
let mut transaction = self.take_transaction()?;
crate::api::commit_database_transaction_state(
&mut self.database,
&mut transaction.state,
false,
)
.map(|result| result.output)
}
pub fn rollback_transaction(&mut self) -> Result<()> {
self.take_transaction()?.state.rollback();
Ok(())
}
pub fn begin_read_transaction(&self) -> Result<DatabaseReadTransaction> {
self.database.begin_read_transaction()
}
fn transaction_mut(&mut self) -> Result<&mut EmbeddedTransaction> {
self.transaction.as_mut().ok_or_else(no_user_transaction)
}
fn take_transaction(&mut self) -> Result<EmbeddedTransaction> {
self.transaction.take().ok_or_else(no_user_transaction)
}
pub fn write_slow_query_log_jsonl(&self, path: impl AsRef<Path>) -> Result<()> {
self.database.write_slow_query_log_jsonl(path)
}
pub fn write_blackbox_report(
&self,
artifact_dir: impl Into<PathBuf>,
output_dir: impl Into<PathBuf>,
run_id: Option<String>,
run_status: BlackboxRunStatus,
exit_code: Option<i64>,
) -> Result<serde_json::Value> {
write_blackbox_report(&BlackboxReportOptions {
artifact_dir: artifact_dir.into(),
output_dir: output_dir.into(),
run_id,
run_status,
exit_code,
})
}
}
#[derive(Debug)]
struct EmbeddedTransaction {
runtime: crate::api::DatabaseTransactionRuntime,
state: crate::api::DatabaseTransactionState,
}
fn no_user_transaction() -> HawDBError {
HawDBError::Execution("no user transaction is open on this database".into())
}
fn default_database_config(profile: EmbeddedDeploymentProfile) -> DatabaseConfig {
match profile {
EmbeddedDeploymentProfile::SharedHost => DatabaseConfig::default(),
EmbeddedDeploymentProfile::MobileEmbedded => DatabaseConfig {
max_read_result_rows: Some(512),
max_optimizer_groups: Some(256),
max_wal_replay_entries: Some(100_000),
max_wal_replay_bytes: Some(128 * 1024 * 1024),
max_wal_record_bytes: Some(4 * 1024 * 1024),
max_wal_batch_operations: Some(25_000),
mutation_limits: hawdb_storage::mutation::MutationLimits {
max_affected_rows: std::num::NonZeroUsize::new(25_000).unwrap(),
max_operations: std::num::NonZeroUsize::new(25_000).unwrap(),
max_result_rows: std::num::NonZeroUsize::new(512).unwrap(),
max_result_payload_bytes: std::num::NonZeroUsize::new(8 * 1024 * 1024).unwrap(),
},
max_checkpoint_encoded_bytes: Some(64 * 1024 * 1024 * 1024),
max_checkpoint_decoded_bytes: Some(256 * 1024 * 1024 * 1024),
segment_cache_capacity_bytes: 32 * 1024 * 1024,
max_search_projection_change_log_entries: Some(512),
max_search_projection_change_log_bytes: Some(8 * 1024 * 1024),
search_projection_relational_change_limits:
hawdb_storage::relational::RelationalPrimaryKeyChangeCaptureLimits {
max_entries: std::num::NonZeroUsize::new(512).unwrap(),
max_bytes: std::num::NonZeroUsize::new(16 * 1024).unwrap(),
},
max_plan_cache_entries: Some(32),
slow_query_log_capacity: 128,
statement_summary_capacity: 128,
runtime_capabilities: RuntimeCapabilities::mobile_embedded()
.intersection(crate::compiled_runtime_capabilities()),
adaptive_vector_backend_policy: AdaptiveVectorBackendPolicy {
flat_scan_max_documents: 512,
flat_scan_memory_budget_bytes: 4 * 1024 * 1024,
..AdaptiveVectorBackendPolicy::default()
},
..DatabaseConfig::default()
},
}
}
fn default_io_budget(
profile: EmbeddedDeploymentProfile,
device: StorageDeviceProfile,
) -> IoConcurrencyBudget {
match profile {
EmbeddedDeploymentProfile::SharedHost => {
IoConcurrencyBudget::shared_host_for_device(device)
}
EmbeddedDeploymentProfile::MobileEmbedded => {
IoConcurrencyBudget::mobile_embedded_for_device(device)
}
}
}
fn default_runtime_governor_config(profile: EmbeddedDeploymentProfile) -> RuntimeGovernorConfig {
match profile {
EmbeddedDeploymentProfile::SharedHost => RuntimeGovernorConfig::shared_host(),
EmbeddedDeploymentProfile::MobileEmbedded => RuntimeGovernorConfig::mobile_embedded(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
GraphMode, HawDBError, ReadinessOptions, RuntimeCapability, Value,
LIBRARY_READINESS_PROTOCOL,
};
use std::collections::BTreeMap;
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicU64, Ordering};
static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);
#[test]
fn embedded_handle_opens_database_and_writes_slow_query_log() {
let root = unique_test_dir("embedded-open");
let db_path = root.join("graph");
let slow_log_path = root.join("slow-query-log.jsonl");
let mut engine = HawDBEmbedded::open_with_options(
HawDBEmbeddedOpenOptions::new(&db_path).with_config(DatabaseConfig {
slow_query_log_threshold_micros: 0,
slow_query_log_capacity: 8,
..DatabaseConfig::default()
}),
)
.unwrap();
engine
.database_mut()
.query("CREATE (:Memory {id: 'm1', title: 'Embedded'})")
.unwrap();
let output = engine
.database_mut()
.query("MATCH (m:Memory {id: 'm1'}) RETURN m.title AS title")
.unwrap();
assert_eq!(
output.rows[0].get("title"),
Some(&Value::String("Embedded".to_string()))
);
engine.write_slow_query_log_jsonl(&slow_log_path).unwrap();
let slow_log = std::fs::read_to_string(slow_log_path).unwrap();
assert!(slow_log.contains("hawdb-slow-query-log-event-v1"));
assert!(slow_log.contains("query_digest"));
assert!(!slow_log.contains("MATCH"));
assert!(!slow_log.contains("m1"));
}
#[test]
fn embedded_handle_opens_store() {
let root = unique_test_dir("embedded-nowledge-mem");
let graph_path = root.join("graph");
let (store, open_report) = HawDBEmbedded::open_embedded_store(
EmbeddedStoreOpenOptions::graph_only(&graph_path, GraphMode::WritableCutover),
)
.unwrap();
let readiness = store
.library_readiness(&ReadinessOptions::default())
.unwrap();
assert_eq!(open_report.mode, GraphMode::WritableCutover);
assert!(open_report.graph_configured);
assert!(open_report.graph_opened);
assert!(!open_report.search_projection_configured);
assert!(!open_report.search_projection_opened);
assert_eq!(readiness.protocol, LIBRARY_READINESS_PROTOCOL);
assert_eq!(readiness.mode, GraphMode::WritableCutover);
assert!(readiness.graph_open);
}
#[test]
fn mobile_profile_uses_bounded_defaults() {
let options = HawDBEmbeddedOpenOptions::mobile("mobile.db");
assert_eq!(
options.deployment_profile,
EmbeddedDeploymentProfile::MobileEmbedded
);
assert_eq!(options.config.max_read_result_rows, Some(512));
assert_eq!(options.config.mutation_limits.max_operations.get(), 25_000);
assert_eq!(
options
.config
.mutation_limits
.max_result_payload_bytes
.get(),
8 * 1024 * 1024
);
assert_eq!(options.config.max_plan_cache_entries, Some(32));
assert_eq!(
options
.config
.adaptive_vector_backend_policy
.flat_scan_memory_budget_bytes,
4 * 1024 * 1024
);
assert_eq!(
options.config.max_search_projection_change_log_entries,
Some(512)
);
assert_eq!(
options.config.max_search_projection_change_log_bytes,
Some(8 * 1024 * 1024)
);
assert!(options.config.runtime_capabilities.full_text_search);
assert!(options.config.runtime_capabilities.vector_search);
assert!(!options.config.runtime_capabilities.graph_analytics);
assert!(!options.config.runtime_capabilities.background_maintenance);
}
#[test]
fn in_memory_open_admits_queries_and_drops_data() {
let mut engine = HawDBEmbedded::open_in_memory();
assert!(engine.is_in_memory());
assert!(engine.path().as_os_str().is_empty());
engine.query_admitted("CREATE (:Memory {id: 1})").unwrap();
let output = engine
.query_admitted("MATCH (m:Memory) RETURN m.id AS id")
.unwrap();
assert_eq!(output.rows.len(), 1);
drop(engine);
let mut reopened = HawDBEmbedded::open_in_memory();
assert!(reopened
.query_admitted("MATCH (m:Memory) RETURN m.id AS id")
.unwrap()
.rows
.is_empty());
}
#[test]
fn in_memory_open_honors_database_config_budgets() {
let mut engine = HawDBEmbedded::open_in_memory_with_config(DatabaseConfig {
max_read_result_rows: Some(1),
..DatabaseConfig::default()
});
engine.query_admitted("CREATE (:Memory {id: 1})").unwrap();
engine.query_admitted("CREATE (:Memory {id: 2})").unwrap();
let error = engine
.query_admitted("MATCH (m:Memory) RETURN m.id AS id")
.unwrap_err();
assert!(
error.to_string().contains("max_read_result_rows"),
"{error}"
);
}
#[test]
fn transaction_commits_own_writes_and_rolls_back() {
let mut engine = HawDBEmbedded::open_in_memory();
engine.begin_transaction().unwrap();
assert!(engine.begin_transaction().is_err());
engine
.transaction_query_with_params("CREATE (:Item {id: 1})", &BTreeMap::new())
.unwrap();
let own_write = engine
.transaction_query_with_params("MATCH (i:Item) RETURN i.id AS id", &BTreeMap::new())
.unwrap();
assert_eq!(own_write.rows.len(), 1);
assert!(engine
.query_admitted("MATCH (i:Item) RETURN i.id AS id")
.is_err());
engine.commit_transaction().unwrap();
let published = engine
.query_admitted("MATCH (i:Item) RETURN i.id AS id")
.unwrap();
assert_eq!(published.rows.len(), 1);
engine.begin_transaction().unwrap();
engine
.transaction_query_with_params("CREATE (:Item {id: 2})", &BTreeMap::new())
.unwrap();
engine.rollback_transaction().unwrap();
let published = engine
.query_admitted("MATCH (i:Item) RETURN i.id AS id")
.unwrap();
assert_eq!(published.rows.len(), 1);
}
fn affected_rows(result: &crate::SqlStatementResult) -> Option<usize> {
result
.mutation
.as_ref()
.map(|mutation| mutation.affected_rows)
}
fn assert_autocommit_sql_reports_affected_rows(engine: &mut HawDBEmbedded) {
let database = engine.database_mut();
let ddl = database
.query_sql_with_result_and_params(
"CREATE TABLE items (id BIGINT PRIMARY KEY, qty BIGINT)",
&[],
)
.unwrap();
assert_eq!(affected_rows(&ddl), None);
let inserted = database
.query_sql_with_result_and_params(
"INSERT INTO items (id, qty) VALUES ($1, 1), ($2, 2), ($3, 3)",
&[Value::Int(1), Value::Int(2), Value::Int(3)],
)
.unwrap();
assert_eq!(affected_rows(&inserted), Some(3));
assert!(!inserted.mutation.as_ref().unwrap().provisional);
assert!(inserted.output.rows.is_empty());
let returning = database
.query_sql_with_result_and_params(
"INSERT INTO items (id, qty) VALUES ($1, 4) RETURNING id",
&[Value::Int(4)],
)
.unwrap();
assert_eq!(affected_rows(&returning), Some(1));
assert_eq!(returning.output.rows.len(), 1);
let updated = database
.query_sql_with_result_and_params(
"UPDATE items SET qty = qty + 10 WHERE qty >= $1",
&[Value::Int(2)],
)
.unwrap();
assert_eq!(affected_rows(&updated), Some(3));
let unmatched = database
.query_sql_with_result_and_params("UPDATE items SET qty = 0 WHERE id = 99", &[])
.unwrap();
assert_eq!(affected_rows(&unmatched), Some(0));
let deleted = database
.query_sql_with_result_and_params("DELETE FROM items WHERE id <= $1", &[Value::Int(2)])
.unwrap();
assert_eq!(affected_rows(&deleted), Some(2));
let selected = database
.query_sql_with_result_and_params("SELECT id FROM items", &[])
.unwrap();
assert_eq!(affected_rows(&selected), None);
assert_eq!(selected.output.rows.len(), 2);
assert!(database
.query_sql_with_params("DELETE FROM items WHERE id = 3", &[])
.unwrap()
.rows
.is_empty());
}
#[test]
fn autocommit_sql_reports_committed_affected_rows() {
assert_autocommit_sql_reports_affected_rows(&mut HawDBEmbedded::open_in_memory());
let mut config = DatabaseConfig::default();
config.mutation_limits.max_affected_rows = NonZeroUsize::new(1_000).unwrap();
assert_autocommit_sql_reports_affected_rows(
&mut HawDBEmbedded::open_in_memory_with_config(config),
);
}
#[test]
fn transaction_sql_reports_provisional_affected_rows() {
let mut engine = HawDBEmbedded::open_in_memory();
engine
.database_mut()
.query_sql("CREATE TABLE items (id BIGINT PRIMARY KEY, qty BIGINT)")
.unwrap();
engine.begin_transaction().unwrap();
let ddl = engine
.transaction_query_sql_with_result_and_params(
"CREATE TABLE other (id BIGINT PRIMARY KEY)",
&[],
)
.unwrap();
assert_eq!(affected_rows(&ddl), None);
let inserted = engine
.transaction_query_sql_with_result_and_params(
"INSERT INTO items (id, qty) VALUES ($1, 1), ($2, 2), ($3, 3)",
&[Value::Int(1), Value::Int(2), Value::Int(3)],
)
.unwrap();
assert_eq!(affected_rows(&inserted), Some(3));
assert!(inserted.mutation.as_ref().unwrap().provisional);
let updated = engine
.transaction_query_sql_with_result_and_params(
"UPDATE items SET qty = 0 WHERE id >= $1",
&[Value::Int(2)],
)
.unwrap();
assert_eq!(affected_rows(&updated), Some(2));
let deleted = engine
.transaction_query_sql_with_result_and_params("DELETE FROM items WHERE id = 1", &[])
.unwrap();
assert_eq!(affected_rows(&deleted), Some(1));
let selected = engine
.transaction_query_sql_with_result_and_params("SELECT id FROM items", &[])
.unwrap();
assert_eq!(affected_rows(&selected), None);
assert_eq!(selected.output.rows.len(), 2);
engine.commit_transaction().unwrap();
assert_eq!(
engine
.database_mut()
.query_sql("SELECT id FROM items")
.unwrap()
.rows
.len(),
2
);
}
#[test]
fn relational_refusals_carry_their_kind_on_both_sql_paths() {
use crate::{RelationalErrorKind, RelationalErrorSurface};
const INSERT: &str = "INSERT INTO items (id, name) VALUES ($1, $2)";
let root = unique_test_dir("embedded-relational-kind");
for mut engine in [
HawDBEmbedded::open_in_memory(),
HawDBEmbedded::open(root.join("graph")).unwrap(),
] {
let database = engine.database_mut();
database
.query_sql_with_params(
"CREATE TABLE items (id BIGINT PRIMARY KEY, name TEXT NOT NULL)",
&[],
)
.unwrap();
database
.query_sql_with_params(INSERT, &[Value::Int(1), Value::String("one".into())])
.unwrap();
for (parameters, kind) in [
(
[Value::Int(1), Value::String("again".into())],
RelationalErrorKind::Constraint,
),
(
[Value::Int(2), Value::Null],
RelationalErrorKind::Constraint,
),
([Value::Int(3), Value::Int(3)], RelationalErrorKind::Schema),
] {
let autocommit = engine
.database_mut()
.query_sql_with_params(INSERT, ¶meters)
.unwrap_err();
assert_eq!(
autocommit.relational_error_kind(),
Some(kind),
"{autocommit:?}"
);
assert_eq!(
autocommit.relational_error_surface(),
Some(RelationalErrorSurface::Storage)
);
assert!(
autocommit
.to_string()
.starts_with(&format!("storage error: {kind}: ")),
"{autocommit}"
);
engine.begin_transaction().unwrap();
let staged = engine
.transaction_query_sql_with_params(INSERT, ¶meters)
.unwrap_err();
engine.rollback_transaction().unwrap();
assert_eq!(staged.relational_error_kind(), Some(kind), "{staged:?}");
assert_eq!(
staged.relational_error_surface(),
Some(RelationalErrorSurface::Execution)
);
assert!(
staged
.to_string()
.starts_with(&format!("execution error: {kind}: ")),
"{staged}"
);
}
let missing = engine
.database_mut()
.query_sql_with_params("SELECT id FROM missing", &[])
.unwrap_err();
assert!(matches!(missing, HawDBError::Semantic(_)), "{missing:?}");
assert_eq!(missing.relational_error_kind(), None);
}
}
fn saturate_admission(engine: &HawDBEmbedded) -> hawdb_qos::RuntimePermit {
let governor = engine.runtime_governor();
governor
.try_admit(
hawdb_qos::RuntimeWorkRequest::new(
hawdb_qos::RuntimeWorkPriority::Foreground,
hawdb_qos::RuntimeWorkKind::Control,
)
.with_cpu_slots(governor.snapshot().limits.effective_cpu_slots.get()),
)
.unwrap()
}
fn assert_retryable_admission<T: fmt::Debug>(
result: std::result::Result<T, EmbeddedQueryError>,
) {
match result {
Err(EmbeddedQueryError::Admission(error)) => {
assert!(error.is_retryable(), "{error}");
assert_eq!(error.code, hawdb_qos::RuntimeAdmissionCode::CpuSaturated);
}
other => panic!("expected a retryable admission refusal, got {other:?}"),
}
}
fn assert_governor_idle(engine: &HawDBEmbedded) {
let snapshot = engine.runtime_governor().snapshot();
assert_eq!(snapshot.admissions, snapshot.completions);
assert_eq!(snapshot.admitted_memory_bytes, 0);
assert_eq!(snapshot.active_cpu_slots, 0);
}
fn sql(text: &str) -> crate::SqlQueryRequest<'_> {
crate::SqlQueryRequest::new(text)
}
#[test]
fn admitted_autocommit_sql_is_refused_when_saturated_and_reports_affected_rows() {
let mut engine = HawDBEmbedded::open_in_memory();
let ddl = engine
.query_sql_request_admitted_with_result(sql(
"CREATE TABLE items (id BIGINT PRIMARY KEY, qty BIGINT)",
))
.unwrap();
assert_eq!(affected_rows(&ddl), None);
let busy = saturate_admission(&engine);
assert_retryable_admission(engine.query_sql_request_admitted_with_result(sql(
"INSERT INTO items (id, qty) VALUES (1, 1)",
)));
assert_retryable_admission(
engine.query_sql_request_admitted_with_result(sql("SELECT id FROM items")),
);
assert_retryable_admission(engine.query_sql_request_admitted_with_result(sql("SELEC")));
drop(busy);
let parameters = [Value::Int(2), Value::Int(3)];
let inserted = engine
.query_sql_request_admitted_with_result(
sql("INSERT INTO items (id, qty) VALUES ($1, 10), ($2, 20)")
.with_params(¶meters),
)
.unwrap();
assert_eq!(affected_rows(&inserted), Some(2));
assert!(!inserted.mutation.as_ref().unwrap().provisional);
let updated = engine
.query_sql_request_admitted_with_result(sql("UPDATE items SET qty = 0 WHERE id = 3"))
.unwrap();
assert_eq!(affected_rows(&updated), Some(1));
let selected = engine
.query_sql_request_admitted_with_result(sql("SELECT id FROM items ORDER BY id"))
.unwrap();
assert_eq!(affected_rows(&selected), None);
assert_eq!(
selected
.output
.rows
.iter()
.map(|row| row["id"].clone())
.collect::<Vec<_>>(),
[Value::Int(2), Value::Int(3)]
);
assert_governor_idle(&engine);
}
#[test]
fn admitted_transaction_sql_is_refused_when_saturated_and_keeps_the_transaction() {
let mut engine = HawDBEmbedded::open_in_memory();
assert!(matches!(
engine.transaction_query_sql_request_admitted_with_result(sql("SELECT 1")),
Err(EmbeddedQueryError::Database(HawDBError::Execution(_)))
));
engine
.query_sql_request_admitted(sql(
"CREATE TABLE items (id BIGINT PRIMARY KEY, qty BIGINT)",
))
.unwrap();
engine.begin_transaction().unwrap();
let first = engine
.transaction_query_sql_request_admitted_with_result(sql(
"INSERT INTO items (id, qty) VALUES (1, 1)",
))
.unwrap();
assert_eq!(affected_rows(&first), Some(1));
assert!(first.mutation.as_ref().unwrap().provisional);
let busy = saturate_admission(&engine);
assert_retryable_admission(
engine.transaction_query_sql_request_admitted_with_result(sql(
"INSERT INTO items (id, qty) VALUES (2, 2)",
)),
);
assert_retryable_admission(
engine.transaction_query_sql_request_admitted_with_result(sql("SELECT id FROM items")),
);
drop(busy);
let cancellation = hawdb_core::RuntimeCancellationToken::new();
cancellation.cancel();
let cancelled = RuntimeTaskContext::without_deadline(cancellation);
assert_eq!(
engine
.transaction_query_sql_request_admitted_with_result(
sql("INSERT INTO items (id, qty) VALUES (3, 3)").with_task_context(&cancelled),
)
.unwrap_err(),
EmbeddedQueryError::Stopped(RuntimeCancellationReason::Cancelled)
);
assert!(engine.transaction_active());
let updated = engine
.transaction_query_sql_request_admitted_with_result(sql(
"UPDATE items SET qty = 5 WHERE id >= 0",
))
.unwrap();
assert_eq!(affected_rows(&updated), Some(1));
let selected = engine
.transaction_query_sql_request_admitted(sql("SELECT id, qty FROM items"))
.unwrap();
assert_eq!(selected.rows.len(), 1);
engine.commit_transaction().unwrap();
let published = engine
.query_sql_request_admitted(sql("SELECT id, qty FROM items"))
.unwrap();
assert_eq!(published.rows.len(), 1);
assert_eq!(published.rows[0]["qty"], Value::Int(5));
assert_governor_idle(&engine);
}
#[test]
fn admitted_sql_result_budget_follows_the_governor_and_names_the_read_ceiling() {
const CEILING: usize = 24 * 1024 * 1024;
let config = DatabaseConfig {
max_read_result_payload_bytes: Some(CEILING),
..DatabaseConfig::default()
};
let mut governor = RuntimeGovernorConfig::shared_host();
governor.result_budget_bytes = CEILING as u64;
let mut engine =
HawDBEmbedded::open_in_memory_with_runtime_governor_config(config, Some(governor));
assert_eq!(engine.admitted_result_budget_bytes(), CEILING as u64);
engine
.query_sql_request_admitted(sql("CREATE TABLE big (id BIGINT PRIMARY KEY, v TEXT)"))
.unwrap();
let value = Value::String("x".repeat(100_000));
for batch in 0..4 {
engine.begin_transaction().unwrap();
for id in 0..50 {
let parameters = [Value::Int(batch * 50 + id), value.clone()];
engine
.transaction_query_sql_request_admitted(
sql("INSERT INTO big (id, v) VALUES ($1, $2)").with_params(¶meters),
)
.unwrap();
}
engine.commit_transaction().unwrap();
}
const WITHIN: &str = "SELECT id, v FROM big";
const BEYOND: &str = "SELECT id, v, v AS w FROM big";
let assert_ceiling =
|result: std::result::Result<QueryOutput, EmbeddedQueryError>| match result {
Err(EmbeddedQueryError::Database(HawDBError::ReadBudgetExceeded(budget))) => {
assert_eq!(budget.resource, crate::ReadBudgetResource::PayloadBytes);
assert_eq!(budget.limit, CEILING);
assert_eq!(
budget.resource.budget_option(),
"max_read_result_payload_bytes"
);
}
other => panic!("expected the read payload ceiling, got {other:?}"),
};
assert_eq!(
engine
.query_sql_request_admitted(sql(WITHIN))
.unwrap()
.rows
.len(),
200
);
assert_ceiling(engine.query_sql_request_admitted(sql(BEYOND)));
engine.begin_transaction().unwrap();
assert_eq!(
engine
.transaction_query_sql_request_admitted(sql(WITHIN))
.unwrap()
.rows
.len(),
200
);
assert_ceiling(engine.transaction_query_sql_request_admitted(sql(BEYOND)));
engine.rollback_transaction().unwrap();
assert_governor_idle(&engine);
}
#[test]
fn admitted_branch_catalog_sql_does_not_wait_for_a_busy_runtime() {
let path = unique_test_dir("embedded-admitted-branch-catalog").join("graph");
let mut writer = HawDBEmbedded::open(&path).unwrap();
writer
.query_admitted("CREATE (:Memory {id: 'kept'})")
.unwrap();
let mut reader = HawDBEmbedded::open(&path).unwrap();
assert!(reader
.query_admitted("MATCH (m:Memory) RETURN m.id")
.is_err());
let catalog = reader
.query_sql_request_admitted(sql("SHOW BRANCHES LIMIT 1"))
.unwrap();
assert_eq!(catalog.rows.len(), 1);
drop(writer);
assert_eq!(
reader
.query_sql_request_admitted(sql("SHOW BRANCHES LIMIT 1"))
.unwrap(),
catalog
);
}
fn statement_summary(
engine: &mut HawDBEmbedded,
query_text: &str,
) -> Option<(String, i64, i64, i64, i64)> {
let parameters = [Value::String(query_text.into())];
let output = engine
.database_mut()
.query_sql_with_params(
"SELECT statement_kind, execution_count, success_count, error_count, \
total_row_count FROM system.statement_summary \
WHERE query_language = 'sql' AND query_text = $1",
¶meters,
)
.unwrap();
assert!(output.rows.len() <= 1, "{output:?}");
output.rows.first().map(|row| {
let int = |name: &str| match &row[name] {
Value::Int(value) => *value,
other => panic!("{name}: {other:?}"),
};
let Value::String(kind) = &row["statement_kind"] else {
panic!("{row:?}");
};
(
kind.clone(),
int("execution_count"),
int("success_count"),
int("error_count"),
int("total_row_count"),
)
})
}
#[test]
fn transaction_and_admitted_sql_are_recorded_like_autocommit_sql() {
const INSERT: &str = "INSERT INTO items (id, qty) VALUES ($1, $2)";
const TX_SELECT: &str = "SELECT id FROM items WHERE qty >= 0";
const ADMITTED_SELECT: &str = "SELECT id, qty FROM items";
let mut engine = HawDBEmbedded::open_in_memory_with_config(DatabaseConfig {
slow_query_log_threshold_micros: 0,
slow_query_log_capacity: 64,
statement_summary_capacity: 64,
..DatabaseConfig::default()
});
engine
.database_mut()
.query_sql("CREATE TABLE items (id BIGINT PRIMARY KEY, qty BIGINT)")
.unwrap();
let slow_before = engine.database().slow_query_log_snapshot().len();
engine.begin_transaction().unwrap();
engine
.transaction_query_sql_with_params(INSERT, &[Value::Int(1), Value::Int(1)])
.unwrap();
engine
.transaction_query_sql_request_admitted(
sql(INSERT).with_params(&[Value::Int(2), Value::Int(2)]),
)
.unwrap();
engine
.transaction_query_sql_with_params(INSERT, &[Value::Int(1), Value::Int(9)])
.unwrap_err();
let staged = engine
.transaction_query_sql_request_admitted(sql(TX_SELECT))
.unwrap();
assert_eq!(staged.rows.len(), 2);
engine
.transaction_query_sql_with_params("SELEC", &[])
.unwrap_err();
engine.commit_transaction().unwrap();
let admitted = engine
.query_sql_request_admitted(sql(ADMITTED_SELECT))
.unwrap();
assert_eq!(admitted.rows.len(), 2);
assert_eq!(
statement_summary(&mut engine, INSERT),
Some(("insert".into(), 3, 2, 1, 0))
);
assert_eq!(
statement_summary(&mut engine, TX_SELECT),
Some(("select".into(), 1, 1, 0, 2))
);
assert_eq!(
statement_summary(&mut engine, ADMITTED_SELECT),
Some(("select".into(), 1, 1, 0, 2))
);
assert_eq!(statement_summary(&mut engine, "SELEC"), None);
let slow = engine.database().slow_query_log_snapshot();
let recorded = &slow[slow_before..];
let count = |kind: &str| {
recorded
.iter()
.filter(|record| record.query_language == "sql" && record.statement_kind == kind)
.count()
};
assert_eq!(count("insert"), 2, "{recorded:?}");
assert!(count("select") >= 2, "{recorded:?}");
assert!(recorded.iter().all(|record| record.success));
}
#[test]
fn transaction_sql_fails_closed_on_a_poisoned_handle() {
let mut engine = HawDBEmbedded::open_in_memory();
engine
.database_mut()
.query_sql("CREATE TABLE items (id BIGINT PRIMARY KEY, qty BIGINT)")
.unwrap();
engine.begin_transaction().unwrap();
engine
.transaction_query_sql_with_params("INSERT INTO items (id, qty) VALUES (1, 1)", &[])
.unwrap();
engine.database().poison_storage_handle_for_test();
assert!(engine.database().storage_handle_poisoned().unwrap());
let poisoned = |error: &HawDBError| matches!(error, HawDBError::Storage(message) if message.contains("poisoned"));
let read = engine
.transaction_query_sql_with_params("SELECT id FROM items", &[])
.unwrap_err();
assert!(poisoned(&read), "{read:?}");
let write = engine
.transaction_query_sql_with_params("INSERT INTO items (id, qty) VALUES (2, 2)", &[])
.unwrap_err();
assert!(poisoned(&write), "{write:?}");
match engine.transaction_query_sql_request_admitted(sql("SELECT id FROM items")) {
Err(EmbeddedQueryError::Database(error)) => assert!(poisoned(&error), "{error:?}"),
other => panic!("expected the poisoned handle, got {other:?}"),
}
engine.rollback_transaction().unwrap();
let autocommit = engine
.query_sql_request_admitted(sql("SELECT id FROM items"))
.unwrap_err();
assert!(
matches!(&autocommit, EmbeddedQueryError::Database(error) if poisoned(error)),
"{autocommit:?}"
);
}
#[test]
fn read_transaction_rejects_writes() {
let mut engine = HawDBEmbedded::open_in_memory();
engine.query_admitted("CREATE (:Item {id: 1})").unwrap();
let mut read = engine.begin_read_transaction().unwrap();
let output = read.query("MATCH (i:Item) RETURN i.id AS id").unwrap();
assert_eq!(output.rows.len(), 1);
assert!(read.query("CREATE (:Item {id: 2})").is_err());
}
#[test]
fn query_path_readiness_rejects_raw_database_access() {
let raw = HawDBEmbedded::raw_database_query_path_readiness();
assert_eq!(raw.protocol, EMBEDDED_QUERY_PATH_READINESS_PROTOCOL);
assert_eq!(raw.entrypoint, EmbeddedQueryEntrypoint::RawDatabase);
assert!(!raw.admission_safe);
assert!(raw.blockers.contains(&"runtime_governor_not_enforced"));
assert!(raw
.blockers
.contains(&"host_equivalent_governor_not_proven"));
}
#[test]
fn admitted_sync_queries_hold_runtime_governor_permits() {
let root = unique_test_dir("embedded-admitted-query");
let mut engine = HawDBEmbedded::open(root.join("graph")).unwrap();
engine
.query_admitted("CREATE (:Memory {id: 'admitted'})")
.unwrap();
let output = engine
.query_admitted("MATCH (m:Memory) RETURN m.id AS id")
.unwrap();
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("admitted".to_string()))
);
let snapshot = engine.runtime_governor().snapshot();
assert_eq!(snapshot.admissions, 4);
assert_eq!(snapshot.completions, 4);
assert_eq!(snapshot.admitted_memory_bytes, 0);
assert!(engine.admitted_query_path_readiness().admission_safe);
}
#[test]
fn admitted_owned_reads_preserve_output_limits_and_release_permits() {
let payload_column = "c".repeat(2048);
let payload_boundary = 4 * (payload_column.len() + 8);
for (row_limit, payload_limit, should_succeed, resource) in [
(Some(1), None, false, hawdb_core::ReadBudgetResource::Rows),
(Some(2), None, true, hawdb_core::ReadBudgetResource::Rows),
(
None,
Some(payload_boundary - 1),
false,
hawdb_core::ReadBudgetResource::PayloadBytes,
),
(
None,
Some(payload_boundary * 4),
true,
hawdb_core::ReadBudgetResource::PayloadBytes,
),
] {
let mut engine = HawDBEmbedded::open_in_memory_with_config(DatabaseConfig {
max_read_result_rows: row_limit,
max_read_result_payload_bytes: payload_limit,
..DatabaseConfig::default()
});
let row_count = if payload_limit.is_some() { 4 } else { 2 };
let column = if payload_limit.is_some() {
payload_column.as_str()
} else {
"id"
};
for id in 1..=row_count {
engine
.database_mut()
.query_with_params(
"CREATE (:Item {id: $id})",
&BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap();
}
let result = engine.query_admitted(&format!(
"MATCH (n:Item) RETURN n.id AS {column} ORDER BY {column}"
));
if should_succeed {
let output = result.unwrap();
assert_eq!(output.rows.len(), row_count as usize);
for (index, row) in output.rows.iter().enumerate() {
assert_eq!(row.get(column), Some(&Value::Int(index as i64 + 1)));
}
} else {
let error = match result {
Err(EmbeddedQueryError::Database(HawDBError::ReadBudgetExceeded(error))) => {
error
}
actual => panic!("expected a typed output budget refusal, got {actual:?}"),
};
assert_eq!(error.resource, resource);
assert_eq!(error.limit, row_limit.or(payload_limit).unwrap());
}
let retry = engine
.query_with_params_admitted(
"MATCH (n:Item) WHERE n.id = $id RETURN n.id AS id",
&BTreeMap::from([("id".into(), Value::Int(2))]),
)
.unwrap();
assert_eq!(retry.rows.len(), 1);
assert_eq!(retry.rows[0].get("id"), Some(&Value::Int(2)));
let governor = engine.runtime_governor().snapshot();
assert_eq!(governor.admissions, governor.completions);
assert_eq!(governor.admitted_memory_bytes, 0);
assert_eq!(governor.active_cpu_slots, 0);
}
for payload_limit in [19, 20] {
let mut engine = HawDBEmbedded::open_in_memory_with_config(DatabaseConfig {
max_read_result_payload_bytes: Some(payload_limit),
..DatabaseConfig::default()
});
engine
.database_mut()
.query("CREATE (:Item {id: 1})")
.unwrap();
let error = engine
.query_admitted("MATCH (n:Item) RETURN n.id AS id")
.unwrap_err();
let EmbeddedQueryError::Database(HawDBError::ResourceBudgetExceeded(cause)) = &error
else {
panic!("expected a typed result-memory refusal, got {error:?}");
};
assert_eq!(cause.resource, crate::ResourceBudgetKind::MemoryBytes);
assert_eq!(cause.scope, crate::ResourceBudgetScope::Account);
assert_eq!(cause.owner, "query result");
assert_eq!(cause.memory_class, Some("result_materialization"));
assert_eq!(cause.budget, payload_limit as u64);
assert_eq!(
cause.budget_option,
"RuntimeTaskContext.memory_reservation.result_bytes"
);
assert!(cause.requested > cause.budget.saturating_sub(cause.used));
assert!(error.to_string().contains("result_materialization"));
let governor = engine.runtime_governor().snapshot();
assert_eq!(governor.admissions, governor.completions);
assert_eq!(governor.admitted_memory_bytes, 0);
assert_eq!(governor.active_cpu_slots, 0);
}
}
#[test]
fn simple_scan_projection_borrows_input_and_preserves_owned_values() {
let mut engine = HawDBEmbedded::open_in_memory();
let nested = Value::Map(BTreeMap::from([(
"entries".into(),
Value::List(vec![Value::Int(7), Value::Null, Value::Bool(true)]),
)]));
for id in [1, 2] {
engine
.database_mut()
.query_with_params(
"CREATE (:Item {id: $id, title: $title, nested: $nested})",
&BTreeMap::from([
("id".into(), Value::Int(id)),
("title".into(), Value::String(format!("item-{id}\0"))),
("nested".into(), nested.clone()),
]),
)
.unwrap();
}
let mut read = engine.database().begin_read_transaction().unwrap();
let output = read.query_with_params_bounded_profile(
"MATCH (n:Item) RETURN n.id AS id, n.title AS title, n.nested AS nested, n.optional AS optional, id(n) AS node_id, 1 AS constant ORDER BY id",
&BTreeMap::new(),
None,
).unwrap();
assert_eq!(
output
.execution_profile
.pipeline_memory_report
.borrowed_node_projection_rows,
2
);
assert_eq!(output.output.rows.len(), 2);
for (ordinal, id) in [1, 2].into_iter().enumerate() {
let row = &output.output.rows[ordinal];
assert_eq!(row.get("id"), Some(&Value::Int(id)));
assert_eq!(
row.get("title"),
Some(&Value::String(format!("item-{id}\0")))
);
assert_eq!(row.get("nested"), Some(&nested));
assert_eq!(row.get("optional"), Some(&Value::Null));
assert_eq!(row.get("node_id"), Some(&Value::Int(ordinal as i64)));
assert_eq!(row.get("constant"), Some(&Value::Int(1)));
}
let fallback = read
.query_with_params_bounded_profile(
"MATCH (n:Item) RETURN n.title AS title, n.id + 1 AS next_id ORDER BY next_id",
&BTreeMap::new(),
None,
)
.unwrap();
assert_eq!(
fallback
.execution_profile
.pipeline_memory_report
.borrowed_node_projection_rows,
0
);
assert_eq!(fallback.output.rows[0].get("next_id"), Some(&Value::Int(2)));
assert_eq!(fallback.output.rows[1].get("next_id"), Some(&Value::Int(3)));
}
#[test]
fn admitted_sync_point_reads_share_cache_and_rebind_parameters() {
let mut engine = HawDBEmbedded::open_in_memory();
engine.query_admitted("CREATE INDEX ON :Item(id)").unwrap();
for id in 0..20 {
engine
.query_with_params_admitted(
"CREATE (:Item {id: $id, score: $score})",
&BTreeMap::from([
("id".into(), Value::Int(id)),
("score".into(), Value::Int(id * 3)),
]),
)
.unwrap();
}
let query = "MATCH (n:Item) WHERE n.id = $id RETURN n.id AS id, n.score AS score";
let before = engine.database().plan_cache_stats().unwrap();
for (iteration, id) in [5, 17, 3].into_iter().enumerate() {
let output = engine
.query_with_params_admitted(query, &BTreeMap::from([("id".into(), Value::Int(id))]))
.unwrap();
assert_eq!(output.rows.len(), 1);
assert_eq!(output.rows[0].get("id"), Some(&Value::Int(id)));
assert_eq!(output.rows[0].get("score"), Some(&Value::Int(id * 3)));
let cache = engine.database().plan_cache_stats().unwrap();
assert_eq!(cache.misses, before.misses + 1);
assert_eq!(cache.hits, before.hits + iteration as u64);
}
let mut old = engine
.database()
.begin_read_transaction_with_shared_plan_cache()
.unwrap();
engine
.query_admitted("CREATE (:Item {id: 31, score: 93})")
.unwrap();
let parameters = BTreeMap::from([("id".into(), Value::Int(31))]);
let output = engine
.query_with_params_admitted(query, ¶meters)
.unwrap();
assert_eq!(output.rows.len(), 1);
assert_eq!(output.rows[0].get("score"), Some(&Value::Int(93)));
assert!(old
.query_with_params(query, ¶meters)
.unwrap()
.rows
.is_empty());
engine
.query_admitted("CREATE INDEX ON :Item(score)")
.unwrap();
let before_schema_read = engine.database().plan_cache_stats().unwrap();
let output = engine
.query_with_params_admitted(query, ¶meters)
.unwrap();
assert_eq!(output.rows[0].get("score"), Some(&Value::Int(93)));
let after_schema_read = engine.database().plan_cache_stats().unwrap();
assert_eq!(after_schema_read.misses, before_schema_read.misses + 1);
assert_eq!(after_schema_read.hits, before_schema_read.hits);
let old_output = old
.query_with_params(query, &BTreeMap::from([("id".into(), Value::Int(5))]))
.unwrap();
assert_eq!(old_output.rows[0].get("score"), Some(&Value::Int(15)));
let governor = engine.runtime_governor().snapshot();
assert_eq!(governor.admissions, governor.completions);
assert_eq!(governor.admitted_memory_bytes, 0);
assert_eq!(governor.active_cpu_slots, 0);
}
#[test]
fn admitted_sync_point_reads_honor_disabled_cache_and_parameter_errors() {
let mut engine = HawDBEmbedded::open_in_memory_with_config(DatabaseConfig {
max_plan_cache_entries: Some(0),
..DatabaseConfig::default()
});
engine.query_admitted("CREATE (:Item {id: 1})").unwrap();
let query = "MATCH (n:Item) WHERE n.id = $id RETURN n.id AS id";
let before = engine.database().plan_cache_stats().unwrap();
let output = engine
.query_with_params_admitted(query, &BTreeMap::from([("id".into(), Value::Int(1))]))
.unwrap();
assert_eq!(output.rows[0].get("id"), Some(&Value::Int(1)));
let cache = engine.database().plan_cache_stats().unwrap();
assert_eq!(cache.entries, 0);
assert_eq!(cache.disabled_misses, before.disabled_misses + 1);
assert!(matches!(
engine.query_with_params_admitted(query, &BTreeMap::new()),
Err(EmbeddedQueryError::Database(_))
));
let governor = engine.runtime_governor().snapshot();
assert_eq!(governor.admissions, governor.completions);
assert_eq!(governor.admitted_memory_bytes, 0);
assert_eq!(governor.active_cpu_slots, 0);
}
#[test]
fn admitted_sync_cache_observes_index_cost_class_changes() {
let mut engine = HawDBEmbedded::open_in_memory();
engine.query_admitted("CREATE INDEX ON :Item(id)").unwrap();
for id in 0..8 {
engine
.query_with_params_admitted(
"CREATE (:Item {id: $id})",
&BTreeMap::from([("id".into(), Value::Int(id))]),
)
.unwrap();
}
let query = "MATCH (n:Item) WHERE n.id = $id RETURN n.id AS id";
let parameters = BTreeMap::from([("id".into(), Value::Int(3))]);
engine
.query_with_params_admitted(query, ¶meters)
.unwrap();
let before_growth = engine.database().plan_cache_stats().unwrap();
engine.query_admitted("CREATE (:Item {id: 8})").unwrap();
let output = engine
.query_with_params_admitted(query, ¶meters)
.unwrap();
assert_eq!(output.rows[0].get("id"), Some(&Value::Int(3)));
let after_growth = engine.database().plan_cache_stats().unwrap();
assert_eq!(after_growth.misses, before_growth.misses + 1);
assert_eq!(after_growth.hits, before_growth.hits);
let governor = engine.runtime_governor().snapshot();
assert_eq!(governor.admissions, governor.completions);
assert_eq!(governor.admitted_memory_bytes, 0);
}
#[test]
fn admitted_sync_queries_do_not_cache_current_timestamps() {
let mut engine = HawDBEmbedded::open_in_memory();
engine.query_admitted("CREATE (:Item {id: 1})").unwrap();
let before = engine.database().plan_cache_stats().unwrap();
for _ in 0..3 {
let output = engine
.query_admitted("MATCH (n:Item) RETURN CASE WHEN true THEN CURRENT_TIMESTAMP() ELSE 0 END AS now")
.unwrap();
assert!(matches!(output.rows[0].get("now"), Some(Value::Int(value)) if *value > 0));
}
let after = engine.database().plan_cache_stats().unwrap();
assert_eq!(after.entries, before.entries);
assert_eq!(after.bypasses, before.bypasses + 3);
let governor = engine.runtime_governor().snapshot();
assert_eq!(governor.admissions, governor.completions);
assert_eq!(governor.admitted_memory_bytes, 0);
}
#[test]
fn sync_queries_rebuild_preparation_when_only_execution_fits() {
for sql in [false, true] {
let mut engine = HawDBEmbedded::open_in_memory_with_config(DatabaseConfig {
max_read_result_payload_bytes: Some(4096),
..DatabaseConfig::default()
});
engine
.database_mut()
.query("CREATE (:Item {value: 7})")
.unwrap();
engine
.database_mut()
.query_sql("CREATE TABLE rows (id BIGINT PRIMARY KEY)")
.unwrap();
engine
.database_mut()
.query_sql("INSERT INTO rows (id) VALUES (7)")
.unwrap();
let cypher = "MATCH (n:Item) RETURN n.value AS value";
let sql_text = "SELECT id AS value FROM rows";
let request = if sql {
engine
.database
.runtime_sql_planning_snapshot()
.prepare(sql_text)
.unwrap()
.work_request(engine.admitted_result_budget_bytes())
} else {
engine
.database
.prepare_runtime_request(crate::QueryRequest::new(cypher))
.unwrap()
.admission()
.runtime_work_request_for_snapshot(
engine.admitted_result_budget_bytes(),
engine.runtime_governor.snapshot(),
)
};
let capacity = request.memory_bytes.max(1024 * 1024) + request.result_bytes;
engine.runtime_governor = RuntimeGovernor::new(
RuntimeGovernorConfig {
memory_budget_bytes: Some(capacity),
..RuntimeGovernorConfig::shared_host()
},
engine.runtime_governor.snapshot().resources,
hawdb_qos::IoConcurrencyBudget::new(2, 1),
);
engine
.database
.set_runtime_governor(engine.runtime_governor.clone());
let output = if sql {
engine.query_sql_request_admitted(crate::SqlQueryRequest::new(sql_text))
} else {
engine.query_admitted(cypher)
}
.unwrap();
assert_eq!(output.rows[0]["value"], Value::Int(7));
assert_eq!(engine.runtime_governor.snapshot().admitted_memory_bytes, 0);
assert_eq!(engine.runtime_governor.snapshot().active_cpu_slots, 0);
}
}
#[test]
fn saturated_sync_admission_rejects_before_parsing() {
let root = unique_test_dir("embedded-planning-gate");
let mut engine = HawDBEmbedded::open(root.join("graph")).unwrap();
let governor = engine.runtime_governor().clone();
let busy = governor
.try_admit(
hawdb_qos::RuntimeWorkRequest::new(
hawdb_qos::RuntimeWorkPriority::Foreground,
hawdb_qos::RuntimeWorkKind::Control,
)
.with_cpu_slots(governor.snapshot().limits.effective_cpu_slots.get()),
)
.unwrap();
let malformed = "MATCH (";
assert!(matches!(
engine.query_admitted(malformed),
Err(EmbeddedQueryError::Admission(_))
));
drop(busy);
assert!(matches!(
engine.query_admitted(malformed),
Err(EmbeddedQueryError::Database(_))
));
let snapshot = governor.snapshot();
assert_eq!(snapshot.admitted_memory_bytes, 0);
assert_eq!(snapshot.active_cpu_slots, 0);
assert_eq!(snapshot.admissions, snapshot.completions);
}
#[test]
fn admitted_sync_query_rejects_before_mutation_when_memory_is_unavailable() {
let root = unique_test_dir("embedded-admission-reject");
let governor = RuntimeGovernorConfig {
memory_budget_bytes: Some(1),
..RuntimeGovernorConfig::default()
};
let mut engine = HawDBEmbedded::open_with_options(
HawDBEmbeddedOpenOptions::new(root.join("graph"))
.with_runtime_governor_config(governor),
)
.unwrap();
let error = engine
.query_admitted("CREATE (:Memory {id: 'rejected'})")
.unwrap_err();
assert!(matches!(
error,
EmbeddedQueryError::Admission(RuntimeAdmissionError {
code: hawdb_qos::RuntimeAdmissionCode::MemorySaturated,
retryable: false,
..
})
));
assert!(engine
.database_mut()
.query("MATCH (m:Memory) RETURN m.id AS id")
.unwrap()
.rows
.is_empty());
}
#[test]
fn admitted_sync_query_reports_pre_execution_cancellation() {
let root = unique_test_dir("embedded-admission-cancel");
let mut engine = HawDBEmbedded::open(root.join("graph")).unwrap();
let cancellation = hawdb_core::RuntimeCancellationToken::new();
cancellation.cancel();
let context = RuntimeTaskContext::without_deadline(cancellation);
let error = engine
.query_with_params_admitted_context("RETURN 1", &BTreeMap::new(), &context)
.unwrap_err();
assert_eq!(
error,
EmbeddedQueryError::Stopped(RuntimeCancellationReason::Cancelled)
);
let snapshot = engine.runtime_governor().snapshot();
assert_eq!(snapshot.admissions, 0);
assert_eq!(snapshot.cancellations, 1);
}
#[test]
fn host_can_override_mobile_runtime_capabilities() {
let options = HawDBEmbeddedOpenOptions::mobile("mobile.db").with_runtime_capabilities(
RuntimeCapabilities::mobile_embedded()
.with(crate::RuntimeCapability::GraphAnalytics, true),
);
assert!(options.config.runtime_capabilities.graph_analytics);
assert!(!options.config.runtime_capabilities.background_maintenance);
}
#[test]
fn explicit_storage_io_budget_overrides_profile_default() {
let root = unique_test_dir("embedded-io-budget");
let storage_device = StorageDeviceProfile::host_provided(
hawdb_qos::StorageMediaKind::Rotational,
NonZeroUsize::new(1),
);
let options = HawDBEmbeddedOpenOptions::mobile(root.join("graph"))
.with_storage_device_profile(storage_device)
.with_storage_io_budget(IoConcurrencyBudget::new(7, 2));
let engine = HawDBEmbedded::open_with_options(options).unwrap();
assert_eq!(
engine.deployment_profile(),
EmbeddedDeploymentProfile::MobileEmbedded
);
assert_eq!(engine.runtime_resources().storage_device, storage_device);
assert_eq!(
engine.runtime_resources().storage_io.foreground_depth.get(),
7
);
assert_eq!(
engine.runtime_resources().storage_io.background_depth.get(),
2
);
assert_eq!(
engine
.runtime_resources()
.foreground_segment_read_scheduler(NonZeroU64::new(1 << 20).unwrap())
.schedule([])
.io_depth
.get(),
7
);
let mut search_index = SearchIndex::in_memory();
engine.configure_search_index(&mut search_index);
assert_eq!(
search_index.runtime_capabilities(),
RuntimeCapabilities::mobile_embedded()
);
assert_eq!(search_index.range_read_config().io_depth.get(), 7);
assert_eq!(
search_index.range_read_config().max_wave_bytes.get(),
2 * 1024 * 1024
);
}
#[test]
fn device_profile_drives_default_io_budget_without_cpu_inference() {
let root = unique_test_dir("embedded-device-profile");
let storage_device = StorageDeviceProfile::host_provided(
hawdb_qos::StorageMediaKind::NonRotational,
NonZeroUsize::new(12),
);
let engine = HawDBEmbedded::open_with_options(
HawDBEmbeddedOpenOptions::new(root.join("graph"))
.with_storage_device_profile(storage_device),
)
.unwrap();
assert_eq!(engine.runtime_resources().storage_device, storage_device);
assert_eq!(
engine.runtime_resources().storage_io,
IoConcurrencyBudget::new(12, 3)
);
}
#[test]
fn embedded_governor_applies_adaptive_resource_updates() {
let root = unique_test_dir("embedded-adaptive-runtime");
let initial = RuntimeResourceSnapshot::from_parts(
RuntimeResourceBudget::from_limits(NonZeroUsize::new(4).unwrap(), None, None),
RuntimeMemorySnapshot::from_limits(
Some(8_u64 << 30),
Some(4_u64 << 30),
None,
None,
None,
),
);
let mut engine = HawDBEmbedded::open_with_options(
HawDBEmbeddedOpenOptions::new(root.join("graph"))
.with_resource_snapshot(initial)
.with_storage_io_budget(IoConcurrencyBudget::new(8, 2)),
)
.unwrap();
assert_eq!(
engine
.runtime_governor()
.snapshot()
.limits
.effective_cpu_slots
.get(),
4
);
let constrained = RuntimeResourceSnapshot::from_parts(
RuntimeResourceBudget::from_limits(
NonZeroUsize::new(8).unwrap(),
NonZeroUsize::new(1),
NonZeroUsize::new(2),
),
RuntimeMemorySnapshot::from_limits(
Some(8_u64 << 30),
Some(256_u64 << 20),
Some(1_u64 << 30),
Some(768_u64 << 20),
Some(600_u64 << 20),
),
);
assert!(engine.update_runtime_resources(constrained));
let snapshot = engine.runtime_governor().snapshot();
assert_eq!(snapshot.limits.effective_cpu_slots.get(), 1);
assert_eq!(snapshot.resources.memory.pressure.as_str(), "elevated");
assert_eq!(
engine.runtime_resources().cpu.effective_parallelism.get(),
1
);
assert_eq!(engine.runtime_resources().memory, constrained.memory);
assert_eq!(snapshot.pressure_adjustments, 1);
}
#[test]
fn shared_host_and_mobile_profiles_share_storage_and_core_cypher_semantics() {
let root = unique_test_dir("embedded-profile-compatibility");
let graph_path = root.join("graph");
let storage_version = {
let mut shared_host = HawDBEmbedded::open(&graph_path).unwrap();
shared_host
.database_mut()
.query("CREATE NODE TABLE Memory")
.unwrap();
shared_host
.database_mut()
.query("CREATE PROPERTY ON NODE TABLE Memory(id) TYPE STRING NOT NULL")
.unwrap();
shared_host
.database_mut()
.query_with_params(
"CREATE (:Memory {id: $id, title: $title})",
&BTreeMap::from([
("id".to_string(), Value::String("desktop".to_string())),
(
"title".to_string(),
Value::String("Written on desktop".to_string()),
),
]),
)
.unwrap();
shared_host.database().storage_version()
};
{
let mut mobile =
HawDBEmbedded::open_with_options(HawDBEmbeddedOpenOptions::mobile(&graph_path))
.unwrap();
assert_eq!(mobile.database().storage_version(), storage_version);
let output = mobile
.database_mut()
.query_with_params(
"MATCH (m:Memory) WHERE m.id = $id RETURN m.title AS title",
&BTreeMap::from([("id".to_string(), Value::String("desktop".to_string()))]),
)
.unwrap();
assert_eq!(
output.rows[0].get("title"),
Some(&Value::String("Written on desktop".to_string()))
);
let error = mobile
.database_mut()
.query("CALL project_graph('memory_graph', ['Memory'], [])")
.unwrap_err();
assert_eq!(
error,
HawDBError::CapabilityUnavailable {
capability: RuntimeCapability::GraphAnalytics
}
);
mobile
.database_mut()
.query_with_params(
"CREATE (:Memory {id: $id, title: $title})",
&BTreeMap::from([
("id".to_string(), Value::String("mobile".to_string())),
(
"title".to_string(),
Value::String("Written on mobile".to_string()),
),
]),
)
.unwrap();
}
let mut shared_host = HawDBEmbedded::open(&graph_path).unwrap();
let output = shared_host
.database_mut()
.query("MATCH (m:Memory) RETURN m.id AS id ORDER BY id ASC")
.unwrap();
assert_eq!(
output
.rows
.iter()
.map(|row| row.get("id").cloned())
.collect::<Vec<_>>(),
vec![
Some(Value::String("desktop".to_string())),
Some(Value::String("mobile".to_string())),
]
);
}
fn unique_test_dir(prefix: &str) -> PathBuf {
let id = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir().join(format!("hawdb-{prefix}-{}-{id}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
}