use super::{QueryAccessControlContext, QueryStreamOptions};
use crate::{HawDBError, Result, Value};
use hawdb_core::graph_rag::{ScoringProgram, ScoringProgramShape};
use hawdb_plan_cypher::{
visit_plan, PhysicalPlan, ScoringSeedGraphInput, SCORING_RERANK_SCORE_COLUMN,
};
use std::collections::BTreeMap;
mod budget;
mod host;
mod owned;
mod sql;
pub use budget::{BudgetedReadSnapshot, ReadSnapshotBudget, ReadSnapshotUsage};
pub use host::HostScoringRequest;
pub use owned::{OwnedHostScoringRequest, OwnedQueryRequest, OwnedSqlQueryRequest};
pub use sql::SqlQueryRequest;
#[derive(Clone, Copy)]
pub(super) enum ScoringAttachment<'a> {
Program(&'a ScoringRequest),
Host {
plan: &'a hawdb_plan_cypher::HostScoringPlan,
candidate_window: bool,
reference_time_millis: Option<u64>,
provider: &'a dyn hawdb_executor::scoring::HostScorerProvider,
},
}
impl<'a> ScoringAttachment<'a> {
pub(super) fn bind(self) -> BoundScoringRequest<'a> {
match self {
Self::Program(request) => request.bind(),
Self::Host {
reference_time_millis,
..
} => BoundScoringRequest {
request: self,
reference_time_millis: reference_time_millis
.unwrap_or_else(hawdb_executor::scoring::reference_time_millis),
},
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScoringRequest {
program: ScoringProgram,
score_column: String,
limit: usize,
candidate_window: bool,
seed_graph_input: Option<ScoringSeedGraphInput>,
reference_time_millis: Option<u64>,
}
impl ScoringRequest {
pub fn new(
program: ScoringProgram,
score_column: impl Into<String>,
limit: usize,
) -> Result<Self> {
let score_column = score_column.into();
if score_column.is_empty()
|| score_column.contains('\0')
|| score_column == SCORING_RERANK_SCORE_COLUMN
{
return Err(HawDBError::Semantic(
"scoring requires a nonempty input score column distinct from its result column"
.into(),
));
}
Ok(Self {
program,
score_column,
limit,
candidate_window: false,
seed_graph_input: None,
reference_time_millis: None,
})
}
pub fn with_candidate_window(mut self) -> Self {
self.candidate_window = true;
self
}
pub fn with_reference_time_millis(mut self, time: u64) -> Self {
self.reference_time_millis = Some(time);
self
}
pub fn with_vector_graph_input(
mut self,
seed_variable: impl Into<String>,
candidate_variable: impl Into<String>,
) -> Result<Self> {
self.seed_graph_input = Some(ScoringSeedGraphInput::new(
seed_variable,
candidate_variable,
)?);
Ok(self)
}
pub fn with_text_graph_input(
mut self,
seed_variable: impl Into<String>,
candidate_variable: impl Into<String>,
) -> Result<Self> {
self.seed_graph_input = Some(ScoringSeedGraphInput::new_text(
seed_variable,
candidate_variable,
)?);
Ok(self)
}
pub fn with_graph_seed_input(
mut self,
seed_variable: impl Into<String>,
candidate_variable: impl Into<String>,
) -> Result<Self> {
self.seed_graph_input = Some(ScoringSeedGraphInput::new_graph(
seed_variable,
candidate_variable,
)?);
Ok(self)
}
pub fn program(&self) -> &ScoringProgram {
&self.program
}
pub(super) fn bind(&self) -> BoundScoringRequest<'_> {
BoundScoringRequest {
request: ScoringAttachment::Program(self),
reference_time_millis: self
.reference_time_millis
.unwrap_or_else(hawdb_executor::scoring::reference_time_millis),
}
}
}
#[derive(Clone, Copy)]
pub struct QueryRequest<'a> {
pub(crate) cypher: &'a str,
pub(crate) parameters: Option<&'a BTreeMap<String, Value>>,
pub(super) scoring: Option<ScoringAttachment<'a>>,
pub(super) access_control: Option<&'a QueryAccessControlContext>,
pub(crate) task_context: Option<&'a hawdb_core::RuntimeTaskContext>,
pub(crate) output_limits: QueryStreamOptions,
}
impl<'a> QueryRequest<'a> {
pub fn new(cypher: &'a str) -> Self {
Self {
cypher,
parameters: None,
scoring: None,
access_control: None,
task_context: None,
output_limits: QueryStreamOptions::default(),
}
}
pub fn with_params(mut self, parameters: &'a BTreeMap<String, Value>) -> Self {
self.parameters = Some(parameters);
self
}
pub fn with_scoring(mut self, scoring: &'a ScoringRequest) -> Self {
self.scoring = Some(ScoringAttachment::Program(scoring));
self
}
pub fn with_host_scoring(mut self, scoring: &'a HostScoringRequest<'_>) -> Self {
self.scoring = Some(ScoringAttachment::Host {
plan: &scoring.plan,
candidate_window: scoring.candidate_window,
reference_time_millis: scoring.reference_time_millis,
provider: scoring,
});
self
}
pub fn with_access_control(mut self, access: &'a QueryAccessControlContext) -> Self {
self.access_control = Some(access);
self
}
pub fn with_task_context(mut self, context: &'a hawdb_core::RuntimeTaskContext) -> Self {
self.task_context = Some(context);
self
}
pub fn with_output_limits(mut self, limits: QueryStreamOptions) -> Self {
self.output_limits = limits;
self
}
pub(crate) fn with_restrictive_output_limits(mut self, limits: QueryStreamOptions) -> Self {
self.output_limits = QueryStreamOptions {
max_rows: super::restrictive_query_limit(self.output_limits.max_rows, limits.max_rows),
max_payload_bytes: super::restrictive_query_limit(
self.output_limits.max_payload_bytes,
limits.max_payload_bytes,
),
};
self
}
}
pub(crate) fn bind_request_context(
parent: Option<&hawdb_core::RuntimeTaskContext>,
request: Option<&hawdb_core::RuntimeTaskContext>,
) -> Result<Option<hawdb_core::RuntimeTaskContext>> {
match (parent, request) {
(Some(parent), Some(request)) => parent.constrained_by(request).map(Some),
(Some(parent), None) => Ok(Some(parent.clone())),
(None, request) => Ok(request.cloned()),
}
}
#[derive(Clone, Copy)]
pub(super) struct BoundScoringRequest<'a> {
request: ScoringAttachment<'a>,
reference_time_millis: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(super) enum ScoringPlanCacheKey {
Program(ScoringProgramCacheKey),
Host {
plan: hawdb_plan_cypher::HostScoringPlan,
candidate_window: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(super) struct ScoringProgramCacheKey {
program: ScoringProgramShape,
score_column: String,
limit: usize,
candidate_window: bool,
seed_graph_input: Option<ScoringSeedGraphInput>,
}
impl<'a> BoundScoringRequest<'a> {
pub(super) fn cache_key(self) -> ScoringPlanCacheKey {
match self.request {
ScoringAttachment::Program(request) => {
ScoringPlanCacheKey::Program(ScoringProgramCacheKey {
program: request.program.shape(),
score_column: request.score_column.clone(),
limit: request.limit,
candidate_window: request.candidate_window,
seed_graph_input: request.seed_graph_input.clone(),
})
}
ScoringAttachment::Host {
plan,
candidate_window,
..
} => ScoringPlanCacheKey::Host {
plan: plan.clone(),
candidate_window,
},
}
}
pub(super) fn host_scorer(self) -> Option<&'a dyn hawdb_executor::scoring::HostScorerProvider> {
match self.request {
ScoringAttachment::Program(_) => None,
ScoringAttachment::Host { provider, .. } => Some(provider),
}
}
pub(super) fn attach_template(self, input: PhysicalPlan) -> Result<PhysicalPlan> {
if hawdb_executor::mutation::is_mutation_plan(&input)? {
return Err(HawDBError::Semantic("scoring requires a read query".into()));
}
if hawdb_executor::batch::BatchPlanRef::try_new(&input).is_none() {
return Err(crate::executor::unsupported_scoring_input_error());
}
let (candidate_window, seed_graph_input) = match self.request {
ScoringAttachment::Program(request) => {
(request.candidate_window, request.seed_graph_input.as_ref())
}
ScoringAttachment::Host {
plan,
candidate_window,
..
} => (candidate_window, plan.seed_graph_input()),
};
if !candidate_window {
let mut windowed = false;
visit_plan(&input, &mut |node| {
windowed |= matches!(
node,
PhysicalPlan::LimitExec { offset, limit, .. }
if *offset != 0 || limit.is_some()
) || matches!(node, PhysicalPlan::TopNExec { .. });
});
if windowed {
return Err(HawDBError::Semantic(
"scoring a query with LIMIT/OFFSET requires an explicit candidate window"
.into(),
));
}
}
if let Some(source) = seed_graph_input {
source.validate_plan(&input)?;
}
Ok(match self.request {
ScoringAttachment::Program(request) => PhysicalPlan::ScoringProgramExec {
score_column: request.score_column.clone(),
seed_graph_input: request.seed_graph_input.clone(),
program: request.program.neutral_template(),
reference_time_millis: 0,
limit: request.limit,
input: Box::new(input),
},
ScoringAttachment::Host { plan, .. } => PhysicalPlan::HostScoringExec {
scoring: plan.clone(),
reference_time_millis: 0,
input: Box::new(input),
},
})
}
pub(super) fn rebind(self, plan: &mut PhysicalPlan) -> Result<()> {
let ScoringAttachment::Program(request) = self.request else {
let ScoringAttachment::Host { plan: expected, .. } = self.request else {
unreachable!()
};
let PhysicalPlan::HostScoringExec {
scoring,
reference_time_millis,
..
} = plan
else {
return Err(HawDBError::Execution(
"cached host scoring plan is missing its scoring operator".into(),
));
};
if scoring != expected {
return Err(HawDBError::Execution(
"cached host scoring plan has a different scoring identity or structure".into(),
));
}
*reference_time_millis = self.reference_time_millis;
return Ok(());
};
let PhysicalPlan::ScoringProgramExec {
score_column,
seed_graph_input,
program,
reference_time_millis,
limit,
..
} = plan
else {
return Err(HawDBError::Execution(
"cached scoring plan is missing its scoring operator".into(),
));
};
if *seed_graph_input != request.seed_graph_input
|| *score_column != request.score_column
|| *limit != request.limit
|| program.shape() != request.program.shape()
{
return Err(HawDBError::Execution(
"cached scoring plan has a different scoring structure".into(),
));
}
*program = request.program.clone();
*reference_time_millis = self.reference_time_millis;
Ok(())
}
}
impl<S: crate::executor::ExecutionStore> super::DatabaseReadTransaction<S> {
pub fn query_request(&mut self, request: QueryRequest<'_>) -> Result<super::QueryOutput> {
self.query_request_profiled(request)
.map(|result| result.output)
}
pub fn query_request_profiled(
&mut self,
request: QueryRequest<'_>,
) -> Result<super::BoundedReadQueryOutput> {
self.query_request_profiled_with_external(
request,
&mut crate::executor::NoExternalReadOperator,
)
}
pub(crate) fn query_request_profiled_with_external(
&mut self,
request: QueryRequest<'_>,
external: &mut dyn crate::executor::ExternalReadOperator,
) -> Result<super::BoundedReadQueryOutput> {
let task_context = bind_request_context(self.task_context.as_ref(), request.task_context)?;
let request = QueryRequest {
task_context: task_context.as_ref(),
..request
};
let options = super::query_runtime::QueryExecutionOptions::for_request(request, None);
let prepared = super::query_runtime::parse_runtime_execution(request.cypher)?;
self.query_prepared_request_profiled(
request.cypher,
prepared,
request.parameters.unwrap_or(&BTreeMap::new()),
options,
external,
)
}
pub fn query_request_streaming(
&mut self,
request: QueryRequest<'_>,
consumer: impl FnMut(crate::executor::Row) -> Result<()>,
) -> Result<super::QueryStreamReport> {
self.query_request_streaming_with_external(
request,
&mut crate::executor::NoExternalReadOperator,
consumer,
)
}
pub fn query_request_streaming_with_external(
&mut self,
request: QueryRequest<'_>,
external: &mut dyn crate::executor::ExternalReadOperator,
mut consumer: impl FnMut(crate::executor::Row) -> Result<()>,
) -> Result<super::QueryStreamReport> {
let task_context = bind_request_context(self.task_context.as_ref(), request.task_context)?;
let request = QueryRequest {
task_context: task_context.as_ref(),
..request
};
let options = super::query_runtime::QueryExecutionOptions::for_request(request, None);
self.query_request_streaming_prepared_external(
request,
super::query_runtime::parse_runtime_execution(request.cypher)?,
options,
external,
&mut consumer,
)
}
fn query_request_streaming_prepared_external(
&mut self,
request: QueryRequest<'_>,
prepared: super::query_runtime::PreparedRuntimeExecution,
options: super::query_runtime::QueryExecutionOptions<'_>,
external: &mut dyn crate::executor::ExternalReadOperator,
consumer: &mut impl FnMut(crate::executor::Row) -> Result<()>,
) -> Result<super::QueryStreamReport> {
let empty = BTreeMap::new();
self.query_with_params_streaming_prepared_external_internal(
request.cypher,
prepared,
request.parameters.unwrap_or(&empty),
options.output_limits,
super::ReadStreamingExecutionContext {
task_context: options.task_context,
external: Some(external),
delivery: crate::executor::StreamDelivery::Validated,
scoring: options.scoring,
access_control: options.access_control,
},
crate::executor::QueryStreamConsumer::Owned(consumer),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
Database, DecayTerm, MissingScoringFeature, ScoreFeature, ScoringCombination, ScoringSpec,
ScoringTerm,
};
pub(super) const QUERY: &str = "MATCH (m:Memory) WHERE m.kind = $kind RETURN m.id AS id, m.seed AS score, m.importance AS importance, m.created AS created ORDER BY id";
#[test]
fn snapshot_request_collects_compact_rows_with_owned_result_accounting() {
let mut database = Database::new();
let parameters = BTreeMap::from([(
"rows".into(),
Value::List(
(0..2_048)
.map(|id| {
Value::Map(BTreeMap::from([
("id".into(), Value::Int(id)),
("title".into(), Value::String("payload".into())),
]))
})
.collect(),
),
)]);
database
.query_with_params(
"UNWIND $rows AS row CREATE (:Sample {id: row.id, title: row.title})",
¶meters,
)
.unwrap();
let mut snapshot = database.begin_read_transaction().unwrap();
let request = QueryRequest::new(
"MATCH (n:Sample) RETURN n.id AS id, n.title AS title, n.absent AS missing",
)
.with_output_limits(QueryStreamOptions {
max_rows: Some(2_048),
max_payload_bytes: Some(256 * 1_024),
});
let compact = snapshot.query_request_profiled(request).unwrap();
assert_eq!(compact.output.rows.len(), 2_048);
let mut ids = std::collections::BTreeSet::new();
for row in &compact.output.rows {
let Some(Value::Int(id)) = row.get("id") else {
panic!("missing integer id")
};
assert!((0..2_048).contains(id));
assert!(ids.insert(*id));
assert_eq!(row.get("title"), Some(&Value::String("payload".into())));
assert_eq!(row.get("missing"), Some(&Value::Null));
}
let mut delivered = 0;
let streamed = snapshot
.query_request_streaming(request, |row| {
assert_eq!(compact.output.rows[delivered], row);
delivered += 1;
Ok(())
})
.unwrap();
assert_eq!(delivered, 2_048);
let owned_memory = &compact.execution_profile.pipeline_memory_report;
let stream_memory = &streamed.execution_profile.pipeline_memory_report;
assert!(owned_memory.query_memory_completion_bytes > 0);
assert_eq!(stream_memory.query_memory_completion_bytes, 0);
assert!(owned_memory.query_memory_peak_bytes < stream_memory.query_memory_peak_bytes);
assert_eq!(
owned_memory.output_payload_bytes,
stream_memory.output_payload_bytes
);
for limits in [
QueryStreamOptions {
max_rows: Some(2_047),
max_payload_bytes: Some(256 * 1_024),
},
QueryStreamOptions {
max_rows: Some(2_048),
max_payload_bytes: Some(1),
},
] {
assert!(snapshot
.query_request(request.with_output_limits(limits))
.is_err());
}
assert_eq!(snapshot.query_request(request).unwrap().rows.len(), 2_048);
}
pub(super) fn fixture() -> Database {
let mut database = Database::new_with_config(crate::DatabaseConfig {
runtime_capabilities: hawdb_core::RuntimeCapabilities::default().with(
hawdb_core::RuntimeCapability::AccessControl,
cfg!(feature = "acl"),
),
..crate::DatabaseConfig::default()
});
for statement in [
"CREATE (:Memory {id: 'early', kind: 'x', seed: 1.0, importance: 0.1, created: 1000, space_id: 'a'})",
"CREATE (:Memory {id: 'late', kind: 'x', seed: 0.2, importance: 1.0, created: 2000, space_id: 'b'})",
"CREATE (:Memory {id: 'other', kind: 'y', seed: 0.8, importance: 0.8, created: 1000, space_id: 'a'})",
] {
database.query(statement).unwrap();
}
database
}
pub(super) fn parameters(kind: &str) -> BTreeMap<String, Value> {
BTreeMap::from([("kind".into(), Value::String(kind.into()))])
}
pub(super) fn scoring(
combination: ScoringCombination,
search: f64,
importance: f64,
) -> ScoringRequest {
ScoringRequest::new(
ScoringProgram::new(
combination,
MissingScoringFeature::Reject,
ScoringSpec {
terms: vec![
ScoringTerm {
feature: ScoreFeature::SearchScore,
weight: search,
},
ScoringTerm {
feature: ScoreFeature::NodeProperty("importance".into()),
weight: importance,
},
],
decay: vec![DecayTerm {
feature: ScoreFeature::TimestampProperty("created".into()),
half_life: 1.0,
min_factor: 0.0,
}],
},
)
.unwrap(),
"score",
1,
)
.unwrap()
}
#[test]
fn ordinary_scoring_rebinds_coefficients_clock_and_query_parameters_on_cache_hits() {
let mut database = fixture();
let x = parameters("x");
let first =
scoring(ScoringCombination::WeightedSum, 1.0, 0.0).with_reference_time_millis(1_000);
let before = database.plan_cache_stats().unwrap();
let output = database
.query_request(
QueryRequest::new(QUERY)
.with_params(&x)
.with_scoring(&first),
)
.unwrap();
assert_eq!(output.rows.len(), 1);
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("early".into()))
);
assert_eq!(
output.rows[0].get(SCORING_RERANK_SCORE_COLUMN),
Some(&Value::Float(1.0))
);
let after_first = database.plan_cache_stats().unwrap();
assert_eq!(after_first.misses, before.misses + 1);
let rebound =
scoring(ScoringCombination::WeightedSum, 0.0, 1.0).with_reference_time_millis(2_000);
let output = database
.query_request(
QueryRequest::new(QUERY)
.with_params(&x)
.with_scoring(&rebound),
)
.unwrap();
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("late".into()))
);
assert_eq!(
output.rows[0].get(SCORING_RERANK_SCORE_COLUMN),
Some(&Value::Float(1.0))
);
assert_eq!(
database.plan_cache_stats().unwrap().hits,
after_first.hits + 1
);
let y = parameters("y");
let output = database
.query_request(
QueryRequest::new(QUERY)
.with_params(&y)
.with_scoring(&rebound),
)
.unwrap();
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("other".into()))
);
let Some(Value::Float(score)) = output.rows[0].get(SCORING_RERANK_SCORE_COLUMN) else {
panic!("missing combined score")
};
assert_eq!(score.to_bits(), 0.4f64.to_bits());
assert_eq!(
database.plan_cache_stats().unwrap().hits,
after_first.hits + 2
);
let explain = database
.query_request(
QueryRequest::new(&format!("EXPLAIN {QUERY}"))
.with_params(&y)
.with_scoring(&rebound),
)
.unwrap();
let rendered = format!("{:?}", explain.rows[0]);
assert!(rendered.contains("ScoringProgramExec"), "{rendered}");
assert!(rendered.contains("WeightedSum"), "{rendered}");
assert!(rendered.contains("weight: 0.0"), "{rendered}");
let Some(Value::Map(cost)) = explain.rows[0].get("selected_plan_cost") else {
panic!("missing scoring plan cost")
};
assert_eq!(cost.get("estimated_rows"), Some(&Value::Int(1)));
assert!(matches!(cost.get("cost"), Some(Value::Int(value)) if *value > 0));
let Some(Value::List(cardinalities)) = explain.rows[0].get("operator_cardinalities") else {
panic!("missing scoring cardinalities")
};
let scoring_estimate = cardinalities.iter().find_map(|value| match value {
Value::Map(estimate)
if estimate.get("operator")
== Some(&Value::String("ScoringProgramExec".into())) =>
{
Some(estimate)
}
_ => None,
});
assert_eq!(
scoring_estimate.and_then(|estimate| estimate.get("estimated_rows")),
Some(&Value::Int(1))
);
}
#[test]
fn ordinary_scoring_cache_separates_programs_from_each_other_and_unscored_queries() {
let mut database = fixture();
let params = parameters("x");
let sum =
scoring(ScoringCombination::WeightedSum, 2.0, 1.0).with_reference_time_millis(2_000);
let product = scoring(ScoringCombination::WeightedProduct, 2.0, 1.0)
.with_reference_time_millis(2_000);
let before = database.plan_cache_stats().unwrap();
let sum_rows = database
.query_request(
QueryRequest::new(QUERY)
.with_params(¶ms)
.with_scoring(&sum),
)
.unwrap();
assert_eq!(
sum_rows.rows[0].get("id"),
Some(&Value::String("late".into()))
);
let product_rows = database
.query_request(
QueryRequest::new(QUERY)
.with_params(¶ms)
.with_scoring(&product),
)
.unwrap();
assert_eq!(
product_rows.rows[0].get("id"),
Some(&Value::String("early".into()))
);
let ordinary = database.query_with_params(QUERY, ¶ms).unwrap();
assert_eq!(ordinary.rows.len(), 2);
assert!(ordinary
.rows
.iter()
.all(|row| row.get(SCORING_RERANK_SCORE_COLUMN).is_none()));
assert_eq!(
database.plan_cache_stats().unwrap().misses,
before.misses + 3
);
}
#[test]
fn ordinary_scoring_preserves_only_explicit_candidate_windows_and_rejects_writes() {
let mut database = fixture();
let params = parameters("x");
let score =
scoring(ScoringCombination::WeightedSum, 0.0, 1.0).with_reference_time_millis(2_000);
let query = "MATCH (m:Memory) WHERE m.kind = $kind RETURN m.id AS id, m.seed AS score, m.importance AS importance, m.created AS created ORDER BY score DESC LIMIT 1";
assert!(matches!(
database.query_request(
QueryRequest::new(query)
.with_params(¶ms)
.with_scoring(&score)
),
Err(HawDBError::Semantic(_))
));
let windowed = score.clone().with_candidate_window();
let output = database
.query_request(
QueryRequest::new(query)
.with_params(¶ms)
.with_scoring(&windowed),
)
.unwrap();
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("early".into()))
);
assert!(matches!(
database.query_request(
QueryRequest::new(query)
.with_params(¶ms)
.with_scoring(&score)
),
Err(HawDBError::Semantic(_))
));
assert!(matches!(
database.query_request(
QueryRequest::new("CREATE (:Memory {id: 'rejected'})").with_scoring(&score)
),
Err(HawDBError::Semantic(_))
));
assert!(database
.query("MATCH (m:Memory) WHERE m.id = 'rejected' RETURN m.id AS id")
.unwrap()
.rows
.is_empty());
}
#[test]
fn snapshot_scoring_preserves_authorization_and_validated_budget_cancellation() {
let database = fixture();
let mut snapshot = database.begin_read_transaction().unwrap();
let params = parameters("x");
let score =
scoring(ScoringCombination::WeightedSum, 0.0, 1.0).with_reference_time_millis(2_000);
let access = QueryAccessControlContext::visibility_scope(7, "space_id", "a");
let request = QueryRequest::new(QUERY)
.with_params(¶ms)
.with_scoring(&score);
#[cfg(feature = "acl")]
let request = request.with_access_control(&access);
#[cfg(not(feature = "acl"))]
assert!(matches!(
snapshot.query_request(request.with_access_control(&access)),
Err(HawDBError::CapabilityUnavailable { .. })
));
let output = snapshot.query_request(request).unwrap();
assert_eq!(output.rows.len(), 1);
#[cfg(feature = "acl")]
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("early".into()))
);
let mut delivered = 0;
let result = snapshot.query_request_streaming(
request.with_output_limits(QueryStreamOptions {
max_rows: Some(1),
max_payload_bytes: Some(1),
}),
|_| {
delivered += 1;
Ok(())
},
);
assert!(result.is_err());
assert_eq!(
delivered, 0,
"validate result payload before the consumer boundary"
);
let two = ScoringRequest::new(score.program().clone(), "score", 2)
.unwrap()
.with_reference_time_millis(2_000);
let result = snapshot.query_request_streaming(
QueryRequest::new(QUERY)
.with_params(¶ms)
.with_scoring(&two)
.with_output_limits(QueryStreamOptions {
max_rows: Some(1),
max_payload_bytes: None,
}),
|_| {
delivered += 1;
Ok(())
},
);
assert!(
result.is_err(),
"output caps must reject rather than truncate scoring K"
);
assert_eq!(delivered, 0);
let token = hawdb_core::RuntimeCancellationToken::new();
let context = hawdb_core::RuntimeTaskContext::without_deadline(token.clone());
token.cancel();
let result = snapshot.query_request_streaming(request.with_task_context(&context), |_| {
delivered += 1;
Ok(())
});
assert!(result.is_err());
assert_eq!(delivered, 0, "cancelled scoring requests deliver no rows");
}
#[test]
fn snapshot_scoring_explain_rebinds_and_analyze_obeys_request_boundaries() {
let database = fixture();
let mut snapshot = database.begin_read_transaction().unwrap();
let params = parameters("x");
let score =
scoring(ScoringCombination::WeightedSum, 1.0, 0.0).with_reference_time_millis(1_000);
let cypher = format!("EXPLAIN {QUERY}");
let request = QueryRequest::new(&cypher)
.with_params(¶ms)
.with_scoring(&score);
let output = snapshot.query_request(request).unwrap();
let rendered = format!("{:?}", output.rows[0]);
assert!(rendered.contains("ScoringProgramExec"), "{rendered}");
assert!(
rendered.contains("reference_time_millis=1000"),
"{rendered}"
);
let before = snapshot.plan_cache_stats();
let rebound =
scoring(ScoringCombination::WeightedSum, 0.0, 1.0).with_reference_time_millis(2_000);
let output = snapshot
.query_request(request.with_scoring(&rebound))
.unwrap();
let rendered = format!("{:?}", output.rows[0]);
assert!(
rendered.contains("reference_time_millis=2000"),
"{rendered}"
);
assert!(rendered.contains("weight: 0.0"), "{rendered}");
assert_eq!(snapshot.plan_cache_stats().hits, before.hits + 1);
let cypher = format!("EXPLAIN ANALYZE {QUERY}");
let request = QueryRequest::new(&cypher)
.with_params(¶ms)
.with_scoring(&rebound);
let output = snapshot.query_request(request).unwrap();
assert_eq!(output.rows[0].get("row_count"), Some(&Value::Int(1)));
assert!(snapshot
.query_request(request.with_output_limits(QueryStreamOptions {
max_rows: Some(1),
max_payload_bytes: Some(1),
}))
.is_err());
let token = hawdb_core::RuntimeCancellationToken::new();
let context = hawdb_core::RuntimeTaskContext::without_deadline(token.clone());
token.cancel();
assert!(snapshot
.query_request(request.with_task_context(&context))
.is_err());
}
fn assert_explain_report_limit(snapshot: bool, analyze: bool, payload: bool) {
let mut database = fixture();
let params = parameters("x");
let program = scoring(ScoringCombination::WeightedSum, 1.0, 0.0)
.program()
.clone();
let scoring = ScoringRequest::new(program, "score", 0)
.unwrap()
.with_reference_time_millis(2_000);
let cypher = format!("EXPLAIN {}{QUERY}", if analyze { "ANALYZE " } else { "" });
let request = QueryRequest::new(&cypher)
.with_params(¶ms)
.with_scoring(&scoring);
let limits = QueryStreamOptions {
max_rows: (!payload).then_some(0),
max_payload_bytes: payload.then_some(1),
};
let result = if snapshot {
let mut transaction = database.begin_read_transaction().unwrap();
let output = transaction.query_request(request).unwrap();
assert_eq!(output.rows.len(), 1);
assert!(output.payload_bytes() > 1);
if analyze {
assert_eq!(output.rows[0].get("row_count"), Some(&Value::Int(0)));
}
transaction.query_request(request.with_output_limits(limits))
} else {
let output = database.query_request(request).unwrap();
assert_eq!(output.rows.len(), 1);
assert!(output.payload_bytes() > 1);
if analyze {
assert_eq!(output.rows[0].get("row_count"), Some(&Value::Int(0)));
}
database.query_request(request.with_output_limits(limits))
};
let expected = if payload {
(crate::ReadBudgetResource::PayloadBytes, 1)
} else {
(crate::ReadBudgetResource::Rows, 0)
};
assert!(
matches!(result, Err(HawDBError::ReadBudgetExceeded(cause))
if (cause.resource, cause.limit) == expected),
"report bypassed its output limit: snapshot={snapshot}, analyze={analyze}, payload={payload}"
);
}
#[test]
fn database_explain_respects_final_report_rows() {
assert_explain_report_limit(false, false, false);
}
#[test]
fn database_explain_respects_final_report_payload() {
assert_explain_report_limit(false, false, true);
}
#[test]
fn database_explain_analyze_respects_final_report_rows() {
assert_explain_report_limit(false, true, false);
}
#[test]
fn database_explain_analyze_respects_final_report_payload() {
assert_explain_report_limit(false, true, true);
}
#[test]
fn snapshot_explain_respects_final_report_rows() {
assert_explain_report_limit(true, false, false);
}
#[test]
fn snapshot_explain_respects_final_report_payload() {
assert_explain_report_limit(true, false, true);
}
#[test]
fn snapshot_explain_analyze_respects_final_report_rows() {
assert_explain_report_limit(true, true, false);
}
#[test]
fn snapshot_explain_analyze_respects_final_report_payload() {
assert_explain_report_limit(true, true, true);
}
fn assert_session_explain_report_limit(analyze: bool, payload: bool) {
let mut database = fixture();
let cypher = format!(
"EXPLAIN {}MATCH (m:Memory) WHERE m.kind = 'missing' RETURN m.id AS id",
if analyze { "ANALYZE " } else { "" }
);
let output = database.session().query(&cypher).unwrap();
assert_eq!(output.rows.len(), 1);
assert!(output.payload_bytes() > 1);
if analyze {
assert_eq!(output.rows[0].get("row_count"), Some(&Value::Int(0)));
}
database.config.max_read_result_rows = (!payload).then_some(0);
database.config.max_read_result_payload_bytes = payload.then_some(1);
if !payload {
assert_eq!(database.session().query(&cypher).unwrap().rows.len(), 1);
return;
}
let expected = (crate::ReadBudgetResource::PayloadBytes, 1);
assert!(
matches!(database.session().query(&cypher), Err(HawDBError::ReadBudgetExceeded(cause))
if (cause.resource, cause.limit) == expected),
"session report bypassed its configured output limit: analyze={analyze}, payload={payload}"
);
}
#[test]
fn session_explain_zero_row_setting_is_unlimited() {
assert_session_explain_report_limit(false, false);
}
#[test]
fn session_explain_respects_final_report_payload() {
assert_session_explain_report_limit(false, true);
}
#[test]
fn session_explain_analyze_zero_row_setting_is_unlimited() {
assert_session_explain_report_limit(true, false);
}
#[test]
fn session_explain_analyze_respects_final_report_payload() {
assert_session_explain_report_limit(true, true);
}
}
#[cfg(test)]
#[path = "query_request/provenance_tests.rs"]
mod provenance_tests;
#[cfg(all(test, feature = "full-text-search"))]
#[path = "query_request/text_provenance_tests.rs"]
mod text_provenance_tests;
#[cfg(test)]
#[path = "query_request/graph_seed_tests.rs"]
mod graph_seed_tests;
#[cfg(test)]
#[path = "query_request/expansion_budget_tests.rs"]
mod expansion_budget_tests;
#[cfg(test)]
#[path = "query_request/adapter_tests.rs"]
mod adapter_tests;
#[cfg(test)]
#[path = "query_request/budget_tests.rs"]
mod budget_tests;
impl hawdb_core::RetainedHeapBytes for ScoringPlanCacheKey {
fn retained_heap_bytes(&self) -> Option<usize> {
match self {
Self::Program(value0) => hawdb_core::checked_retained_heap_sum([
hawdb_core::RetainedHeapBytes::retained_heap_bytes(value0),
]),
Self::Host {
plan,
candidate_window,
} => hawdb_core::checked_retained_heap_sum([
hawdb_core::RetainedHeapBytes::retained_heap_bytes(plan),
hawdb_core::RetainedHeapBytes::retained_heap_bytes(candidate_window),
]),
}
}
}
hawdb_core::impl_retained_heap_for_struct!(ScoringProgramCacheKey {
program,
score_column,
limit,
candidate_window,
seed_graph_input
});