From fe2e4ac3a6cdb48d5a9ace575692cbd2965ac35c Mon Sep 17 00:00:00 2001 From: angela-helios Date: Mon, 30 Nov 2026 19:41:39 -0400 Subject: [PATCH] fix(persistence): bound the searches one chained search may issue The chain resolver searches a hop's references 250 at a time, once per candidate parent type, so a hop at the 300,000-id ceiling ran 1,200 searches per type. Each chained parameter now has a budget of 400 such searches across all its hops and parent types; a hop that does not fit is refused with 422 before any of its searches runs. The liveness check of a forward chain ending in _has spends from the same budget. Closes #3203 --- .../persistence/src/search/chain_resolver.rs | 238 +++++++++++++++++- 1 file changed, 236 insertions(+), 2 deletions(-) diff --git a/crates/persistence/src/search/chain_resolver.rs b/crates/persistence/src/search/chain_resolver.rs index 7b03c9643c..9939e1934f 100644 --- a/crates/persistence/src/search/chain_resolver.rs +++ b/crates/persistence/src/search/chain_resolver.rs @@ -408,6 +408,58 @@ fn check_hop_ids(count: usize) -> StorageResult<()> { /// correctness never depends on the size — the chunks' matches are unioned. const CHAIN_VALUE_CHUNK: usize = 250; +/// Most searches the reference hops of one chained parameter may issue, over +/// all of its hops and their candidate parent types. A hop is searched +/// [`CHAIN_VALUE_CHUNK`] references at a time, once per candidate parent +/// type, so [`MAX_HOP_IDS`] alone lets a single hop run 1,200 searches per +/// type; this bounds the walk at the searches 100,000 references take through +/// one parent type. +const MAX_CHAIN_FAN_OUT: usize = 400; + +#[cfg(test)] +tokio::task_local! { + static FAN_OUT_OVERRIDE: usize; +} + +/// [`MAX_CHAIN_FAN_OUT`], or a lower ceiling a test installed for the +/// duration of one future. +fn max_chain_fan_out() -> usize { + #[cfg(test)] + if let Ok(lowered) = FAN_OUT_OVERRIDE.try_with(|c| *c) { + return lowered; + } + MAX_CHAIN_FAN_OUT +} + +/// The searches the reference hops of one chained parameter may still issue. +struct FanOut { + left: usize, +} + +impl FanOut { + /// The whole budget of one chained parameter ([`MAX_CHAIN_FAN_OUT`]). + fn new() -> Self { + Self { + left: max_chain_fan_out(), + } + } + + /// Takes the searches a hop of `values` references or ids needs across + /// `types` candidate types, one per chunk and type. A hop that needs more + /// than are left is refused (`422`) before any of its searches runs; the + /// error carries the hop's width and the widest hop the budget still + /// allowed. + fn spend(&mut self, values: usize, types: usize) -> StorageResult<()> { + let searches = values.div_ceil(CHAIN_VALUE_CHUNK).saturating_mul(types); + if searches > self.left { + let max = (self.left / types.max(1)).saturating_mul(CHAIN_VALUE_CHUNK); + return Err(hop_too_large(values, max)); + } + self.left -= searches; + Ok(()) + } +} + /// Every match of `query`, across every page. The resolver's intermediate /// searches feed id rewrites, so letting a backend apply its default page /// size silently truncated every hop of every chain at 100 matches — both @@ -731,6 +783,7 @@ where &parent_types_per_hop, current_refs, options, + FanOut::new(), ) .await .map(Some) @@ -789,6 +842,7 @@ where .collect(), )?; let mut current_refs: Vec = Vec::new(); + let mut fan_out = FanOut::new(); for (target, ids) in terminal_types.iter().zip(referenced) { let Some((_, scope)) = admitted.iter().find(|(t, _)| t == target) else { continue; @@ -796,7 +850,7 @@ where // The `_has` yields the ids its sources *refer to*. Only those of // resources that exist are reached by the chain, as a terminal // search's matches are and a top-level `_has`'s final search is. - let live = existing_ids(storage, tenant, scope, ids).await?; + let live = existing_ids(storage, tenant, scope, ids, &mut fan_out).await?; current_refs.extend(live.into_iter().map(|id| format!("{target}/{id}"))); } if current_refs.is_empty() { @@ -810,6 +864,7 @@ where &parent_types_per_hop, current_refs, options, + fan_out, ) .await .map(Some) @@ -817,12 +872,14 @@ where /// The distinct ids among `ids` of resources that exist in the tenant and /// match `scope` (a query on their type that the hop guard may have narrowed), -/// read without resource bodies, `CHAIN_VALUE_CHUNK` ids per search. +/// read without resource bodies, `CHAIN_VALUE_CHUNK` ids per search. The +/// searches are taken from `fan_out`. async fn existing_ids( storage: &S, tenant: &TenantContext, scope: &SearchQuery, ids: Vec, + fan_out: &mut FanOut, ) -> StorageResult> where S: SearchProvider + ?Sized, @@ -832,6 +889,7 @@ where .into_iter() .filter(|id| seen.insert(id.clone())) .collect(); + fan_out.spend(ids.len(), 1)?; let mut live = Vec::new(); for chunk in ids.chunks(CHAIN_VALUE_CHUNK) { let query = scope.clone().with_parameter(SearchParameter { @@ -886,6 +944,10 @@ fn hop_target_types( /// references its last hop reached: for each reference hop, finds the parents /// pointing at the refs, across every candidate parent type. Returns the ids /// of the chain's base type. +/// +/// Every hop takes its searches from `fan_out`, so the walk as a whole issues +/// no more than the chained parameter's budget and a hop too wide for what is +/// left is refused before it is searched. async fn walk_back_out( storage: &S, tenant: &TenantContext, @@ -893,6 +955,7 @@ async fn walk_back_out( parent_types_per_hop: &[Vec], mut current_refs: Vec, options: ChainResolveOptions<'_>, + mut fan_out: FanOut, ) -> StorageResult> where S: SearchProvider + ?Sized, @@ -916,6 +979,7 @@ where .map(|t| (t.clone(), SearchQuery::new(t))) .collect(), )?; + fan_out.spend(current_refs.len(), parents.len())?; for (parent_type, scope) in &parents { for chunk in current_refs.chunks(CHAIN_VALUE_CHUNK) { let values: Vec = chunk.iter().map(SearchValue::eq).collect(); @@ -3565,6 +3629,176 @@ mod tests { ); } + #[test] + fn fan_out_budget_counts_one_search_per_chunk_and_type() { + let mut fan_out = FanOut { left: 10 }; + fan_out.spend(0, 3).unwrap(); + assert_eq!(fan_out.left, 10); + fan_out.spend(1, 1).unwrap(); + assert_eq!(fan_out.left, 9); + fan_out.spend(CHAIN_VALUE_CHUNK, 2).unwrap(); + assert_eq!(fan_out.left, 7); + fan_out.spend(CHAIN_VALUE_CHUNK + 1, 3).unwrap(); + assert_eq!(fan_out.left, 1); + + let refused = fan_out.spend(CHAIN_VALUE_CHUNK + 1, 1); + assert!( + matches!( + refused, + Err(StorageError::Search(SearchError::TooManyResults { count, max })) + if count == CHAIN_VALUE_CHUNK + 1 && max == CHAIN_VALUE_CHUNK + ), + "{refused:?}" + ); + assert_eq!(fan_out.left, 1, "a refused hop takes nothing"); + let refused = fan_out.spend(1, 2); + assert!( + matches!( + refused, + Err(StorageError::Search(SearchError::TooManyResults { + count: 1, + max: 0 + })) + ), + "{refused:?}" + ); + fan_out.spend(CHAIN_VALUE_CHUNK, 1).unwrap(); + assert_eq!(fan_out.left, 0); + } + + #[test] + fn fan_out_default_budget_is_below_what_the_id_ceiling_allows() { + assert!(MAX_CHAIN_FAN_OUT < MAX_HOP_IDS.div_ceil(CHAIN_VALUE_CHUNK)); + let mut fan_out = FanOut::new(); + assert_eq!(fan_out.left, MAX_CHAIN_FAN_OUT); + fan_out + .spend(MAX_CHAIN_FAN_OUT * CHAIN_VALUE_CHUNK, 1) + .unwrap(); + assert_eq!(fan_out.left, 0); + assert!(FanOut::new().spend(MAX_HOP_IDS, 1).is_err()); + } + + /// A hop wider than the searches left is refused, with the hop's width and + /// the widest hop that would have fitted, and resolves once it fits. + #[tokio::test] + async fn a_hop_needing_more_searches_than_the_fan_out_ceiling_is_refused() { + let b = backend(); + let t = tenant(); + // 600 references: three chunks of 250. + const PATIENTS: usize = 600; + for i in 0..PATIENTS { + b.create( + &t, + "Patient", + json!({ "resourceType": "Patient", "id": format!("p{i}"), "gender": "female" }), + FhirVersion::default(), + ) + .await + .unwrap(); + b.create( + &t, + "Observation", + json!({ "resourceType": "Observation", "id": format!("o{i}"), "status": "final", + "subject": { "reference": format!("Patient/p{i}") } }), + FhirVersion::default(), + ) + .await + .unwrap(); + } + let query = forward( + "Observation", + &[("subject", "Patient", "gender")], + &["female"], + ); + + let refused = FAN_OUT_OVERRIDE + .scope(2, resolve_chains(&b, &t, &query)) + .await; + assert_eq!( + too_many(&refused), + Some((PATIENTS, 2 * CHAIN_VALUE_CHUNK)), + "{refused:?}" + ); + + let resolved = FAN_OUT_OVERRIDE + .scope(3, resolve_chains(&b, &t, &query)) + .await + .unwrap(); + let ids: usize = resolved + .parameters + .iter() + .filter(|p| p.name == "_id") + .map(|p| p.values.len()) + .sum(); + assert_eq!(ids, PATIENTS); + } + + /// The ceiling is the chained parameter's, not one hop's: each hop of this + /// two-hop chain needs two searches, and three do not cover both. + #[tokio::test] + async fn the_fan_out_ceiling_is_shared_by_the_hops_of_a_chain() { + let b = backend(); + let t = tenant(); + const N: usize = 300; + for i in 0..N { + b.create( + &t, + "Patient", + json!({ "resourceType": "Patient", "id": format!("p{i}"), "gender": "female" }), + FhirVersion::default(), + ) + .await + .unwrap(); + b.create( + &t, + "Encounter", + json!({ "resourceType": "Encounter", "id": format!("e{i}"), "status": "finished", + "subject": { "reference": format!("Patient/p{i}") } }), + FhirVersion::default(), + ) + .await + .unwrap(); + b.create( + &t, + "Observation", + json!({ "resourceType": "Observation", "id": format!("o{i}"), "status": "final", + "encounter": { "reference": format!("Encounter/e{i}") } }), + FhirVersion::default(), + ) + .await + .unwrap(); + } + let query = forward( + "Observation", + &[ + ("encounter", "Encounter", "subject"), + ("subject", "Patient", "gender"), + ], + &["female"], + ); + + let refused = FAN_OUT_OVERRIDE + .scope(3, resolve_chains(&b, &t, &query)) + .await; + assert_eq!( + too_many(&refused), + Some((N, CHAIN_VALUE_CHUNK)), + "{refused:?}" + ); + + let resolved = FAN_OUT_OVERRIDE + .scope(4, resolve_chains(&b, &t, &query)) + .await + .unwrap(); + let ids: usize = resolved + .parameters + .iter() + .filter(|p| p.name == "_id") + .map(|p| p.values.len()) + .sum(); + assert_eq!(ids, N); + } + #[tokio::test] async fn a_hop_past_its_ceiling_is_refused_not_truncated() { for ids_only in [true, false] {