use super::super::relational_query_limits_with_payload;
use super::*;
#[test]
fn relational_index_read_row_budget_matches_intermediate_limit() {
let config = DatabaseConfig {
max_read_result_rows: Some(4_097),
..DatabaseConfig::default()
};
let limits = relational_query_limits_with_payload(&config, None, None);
assert_eq!(limits.max_intermediate_rows, 4_097);
assert_eq!(limits.index_read.max_rows.get(), 4_097);
assert_eq!(
limits.index_read.max_pages.get(),
4_097usize.saturating_mul(
hawdb_storage::relational::DEFAULT_RELATIONAL_INDEX_READ_TREE_HEIGHT as usize
)
);
assert_eq!(
limits.index_read.max_bytes.get(),
limits
.index_read
.max_pages
.get()
.saturating_mul(hawdb_storage::index_page::DEFAULT_IMMUTABLE_INDEX_PAGE_BYTES)
);
assert_eq!(
limits.index_read.max_file_bytes,
config.max_relational_index_read_bytes.get()
);
}
#[test]
fn numeric_scan_filter_project_is_default_morsel_eligible() {
let mut db = Database::new();
db.query("CREATE NODE TABLE Item").unwrap();
db.query("CREATE PROPERTY ON NODE TABLE Item(score) TYPE INT")
.unwrap();
let admission = db
.runtime_admission_plan(
"MATCH (n:Item) WHERE n.score >= 10 RETURN n.score AS score",
&BTreeMap::new(),
)
.unwrap();
assert!(admission.parallel_execution_eligible);
assert_eq!(admission.max_parallelism, 1);
}
#[test]
fn vector_seed_admission_uses_optimizer_resource_contract() {
let db = Database::new();
let parameters = BTreeMap::from([(
"embedding".to_string(),
Value::List(vec![Value::Float(1.0), Value::Float(0.0)]),
)]);
let admission = db
.runtime_admission_plan(
"CALL vector_search($embedding, topK := 4) RETURN id, score",
¶meters,
)
.unwrap();
assert!(admission.parallel_execution_eligible);
assert_eq!(
admission.max_parallelism,
crate::executor::MAX_MORSEL_PARALLELISM
);
assert!(
admission.estimated_memory_bytes
>= u64::try_from(db.config.execution_memory.blocking_operator_bytes.get())
.unwrap()
.saturating_mul(3)
);
}
#[test]
fn parameterized_create_and_index_seek_execute_end_to_end() {
let mut db = Database::new();
db.query("CREATE INDEX ON :Memory(id)").unwrap();
db.query_with_params(
"CREATE (:Memory {id: $id, title: $title})",
&BTreeMap::from([
("id".to_string(), Value::Int(42)),
(
"title".to_string(),
Value::String("Parameterized memory".to_string()),
),
]),
)
.unwrap();
for id in 100..116 {
db.query(&format!(
"CREATE (:Memory {{id: {id}, title: 'Parameterized extra {id}'}})"
))
.unwrap();
}
let params = BTreeMap::from([("id".to_string(), Value::Int(42))]);
let explain = db
.explain_query_with_params(
"MATCH (m:Memory) WHERE m.id = $id RETURN m.title AS title",
¶ms,
)
.unwrap();
assert!(explain.trace.selected_plan.contains("IndexNodeSeek"));
let output = db
.query_with_params(
"MATCH (m:Memory) WHERE m.id = $id RETURN m.title AS title",
¶ms,
)
.unwrap();
assert_eq!(
output.rows[0].get("title"),
Some(&Value::String("Parameterized memory".to_string()))
);
}
#[test]
fn bounded_scalar_index_queries_rebind_in_and_union_parameters() {
let mut db = Database::new();
db.query("CREATE INDEX ON :BoundedIndex(key)").unwrap();
db.query("CREATE INDEX ON :BoundedIndex(other)").unwrap();
for key in 0..256 {
db.query_with_params(
"CREATE (:BoundedIndex {key: $key, other: $other})",
&BTreeMap::from([
("key".into(), Value::Int(key)),
("other".into(), Value::Int(key + 1000)),
]),
)
.unwrap();
}
for (query, expected) in [
("MATCH (n:BoundedIndex) WHERE n.key = $key RETURN n.key AS key", vec![2]),
("MATCH (n:BoundedIndex) WHERE n.key IN $keys RETURN n.key AS key ORDER BY key", vec![2, 17]),
("MATCH (n:BoundedIndex) WHERE n.key IN $keys OR n.other = $other RETURN n.key AS key ORDER BY key", vec![2, 3, 17]),
] {
for offset in [0, 40] {
let parameters = BTreeMap::from([
("key".into(), Value::Int(2 + offset)),
("keys".into(), Value::List(vec![Value::Int(17 + offset), Value::Int(2 + offset), Value::Int(17 + offset)])),
("other".into(), Value::Int(1003 + offset)),
]);
let explain = db.explain_query_with_params(query, ¶meters).unwrap();
assert!(explain.trace.selected_plan.contains("NodeProjectionScanExec"), "{}", explain.trace.selected_plan);
let task = hawdb_core::RuntimeTaskContext::default().with_work_limit(64);
let output = db.query_with_params_context(query, ¶meters, &task).unwrap();
assert_eq!(
output.rows.iter().map(|row| row.get("key").unwrap().clone()).collect::<Vec<_>>(),
expected.iter().map(|key| Value::Int(key + offset)).collect::<Vec<_>>(),
"query={query} offset={offset}",
);
}
}
}
#[test]
fn durable_source_filter_uses_segment_scan_through_query_runtime() {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!("hawdb-source-query-runtime-{nonce}"));
let mut db = Database::open(&path).unwrap();
db.query("CREATE (:Source {id: 'source-alpha', space_id: 'alpha', source_type: 'file'})")
.unwrap();
db.query("CREATE (:Source {id: 'source-beta', space_id: 'beta', source_type: 'file'})")
.unwrap();
db.checkpoint().unwrap();
let query = "MATCH (s:Source) WHERE s.space_id = $space_id RETURN s.id AS id";
let parameters = BTreeMap::from([("space_id".to_string(), Value::String("alpha".to_string()))]);
let explain = db.explain_query_with_params(query, ¶meters).unwrap();
assert!(explain
.physical_plan
.explain(0)
.contains("SourceSegmentScan"));
assert!(explain
.trace
.decisions
.iter()
.any(|decision| decision.contains("choose SourceSegmentScan")));
let admission = db.runtime_admission_plan(query, ¶meters).unwrap();
assert_eq!(admission.required_io_slots, 2);
let output = db.query_with_params(query, ¶meters).unwrap();
assert_eq!(output.rows.len(), 1);
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("source-alpha".to_string()))
);
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn source_segment_scan_falls_back_after_uncheckpointed_mutation() {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!("hawdb-source-query-fallback-{nonce}"));
let mut db = Database::open(&path).unwrap();
db.query("CREATE (:Source {id: 'source-checkpointed', space_id: 'alpha'})")
.unwrap();
db.checkpoint().unwrap();
db.query("CREATE (:Source {id: 'source-uncheckpointed', space_id: 'alpha'})")
.unwrap();
let query = "MATCH (s:Source) WHERE s.space_id = 'alpha' RETURN s.id AS id ORDER BY id ASC";
let explain = db.explain_query(query).unwrap();
assert!(explain
.physical_plan
.explain(0)
.contains("SourceSegmentScan"));
let output = db.query(query).unwrap();
assert_eq!(output.rows.len(), 2);
assert_eq!(
output.rows[0].get("id"),
Some(&Value::String("source-checkpointed".to_string()))
);
assert_eq!(
output.rows[1].get("id"),
Some(&Value::String("source-uncheckpointed".to_string()))
);
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn database_config_caps_optimizer_groups_for_explain() {
let db = Database::new_with_config(DatabaseConfig {
max_optimizer_groups: Some(2),
..DatabaseConfig::default()
});
let explain = db
.explain_query(
"MATCH (m:Memory) WHERE m.id = 1 RETURN m.title AS title ORDER BY title ASC LIMIT 1",
)
.unwrap();
assert!(explain.trace.warnings.is_empty());
assert!(explain.trace.groups > 2);
assert!(explain.trace.decisions.iter().any(|decision| {
decision.contains("max_groups=2") && decision.contains("same physical alternatives")
}));
assert!(explain.trace.selected_plan.contains("TopNExec"));
}
#[test]
fn orders_and_limits_by_projected_alias() {
let mut db = Database::new();
db.query("CREATE (:Memory {id: 1, title: 'Beta'})").unwrap();
db.query("CREATE (:Memory {id: 2, title: 'Gamma'})")
.unwrap();
db.query("CREATE (:Memory {id: 3, title: 'Alpha'})")
.unwrap();
let output = db
.query_with_params(
"MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC LIMIT $limit",
&BTreeMap::from([("limit".to_string(), Value::Int(2))]),
)
.unwrap();
assert_eq!(output.rows.len(), 2);
assert_eq!(
output.rows[0].get("title"),
Some(&Value::String("Alpha".to_string()))
);
assert_eq!(
output.rows[1].get("title"),
Some(&Value::String("Beta".to_string()))
);
}
#[test]
fn orders_by_unprojected_property_with_offset() {
let mut db = Database::new();
db.query("CREATE (:Memory {id: 1, title: 'First', rank: 3})")
.unwrap();
db.query("CREATE (:Memory {id: 2, title: 'Second', rank: 1})")
.unwrap();
db.query("CREATE (:Memory {id: 3, title: 'Third', rank: 2})")
.unwrap();
let output = db
.query("MATCH (m:Memory) RETURN m.title AS title ORDER BY m.rank ASC SKIP 1 LIMIT 1")
.unwrap();
assert_eq!(output.rows.len(), 1);
assert_eq!(
output.rows[0].get("title"),
Some(&Value::String("Third".to_string()))
);
}
#[test]
fn distinct_return_deduplicates_before_order_and_limit() {
let mut db = Database::new();
db.query("CREATE (:Memory {id: 1, kind: 'note'})").unwrap();
db.query("CREATE (:Memory {id: 2, kind: 'task'})").unwrap();
db.query("CREATE (:Memory {id: 3, kind: 'note'})").unwrap();
db.query("CREATE (:Memory {id: 4, kind: 'thread'})")
.unwrap();
let output = db
.query("MATCH (m:Memory) RETURN DISTINCT m.kind AS kind ORDER BY kind ASC LIMIT 2")
.unwrap();
assert_eq!(output.rows.len(), 2);
assert_eq!(
output.rows[0].get("kind"),
Some(&Value::String("note".to_string()))
);
assert_eq!(
output.rows[1].get("kind"),
Some(&Value::String("task".to_string()))
);
let explain = db
.explain_query("MATCH (m:Memory) RETURN DISTINCT m.kind AS kind ORDER BY kind ASC")
.unwrap();
assert!(explain.physical_plan.explain(0).contains("DistinctExec"));
assert!(explain.trace.selected_plan.contains("DistinctExec"));
}
#[test]
fn database_config_caps_read_query_result_rows() {
let mut db = Database::new_with_config(DatabaseConfig {
max_read_result_rows: Some(2),
..DatabaseConfig::default()
});
db.query("CREATE (:Memory {id: 1, title: 'One'})").unwrap();
db.query("CREATE (:Memory {id: 2, title: 'Two'})").unwrap();
db.query("CREATE (:Memory {id: 3, title: 'Three'})")
.unwrap();
let error = db
.query("MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC")
.unwrap_err();
assert!(error
.to_string()
.contains("exceeding max_read_result_rows 2"));
let output = db
.query("MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC LIMIT 2")
.unwrap();
assert_eq!(output.rows.len(), 2);
}
#[test]
fn database_config_defaults_to_unlimited_rows_and_bounded_payload() {
let config = DatabaseConfig::default();
assert_eq!(
config.max_read_result_rows,
crate::DEFAULT_MAX_READ_RESULT_ROWS
);
assert_eq!(
config.max_read_result_payload_bytes,
Some(crate::DEFAULT_MAX_READ_RESULT_PAYLOAD_BYTES)
);
}
#[test]
fn relational_query_index_limits_separate_logical_work_from_file_io() {
let config = DatabaseConfig::default();
let limits = super::super::relational_query_limits_with_payload(&config, None, None);
let index = limits.index_read;
let expected_pages = usize::MAX.saturating_mul(
hawdb_storage::relational::DEFAULT_RELATIONAL_INDEX_READ_TREE_HEIGHT as usize,
);
assert_eq!(index.max_rows.get(), usize::MAX);
assert_eq!(index.max_pages.get(), expected_pages);
assert_eq!(
index.max_bytes.get(),
expected_pages
.saturating_mul(hawdb_storage::index_page::DEFAULT_IMMUTABLE_INDEX_PAGE_BYTES)
);
assert_eq!(
index.max_file_bytes,
config.max_relational_index_read_bytes.get()
);
}
#[test]
fn database_config_caps_collected_read_query_payload() {
let mut db = Database::new_with_config(DatabaseConfig {
max_read_result_payload_bytes: Some(16),
..DatabaseConfig::default()
});
db.query("CREATE (:Memory {id: 1, title: 'payload exceeds the configured budget'})")
.unwrap();
let error = db
.query("MATCH (m:Memory) RETURN m.title AS title")
.unwrap_err();
assert!(
error
.to_string()
.contains("max_read_result_payload_bytes 16"),
"unexpected payload budget error: {error}"
);
}
#[test]
fn read_transaction_streaming_options_cannot_relax_database_payload_cap() {
let mut db = Database::new_with_config(DatabaseConfig {
max_read_result_payload_bytes: Some(16),
..DatabaseConfig::default()
});
db.query("CREATE (:Memory {id: 1, title: 'payload exceeds the configured budget'})")
.unwrap();
let mut read = db.begin_read_transaction().unwrap();
let mut delivered_rows = 0usize;
let error = read
.query_streaming(
"MATCH (m:Memory) RETURN m.title AS title",
QueryStreamOptions {
max_rows: Some(usize::MAX),
max_payload_bytes: Some(usize::MAX),
},
|_| {
delivered_rows += 1;
Ok(())
},
)
.unwrap_err();
assert_eq!(delivered_rows, 0);
assert!(
error.to_string().contains("max_payload_bytes 16"),
"unexpected streaming payload budget error: {error}"
);
}
#[test]
fn database_config_can_explicitly_allow_unbounded_read_results() {
let mut db = Database::new_with_config(DatabaseConfig {
max_read_result_rows: None,
max_read_result_payload_bytes: None,
..DatabaseConfig::default()
});
let title = "x".repeat(128 * 1024);
db.query_with_params(
"CREATE (:Memory {id: 1, title: $title})",
&BTreeMap::from([("title".to_string(), Value::String(title.clone()))]),
)
.unwrap();
let output = db
.query("MATCH (m:Memory) RETURN m.title AS title")
.unwrap();
assert_eq!(output.rows[0].get("title"), Some(&Value::String(title)));
}
#[test]
fn read_transaction_inherits_database_result_row_cap() {
let mut db = Database::new_with_config(DatabaseConfig {
max_read_result_rows: Some(1),
..DatabaseConfig::default()
});
db.query("CREATE (:Memory {id: 1, title: 'One'})").unwrap();
db.query("CREATE (:Memory {id: 2, title: 'Two'})").unwrap();
let mut read = db.begin_read_transaction().unwrap();
let error = read
.query("MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC")
.unwrap_err();
assert!(error
.to_string()
.contains("exceeding max_read_result_rows 1"));
}
#[test]
fn read_only_database_rejects_cypher_mutations_before_writing() {
let mut db = Database::new_with_config(DatabaseConfig {
read_only: true,
recovery_mode: crate::RecoveryMode::Strict,
..DatabaseConfig::default()
});
let error = db
.query("CREATE (:Memory {id: 1, title: 'Blocked'})")
.unwrap_err();
assert!(error.to_string().contains("read-only mode"));
let output = db
.query("MATCH (m:Memory) RETURN m.title AS title")
.unwrap();
assert!(output.rows.is_empty());
}
#[test]
fn read_only_rejected_mutations_do_not_populate_plan_cache() {
let mut db = Database::new_with_config(DatabaseConfig {
read_only: true,
recovery_mode: crate::RecoveryMode::Strict,
max_plan_cache_entries: Some(8),
..DatabaseConfig::default()
});
let error = db
.query("CREATE (:Memory {id: 1, title: 'Blocked'})")
.unwrap_err();
assert!(error.to_string().contains("read-only mode"));
let stats = db.plan_cache_stats().unwrap();
assert_eq!(stats.entries, 0);
assert_eq!(stats.hits, 0);
assert_eq!(stats.misses, 0);
assert_eq!(stats.evictions, 0);
}
#[test]
fn unlabeled_match_reads_and_updates_nodes() {
let mut db = Database::new();
db.query("CREATE (:Memory {id: 1, title: 'Memory'})")
.unwrap();
db.query("CREATE (:Entity {id: 2, name: 'Entity'})")
.unwrap();
let output = db
.query_with_params(
"MATCH (n) WHERE n.id IN $ids RETURN n.id AS id ORDER BY id ASC",
&BTreeMap::from([(
"ids".to_string(),
Value::List(vec![Value::Int(1), Value::Int(2)]),
)]),
)
.unwrap();
assert_eq!(output.rows.len(), 2);
assert_eq!(output.rows[0].get("id"), Some(&Value::Int(1)));
assert_eq!(output.rows[1].get("id"), Some(&Value::Int(2)));
let output = db
.query("MATCH (n) WHERE n.id = 2 SET n.community_id = 7")
.unwrap();
assert_eq!(output.rows.len(), 1);
let output = db
.query("MATCH (n) WHERE n.community_id = 7 RETURN n.id AS id")
.unwrap();
assert_eq!(output.rows.len(), 1);
assert_eq!(output.rows[0].get("id"), Some(&Value::Int(2)));
}
#[test]
fn multi_label_match_reads_any_listed_label() {
let mut db = Database::new();
db.query(
"CREATE (:Memory {id: 1, title: 'Memory'})-[:MENTIONS]->(:Entity {id: 2, name: 'Entity'})",
)
.unwrap();
db.query("CREATE (:Source {id: 3, original_name: 'Source'})")
.unwrap();
let output = db
.query("MATCH (n:Entity:Memory) RETURN n.id AS id ORDER BY id ASC")
.unwrap();
assert_eq!(output.rows.len(), 2);
assert_eq!(output.rows[0].get("id"), Some(&Value::Int(1)));
assert_eq!(output.rows[1].get("id"), Some(&Value::Int(2)));
let output = db
.query(
"MATCH (m:Memory {id: 1})-[r]-(neighbor:Entity:Memory) RETURN DISTINCT neighbor.id AS id",
)
.unwrap();
assert_eq!(output.rows.len(), 1);
assert_eq!(output.rows[0].get("id"), Some(&Value::Int(2)));
let output = db
.query("MATCH (n:MissingLabel) RETURN n.id AS id")
.unwrap();
assert!(output.rows.is_empty());
for query in [
"MATCH (n:Entity:Memory) RETURN count(n) AS n",
"MATCH (n:Entity:Memory) RETURN count(*) AS n",
"MATCH (n:Memory:Source:Entity) RETURN count(n) AS n",
] {
let expected = if query.contains("Source") { 3 } else { 2 };
let output = db.query(query).unwrap();
assert_eq!(
output.rows[0].get("n"),
Some(&Value::Int(expected)),
"{query}"
);
}
let output = db
.query("MATCH (n:Entity:MissingLabel) RETURN count(n) AS n")
.unwrap();
assert_eq!(output.rows[0].get("n"), Some(&Value::Int(1)));
}
#[test]
fn variable_return_items_project_graph_records() {
let mut db = Database::new();
db.query("CREATE (:Memory {id: 'm1', title: 'Memory'})-[:MENTIONS {weight: 3}]->(:Entity {id: 'e1', name: 'Entity'})")
.unwrap();
let output = db.query("MATCH (m:Memory {id: 'm1'}) RETURN m").unwrap();
assert_eq!(output.rows.len(), 1);
let Some(Value::Map(memory)) = output.rows[0].get("m") else {
panic!("expected projected memory map");
};
assert_eq!(memory.get("id"), Some(&Value::String("m1".to_string())));
assert_eq!(
memory.get("title"),
Some(&Value::String("Memory".to_string()))
);
assert_eq!(
memory.get("labels"),
Some(&Value::List(vec![Value::String("Memory".to_string())]))
);
let output = db
.query("MATCH (m:Memory {id: 'm1'})-[r:MENTIONS]->(e:Entity) RETURN r")
.unwrap();
assert_eq!(output.rows.len(), 1);
let Some(Value::Map(relationship)) = output.rows[0].get("r") else {
panic!("expected projected relationship map");
};
assert_eq!(
relationship.get("type"),
Some(&Value::String("MENTIONS".to_string()))
);
assert_eq!(relationship.get("weight"), Some(&Value::Int(3)));
assert_eq!(relationship.get("source_id"), Some(&Value::Int(0)));
assert_eq!(relationship.get("target_id"), Some(&Value::Int(1)));
}
#[test]
fn read_transaction_streams_rows_with_row_and_payload_budgets() {
let execution_memory = crate::executor::ExecutionMemoryConfig {
batch_rows: std::num::NonZeroUsize::new(1).unwrap(),
..crate::executor::ExecutionMemoryConfig::default()
};
let mut db = Database::new_with_config(DatabaseConfig {
execution_memory,
..DatabaseConfig::default()
});
for (id, title) in [(1, "alpha"), (2, "beta"), (3, "gamma")] {
db.query(&format!("CREATE (:Memory {{id: {id}, title: '{title}'}})"))
.unwrap();
}
let mut tx = db.begin_read_transaction().unwrap();
let mut titles = Vec::new();
let report = tx
.query_streaming(
"MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC LIMIT 2",
QueryStreamOptions {
max_rows: Some(2),
max_payload_bytes: Some(1024),
},
|row| {
titles.push(row["title"].clone());
Ok(())
},
)
.unwrap();
assert!(report.fully_streamed);
assert_eq!(report.output_rows, 2);
assert!(report.output_payload_bytes > 0);
assert_eq!(
titles,
vec![
Value::String("alpha".to_string()),
Value::String("beta".to_string())
]
);
let mut tx = db.begin_read_transaction().unwrap();
let mut delivered_rows = 0usize;
let error = tx
.query_streaming(
"MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC",
QueryStreamOptions {
max_rows: Some(1),
max_payload_bytes: Some(1024),
},
|_| {
delivered_rows += 1;
Ok(())
},
)
.unwrap_err();
assert_eq!(delivered_rows, 0);
assert!(error
.to_string()
.contains("exceeding max_read_result_rows 1"));
let mut tx = db.begin_read_transaction().unwrap();
let first_row_payload_bytes = crate::executor::map_payload_bytes(&BTreeMap::from([(
"title".to_string(),
Value::String("alpha".to_string()),
)]));
let mut delivered_rows = 0usize;
let error = tx
.query_streaming(
"MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC LIMIT 2",
QueryStreamOptions {
max_rows: Some(2),
max_payload_bytes: Some(first_row_payload_bytes),
},
|_| {
delivered_rows += 1;
Ok(())
},
)
.unwrap_err();
assert_eq!(delivered_rows, 0);
assert!(error
.to_string()
.contains(&format!("max_payload_bytes {first_row_payload_bytes}")));
}
#[test]
fn executor_owned_result_delivery_preserves_read_transaction_boundaries() {
let mut db = Database::new_with_config(DatabaseConfig {
max_read_result_rows: None,
max_read_result_payload_bytes: None,
execution_memory: crate::executor::ExecutionMemoryConfig {
batch_rows: std::num::NonZeroUsize::new(1).unwrap(),
..crate::executor::ExecutionMemoryConfig::default()
},
..DatabaseConfig::default()
});
for title in ["alpha", "beta", "gamma"] {
db.query(&format!("CREATE (:Memory {{title: '{title}'}})"))
.unwrap();
}
const QUERY: &str = "MATCH (m:Memory) RETURN m.title AS title ORDER BY title ASC";
let parameters = BTreeMap::new();
let expected = ["alpha", "beta", "gamma"]
.into_iter()
.map(|title| BTreeMap::from([("title".to_string(), Value::String(title.to_string()))]))
.collect::<Vec<_>>();
let total_payload = 3 * "title".len() + "alpha".len() + "beta".len() + "gamma".len();
let mut tx = db.begin_read_transaction().unwrap();
let retained = tx
.query_with_params_bounded_profile(QUERY, ¶meters, Some(3))
.unwrap();
assert_eq!(retained.output.rows, expected);
assert!(
retained
.execution_profile
.pipeline_memory_report
.query_memory_completion_bytes
> 0
);
for options in [
QueryStreamOptions {
max_rows: None,
max_payload_bytes: None,
},
QueryStreamOptions {
max_rows: Some(3),
max_payload_bytes: Some(total_payload),
},
] {
let mut delivered = Vec::new();
let report = tx
.query_streaming(QUERY, options, |row| {
delivered.push(row);
Ok(())
})
.unwrap();
assert_eq!(delivered, expected);
assert_eq!(report.output_rows, 3);
assert_eq!(report.output_payload_bytes, total_payload);
assert_eq!(
report
.execution_profile
.pipeline_memory_report
.query_memory_completion_bytes,
0
);
assert!(
report
.execution_profile
.pipeline_memory_report
.query_memory_peak_bytes
> 0
);
}
for (options, error_field) in [
(
QueryStreamOptions {
max_rows: Some(2),
max_payload_bytes: Some(total_payload),
},
"max_read_result_rows 2",
),
(
QueryStreamOptions {
max_rows: Some(3),
max_payload_bytes: Some(total_payload - 1),
},
"max_read_result_payload_bytes",
),
] {
let mut delivered = Vec::new();
let error = tx
.query_streaming(QUERY, options, |row| {
delivered.push(row);
Ok(())
})
.unwrap_err();
assert!(error.to_string().contains(error_field), "{error}");
assert!(delivered.is_empty());
}
for cancel in [false, true] {
let context = hawdb_core::RuntimeTaskContext::default();
let mut delivered = Vec::new();
let error = tx
.query_with_params_streaming_context(
QUERY,
¶meters,
QueryStreamOptions {
max_rows: Some(3),
max_payload_bytes: Some(total_payload),
},
&context,
|row| {
delivered.push(row);
if cancel {
context.cancellation().cancel();
Ok(())
} else {
Err(crate::HawDBError::Execution(
"host consumer failed".to_string(),
))
}
},
)
.unwrap_err();
assert_eq!(delivered, expected[..1]);
assert!(
error.to_string().contains(if cancel {
"cancelled"
} else {
"host consumer failed"
}),
"{error}"
);
assert_eq!(tx.query(QUERY).unwrap().rows, expected);
}
}
#[test]
fn read_transaction_exposes_validated_compact_borrowed_rows() {
let mut db = Database::new();
db.query("CREATE (:Memory {id: 7, title: 'borrowed payload'})")
.unwrap();
let mut tx = db.begin_read_transaction().unwrap();
let mut observed = Vec::new();
let report = tx
.query_with_params_streaming_ref(
"MATCH (m:Memory) RETURN m.id AS id, m.title AS title",
&BTreeMap::new(),
QueryStreamOptions {
max_rows: Some(1),
max_payload_bytes: Some(1024),
},
|row| {
assert!(matches!(row, crate::RowRef::Compact(_)));
observed.push((
row.get("id").and_then(crate::ValueRef::as_i64),
row.get("title")
.and_then(crate::ValueRef::as_str)
.map(str::to_owned),
));
Ok(())
},
)
.unwrap();
assert_eq!(report.output_rows, 1);
assert_eq!(observed, vec![(Some(7), Some("borrowed payload".into()))]);
}
#[test]
fn read_transaction_borrowed_stream_refuses_limits_without_delivering_a_prefix() {
let mut db = Database::new();
db.query("CREATE (:Memory {id: 1, title: 'first'})")
.unwrap();
db.query("CREATE (:Memory {id: 2, title: 'second'})")
.unwrap();
let mut tx = db.begin_read_transaction().unwrap();
let query = "MATCH (m:Memory) RETURN m.id AS id, m.title AS title ORDER BY id";
for options in [
QueryStreamOptions {
max_rows: Some(1),
max_payload_bytes: Some(1024),
},
QueryStreamOptions {
max_rows: Some(2),
max_payload_bytes: Some(19),
},
] {
let mut calls = 0;
let error = tx
.query_with_params_streaming_ref(query, &BTreeMap::new(), options, |_| {
calls += 1;
Ok(())
})
.unwrap_err();
assert!(matches!(error, crate::HawDBError::ReadBudgetExceeded(_)));
assert_eq!(calls, 0);
assert_eq!(tx.query(query).unwrap().rows.len(), 2);
}
}
#[test]
fn native_numeric_results_preserve_borrowing_validation_and_owned_parity() {
let mut db = Database::new_with_config(DatabaseConfig {
max_read_result_rows: None,
max_read_result_payload_bytes: None,
..DatabaseConfig::default()
});
db.query("CREATE NODE TABLE Item").unwrap();
db.query("CREATE PROPERTY ON NODE TABLE Item(score) TYPE INT")
.unwrap();
for score in 0..3 {
db.query_with_params(
"CREATE (:Item {score: $score, body: $body})",
&BTreeMap::from([
("score".into(), Value::Int(score)),
("body".into(), Value::String(format!("body-{score}"))),
]),
)
.unwrap();
}
let query = "MATCH (n:Item) WHERE n.score >= 0 RETURN n.score AS score, n.body AS body";
let parameters = BTreeMap::new();
let mut tx = db.begin_read_transaction().unwrap();
let expected = tx
.query_with_params_bounded_profile(query, ¶meters, Some(3))
.unwrap();
assert_eq!(
expected
.execution_profile
.pipeline_memory_report
.native_projection_rows,
3
);
let limited = tx
.query_with_params_bounded_profile(&format!("{query} SKIP 1 LIMIT 1"), ¶meters, Some(1))
.unwrap();
let memory = &limited.execution_profile.pipeline_memory_report;
assert_eq!(limited.output.rows.len(), 1);
assert_eq!(memory.native_projection_rows, 1);
assert_eq!(memory.intermediate_rows, 1);
for bounded in [false, true] {
let mut rows = Vec::new();
let report = tx
.query_with_params_streaming_ref(
query,
¶meters,
QueryStreamOptions {
max_rows: bounded.then_some(3),
max_payload_bytes: bounded.then_some(1024),
},
|row| {
assert!(if bounded {
matches!(row, crate::RowRef::Compact(_))
} else {
matches!(row, crate::RowRef::Projected(_))
});
rows.push(row.to_owned_row());
Ok(())
},
)
.unwrap();
assert_eq!(rows, expected.output.rows);
assert_eq!(
report
.execution_profile
.pipeline_memory_report
.native_projection_rows,
3
);
assert_eq!(
report
.execution_profile
.pipeline_memory_report
.query_memory_completion_bytes,
0
);
}
for options in [
QueryStreamOptions {
max_rows: Some(2),
max_payload_bytes: Some(1024),
},
QueryStreamOptions {
max_rows: Some(3),
max_payload_bytes: Some(1),
},
] {
let mut calls = 0;
let error = tx
.query_with_params_streaming_ref(query, ¶meters, options, |_| {
calls += 1;
Ok(())
})
.unwrap_err();
assert!(matches!(error, crate::HawDBError::ReadBudgetExceeded(_)));
assert_eq!(calls, 0);
assert_eq!(tx.query(query).unwrap().rows, expected.output.rows);
}
for (suffix, offset, limit) in [
(" SKIP 1 LIMIT 1", 1, 1),
(" SKIP 3 LIMIT 2", 3, 2),
(" LIMIT 0", 0, 0),
(" LIMIT 2", 0, 2),
] {
let mut rows = Vec::new();
tx.query_with_params_streaming_ref(
&format!("{query}{suffix}"),
¶meters,
QueryStreamOptions::default(),
|row| {
assert!(matches!(row, crate::RowRef::Projected(_)));
rows.push(row.to_owned_row());
Ok(())
},
)
.unwrap();
assert_eq!(
rows,
expected
.output
.rows
.iter()
.skip(offset)
.take(limit)
.map(|row| row.to_owned_row())
.collect::<Vec<_>>()
);
}
let context = hawdb_core::RuntimeTaskContext::default().with_work_limit(100);
let mut rows = Vec::new();
let report = tx
.query_with_params_streaming_context(
query,
¶meters,
QueryStreamOptions::default(),
&context,
|row| {
rows.push(row);
Ok(())
},
)
.unwrap();
assert_eq!(rows, expected.output.rows);
assert_eq!(
report
.execution_profile
.pipeline_memory_report
.native_projection_rows,
0
);
assert!(context.work_units() > 0);
}
#[test]
fn blocking_memory_refusals_expose_effective_limits_and_preserve_complete_results() {
use crate::{HawDBError, ResourceBudgetKind, ResourceBudgetScope};
use std::num::NonZeroUsize;
let cases = [
("SortExec", "MATCH (m:Memory) RETURN m.id AS id ORDER BY m.payload", 64, vec![2, 1]),
("TopNExec", "MATCH (m:Memory) RETURN m.id AS id ORDER BY m.payload LIMIT 1", 64, vec![2]),
("AggregateExec", "MATCH (m:Memory) WITH m.payload AS payload, COUNT(*) AS total RETURN payload, total", 21, vec![]),
("AggregateExec", "MATCH (m:Memory) WITH m.payload AS payload, COUNT(DISTINCT m.id) AS total RETURN payload, total", 64, vec![]),
];
for budget in [64, 8192] {
let mut db = Database::new_with_config(DatabaseConfig {
execution_memory: crate::executor::ExecutionMemoryConfig {
blocking_operator_bytes: NonZeroUsize::new(budget).unwrap(),
query_memory_bytes: NonZeroUsize::new(65536).unwrap(),
batch_rows: NonZeroUsize::MIN,
batch_payload_bytes: NonZeroUsize::new(4096).unwrap(),
..Default::default()
},
..Default::default()
});
let payloads = [
format!("b{}", "x".repeat(256)),
format!("a{}", "x".repeat(256)),
];
for (id, payload) in payloads.iter().enumerate() {
db.query_with_params(
"CREATE (:Memory {id: $id, payload: $payload})",
&BTreeMap::from([
("id".into(), Value::Int(id as i64 + 1)),
("payload".into(), Value::String(payload.clone())),
]),
)
.unwrap();
}
for (owner, query, effective_limit, expected_ids) in &cases {
if budget == 64 {
let error = db.query(query).unwrap_err();
let HawDBError::ResourceBudgetExceeded(cause) = error else {
panic!("{query}: expected typed memory refusal, got {error}");
};
assert_eq!(cause.resource, ResourceBudgetKind::MemoryBytes);
assert_eq!(cause.scope, ResourceBudgetScope::Operator);
assert!(cause.owner.starts_with(owner), "{cause:?}");
assert_eq!(cause.memory_class, Some("blocking_state"));
assert_eq!(cause.budget, *effective_limit);
assert_eq!(cause.used, 0);
assert!(cause.requested > cause.budget);
assert_eq!(
cause.budget_option,
"ExecutionMemoryConfig.blocking_operator_bytes"
);
assert_eq!(
db.query("MATCH (m:Memory) RETURN m.payload AS payload")
.unwrap()
.rows
.len(),
2
);
} else {
let result = db.query(query).unwrap();
if expected_ids.is_empty() {
assert_eq!(result.rows.len(), 2);
let mut actual = result
.rows
.iter()
.map(|row| {
assert_eq!(row.get("total"), Some(&Value::Int(1)));
let Some(Value::String(payload)) = row.get("payload") else {
panic!("missing group key");
};
payload.clone()
})
.collect::<Vec<_>>();
actual.sort();
let mut expected = payloads.to_vec();
expected.sort();
assert_eq!(actual, expected);
} else {
let actual = result
.rows
.iter()
.map(|row| row.get("id").unwrap().clone())
.collect::<Vec<_>>();
assert_eq!(
actual,
expected_ids
.iter()
.copied()
.map(Value::Int)
.collect::<Vec<_>>()
);
}
}
}
}
}