Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
238 changes: 236 additions & 2 deletions crates/persistence/src/search/chain_resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -731,6 +783,7 @@ where
&parent_types_per_hop,
current_refs,
options,
FanOut::new(),
)
.await
.map(Some)
Expand Down Expand Up @@ -789,14 +842,15 @@ where
.collect(),
)?;
let mut current_refs: Vec<String> = 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;
};
// 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() {
Expand All @@ -810,19 +864,22 @@ where
&parent_types_per_hop,
current_refs,
options,
fan_out,
)
.await
.map(Some)
}

/// 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<S>(
storage: &S,
tenant: &TenantContext,
scope: &SearchQuery,
ids: Vec<String>,
fan_out: &mut FanOut,
) -> StorageResult<Vec<String>>
where
S: SearchProvider + ?Sized,
Expand All @@ -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 {
Expand Down Expand Up @@ -886,13 +944,18 @@ 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<S>(
storage: &S,
tenant: &TenantContext,
hops: &[ChainedParameter],
parent_types_per_hop: &[Vec<String>],
mut current_refs: Vec<String>,
options: ChainResolveOptions<'_>,
mut fan_out: FanOut,
) -> StorageResult<Vec<String>>
where
S: SearchProvider + ?Sized,
Expand All @@ -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<SearchValue> = chunk.iter().map(SearchValue::eq).collect();
Expand Down Expand Up @@ -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] {
Expand Down
Loading