diff --git a/store/postgres/src/deployment_store.rs b/store/postgres/src/deployment_store.rs index d764d451ad6..1a879582293 100644 --- a/store/postgres/src/deployment_store.rs +++ b/store/postgres/src/deployment_store.rs @@ -1100,13 +1100,10 @@ impl DeploymentStore { site: Arc, derived_query: &DerivedEntityQuery, block: BlockNumber, - excluded_keys: &[EntityKey], ) -> Result, StoreError> { let mut conn = self.pool.get_permitted().await?; let layout = self.layout(&mut conn, site).await?; - layout - .find_derived(&mut conn, derived_query, block, excluded_keys) - .await + layout.find_derived(&mut conn, derived_query, block).await } pub(crate) async fn get_changes( diff --git a/store/postgres/src/relational.rs b/store/postgres/src/relational.rs index 4059e736635..7e01bcb22ec 100644 --- a/store/postgres/src/relational.rs +++ b/store/postgres/src/relational.rs @@ -664,12 +664,9 @@ impl Layout { conn: &mut AsyncPgConnection, derived_query: &DerivedEntityQuery, block: BlockNumber, - excluded_keys: &[EntityKey], ) -> Result, StoreError> { let table = self.table_for_entity(&derived_query.entity_type)?; - let ids = excluded_keys.iter().map(|key| &key.entity_id).cloned(); - let excluded_keys = IdList::try_from_iter(derived_query.entity_type.id_type()?, ids)?; - let query = FindDerivedQuery::new(table, derived_query, block, excluded_keys); + let query = FindDerivedQuery::new(table, derived_query, block); let mut entities = BTreeMap::new(); diff --git a/store/postgres/src/relational_queries.rs b/store/postgres/src/relational_queries.rs index d87b950adc1..eeac67da972 100644 --- a/store/postgres/src/relational_queries.rs +++ b/store/postgres/src/relational_queries.rs @@ -2188,13 +2188,12 @@ impl<'a> Query for FindManyQuery<'a> { impl<'a, Conn> RunQueryDsl for FindManyQuery<'a> {} -/// A query that finds an entity by key. Used during indexing. -/// See also `FindManyQuery`. +/// A query that finds the entities whose `entity_field` references +/// `value`. Used by `loadRelated`. #[derive(Debug)] pub struct FindDerivedQuery<'a> { table: &'a Table, derived_query: &'a DerivedEntityQuery, - excluded_keys: IdList, br_column: BlockRangeColumn<'a>, } @@ -2203,13 +2202,11 @@ impl<'a> FindDerivedQuery<'a> { table: &'a Table, derived_query: &'a DerivedEntityQuery, block: BlockNumber, - excluded_keys: IdList, ) -> Self { let br_column = BlockRangeColumn::new(table, "e.", block); Self { table, derived_query, - excluded_keys, br_column, } } @@ -2235,16 +2232,6 @@ impl<'a> QueryFragment for FindDerivedQuery<'a> { out.push_sql(" from "); out.push_sql(self.table.qualified_name.as_str()); out.push_sql(" e\n where "); - // This clause with an empty array would filter out everything - if !self.excluded_keys.is_empty() { - out.push_identifier(&self.table.primary_key().name)?; - // For truly gigantic `excluded_keys` lists, this will be slow, and - // we should rewrite this query to use a CTE or a temp table to hold - // the excluded keys. - out.push_sql(" != any("); - self.excluded_keys.push_bind_param(&mut out)?; - out.push_sql(") and "); - } out.push_identifier(entity_field.to_snake_case().as_str())?; out.push_sql(" = "); entity_id.push_bind_param(&mut out)?; diff --git a/store/postgres/src/writable.rs b/store/postgres/src/writable.rs index 633688aeb1a..ba64ee15aff 100644 --- a/store/postgres/src/writable.rs +++ b/store/postgres/src/writable.rs @@ -349,11 +349,10 @@ impl SyncStore { &self, key: &DerivedEntityQuery, block: BlockNumber, - excluded_keys: Vec, ) -> Result, StoreError> { retry::forever(&self.logger, "get_derived", || async { self.writable - .get_derived(self.site.cheap_clone(), key, block, &excluded_keys) + .get_derived(self.site.cheap_clone(), key, block) .await }) .await @@ -1344,12 +1343,12 @@ impl Queue { ) -> impl Iterator)> + 'a { batch .effective_ops(&derived_query.entity_type, at) - .filter_map(|op| match op { + .map(|op| match op { EntityOp::Write { key, entity } if is_related(derived_query, entity) => { - Some((key.clone(), Some(entity.clone()))) + (key.clone(), Some(entity.clone())) } - EntityOp::Write { .. } => None, - EntityOp::Remove { key } => Some((key.clone(), None)), + // Removed, or no longer related: still hides the database row + EntityOp::Write { key, .. } | EntityOp::Remove { key } => (key.clone(), None), }) } @@ -1368,16 +1367,14 @@ impl Queue { }, ); - let excluded_keys: Vec = entities_in_queue.keys().cloned().collect(); + let mut items_from_database = self.store.get_derived(derived_query, query_block).await?; - // We filter to exclude the entities ids that we already have from the queue - let mut items_from_database = self - .store - .get_derived(derived_query, query_block, excluded_keys) - .await?; + // A queued change to an id supersedes its database row. Match ids, not + // keys: a batch keeps only the newest change per id across causality + // regions, so a removal can hide behind a write in another region + let queued: BTreeSet<_> = entities_in_queue.keys().map(|key| &key.entity_id).collect(); + items_from_database.retain(|key, _| !queued.contains(&key.entity_id)); - // Extend the store results with the entities from the queue. - // This overwrites any entitiy from the database with the same key from queue let items_from_queue: BTreeMap = entities_in_queue .into_iter() .filter_map(|(key, entity)| entity.map(|entity| (key, entity))) @@ -1546,7 +1543,7 @@ impl Writer { key: &DerivedEntityQuery, ) -> Result, StoreError> { match self { - Writer::Sync(store) => store.get_derived(key, BLOCK_NUMBER_MAX, vec![]).await, + Writer::Sync(store) => store.get_derived(key, BLOCK_NUMBER_MAX).await, Writer::Async { queue, .. } => queue.get_derived(key).await, } } diff --git a/store/test-store/tests/postgres/writable.rs b/store/test-store/tests/postgres/writable.rs index 7c17e8f201f..a73777aaeef 100644 --- a/store/test-store/tests/postgres/writable.rs +++ b/store/test-store/tests/postgres/writable.rs @@ -41,6 +41,18 @@ const SCHEMA_GQL: &str = " id: String!, value: String! } + type Parent @entity { + id: ID!, + children: [Child!]! @derivedFrom(field: \"parent\") + } + type Child @entity { + id: ID!, + parent: Parent! + } + type FileChild @entity { + id: ID!, + parent: Parent! + } type PoolCreated @entity(immutable: true) { id: Bytes!, token0: Bytes!, @@ -69,6 +81,9 @@ lazy_static! { .expect("Failed to parse user schema"); static ref COUNTER_TYPE: EntityType = TEST_SUBGRAPH_SCHEMA.entity_type(COUNTER).unwrap(); static ref COUNTER2_TYPE: EntityType = TEST_SUBGRAPH_SCHEMA.entity_type(COUNTER2).unwrap(); + static ref PARENT_TYPE: EntityType = TEST_SUBGRAPH_SCHEMA.entity_type("Parent").unwrap(); + static ref CHILD_TYPE: EntityType = TEST_SUBGRAPH_SCHEMA.entity_type("Child").unwrap(); + static ref FILE_CHILD_TYPE: EntityType = TEST_SUBGRAPH_SCHEMA.entity_type("FileChild").unwrap(); } /// Inserts test data into the store. @@ -90,7 +105,9 @@ async fn insert_test_data(store: Arc) -> DeploymentLocator }; // Create SubgraphDeploymentEntity - let deployment = DeploymentCreate::new(String::new(), &manifest, None); + // `FileChild` gets a causality region as if a file data source wrote it + let deployment = DeploymentCreate::new(String::new(), &manifest, None) + .entities_with_causality_region(BTreeSet::from([FILE_CHILD_TYPE.clone()])); let name = SubgraphName::new("test/writable").unwrap(); let node_id = NodeId::new("test").unwrap(); @@ -203,6 +220,22 @@ async fn pause_writer(deployment: &DeploymentLocator) { writable::allow_steps(deployment, 0).await; } +/// Assert that the blocks after block 2 are still in the write queue +async fn assert_queued_after_block_2( + store: &Arc, + deployment: &DeploymentLocator, +) { + let head = store + .least_block_ptr(&deployment.hash) + .await + .unwrap() + .map(|ptr| ptr.number); + assert!( + matches!(head, Some(1) | Some(2)), + "blocks after 2 must still be queued, database head is {head:?}" + ); +} + /// Test that looking up entities when several changes to the same entity /// are queued works. When `batch` is true, the changes all reside in one /// batch. If it is false, each change is in its own batch. @@ -316,6 +349,171 @@ fn get_derived_nobatch() { get_with_pending(false, count_get_derived); } +fn set_parent(id: &str, vid: i64) -> EntityOperation { + EntityOperation::Set { + key: PARENT_TYPE.parse_key(id).unwrap(), + data: entity! { TEST_SUBGRAPH_SCHEMA => id: id, vid: vid }, + } +} + +fn set_child(id: &str, parent: &str, vid: i64) -> EntityOperation { + EntityOperation::Set { + key: CHILD_TYPE.parse_key(id).unwrap(), + data: entity! { TEST_SUBGRAPH_SCHEMA => id: id, parent: parent, vid: vid }, + } +} + +fn remove_child(id: &str) -> EntityOperation { + EntityOperation::Remove { + key: CHILD_TYPE.parse_key(id).unwrap(), + } +} + +/// The ids of the children of `parent` according to `get_derived` +async fn children_of(writable: &Arc, parent: &str) -> Vec { + let query = DerivedEntityQuery { + entity_type: CHILD_TYPE.clone(), + entity_field: Word::from("parent"), + value: PARENT_TYPE.parse_id(parent).unwrap(), + causality_region: CausalityRegion::ONCHAIN, + }; + let map = writable.get_derived(&query).await.unwrap(); + let mut ids: Vec = map.keys().map(|k| k.entity_id.to_string()).collect(); + ids.sort(); + ids +} + +/// `get_derived` while the changes of a block are still in the write +/// queue must give the same answer as after they are written. Block 1 +/// (parents `p0`, `p1`; children `w`, `x` under `p0`) is written to the +/// database; block 2 is empty and absorbs a writer that may already be +/// past its pause point; block 3 (`queued`) is held in the queue. +fn derived_with_pending(queued: Vec, expected: &'static [&'static str]) { + run_test(move |store, writable, _, deployment| async move { + let subgraph_store = store.subgraph_store(); + let base = vec![ + set_parent("p0", 1), + set_parent("p1", 2), + set_child("w", "p0", 3), + set_child("x", "p0", 4), + ]; + transact_entity_operations(&subgraph_store, &deployment, block_pointer(1), base) + .await + .unwrap(); + pause_writer(&deployment).await; + transact_entity_operations(&subgraph_store, &deployment, block_pointer(2), vec![]) + .await + .unwrap(); + transact_entity_operations(&subgraph_store, &deployment, block_pointer(3), queued) + .await + .unwrap(); + assert_queued_after_block_2(&subgraph_store, &deployment).await; + let expected: Vec = expected.iter().map(|s| s.to_string()).collect(); + assert_eq!(expected, children_of(&writable, "p0").await, "while queued"); + + writable.flush().await.unwrap(); + assert_eq!(expected, children_of(&writable, "p0").await, "after flush"); + }) +} + +/// Control: one queued removal hides the database row +#[test] +fn get_derived_pending_one_removal() { + derived_with_pending(vec![remove_child("x")], &["w"]); +} + +/// Two queued removals hide both database rows +#[test] +fn get_derived_pending_two_removals() { + derived_with_pending(vec![remove_child("w"), remove_child("x")], &[]); +} + +/// A queued removal plus a queued creation +#[test] +fn get_derived_pending_removal_and_creation() { + derived_with_pending( + vec![remove_child("x"), set_child("y", "p0", 5)], + &["w", "y"], + ); +} + +/// A queued write that moves `x` to another parent must hide the stored `x` +#[test] +fn get_derived_pending_parent_change() { + derived_with_pending(vec![set_child("x", "p1", 5)], &["w"]); +} + +/// The ids of the onchain `FileChild` children of `p0` according to +/// `get_derived`, filtered with `DerivedEntityQuery::matches` as +/// `EntityCache::load_related` does: `get_derived` also returns queued +/// entities from other causality regions +async fn onchain_file_children_of_p0(writable: &Arc) -> Vec { + let query = DerivedEntityQuery { + entity_type: FILE_CHILD_TYPE.clone(), + entity_field: Word::from("parent"), + value: PARENT_TYPE.parse_id("p0").unwrap(), + causality_region: CausalityRegion::ONCHAIN, + }; + let map = writable.get_derived(&query).await.unwrap(); + map.iter() + .filter(|(key, entity)| query.matches(key, entity)) + .map(|(key, _)| key.entity_id.to_string()) + .collect() +} + +/// `x` is written onchain; one queued batch then removes it onchain and a +/// file data source creates its own `x`. The queue only shows the newer +/// `x`, which must still hide the onchain `x` read from the database. +/// Fails if `get_derived` matches database rows by key instead of id. +/// Blocks 3 and 4 share a batch only with write batching enabled +#[test] +fn get_derived_pending_causality_region() { + assert!( + ENV_VARS.store.write_batch_size > 0 && !ENV_VARS.store.write_batch_duration.is_zero(), + "this test needs write batching" + ); + run_test(|store, writable, _, deployment| async move { + let subgraph_store = store.subgraph_store(); + let set_x = |causality_region, vid: i64| EntityOperation::Set { + key: FILE_CHILD_TYPE.parse_key_in("x", causality_region).unwrap(), + data: entity! { TEST_SUBGRAPH_SCHEMA => id: "x", parent: "p0", vid: vid }, + }; + let remove_x = EntityOperation::Remove { + key: FILE_CHILD_TYPE + .parse_key_in("x", CausalityRegion::ONCHAIN) + .unwrap(), + }; + + let transact = |block, ops| { + transact_entity_operations(&subgraph_store, &deployment, block_pointer(block), ops) + }; + transact(1, vec![set_x(CausalityRegion::ONCHAIN, 1)]) + .await + .unwrap(); + pause_writer(&deployment).await; + // Absorbs a writer that may already be past its pause point + transact(2, vec![]).await.unwrap(); + transact(3, vec![remove_x]).await.unwrap(); + transact(4, vec![set_x(CausalityRegion::ONCHAIN.next(), 2)]) + .await + .unwrap(); + assert_queued_after_block_2(&subgraph_store, &deployment).await; + let expected: Vec = vec![]; + assert_eq!( + expected, + onchain_file_children_of_p0(&writable).await, + "while queued" + ); + + writable.flush().await.unwrap(); + assert_eq!( + expected, + onchain_file_children_of_p0(&writable).await, + "after flush" + ); + }) +} + #[test] fn restart() { run_test(|store, writable, _, deployment| async move {