From b8f662b68043f022997d2f755e2a5dfe2d594835 Mon Sep 17 00:00:00 2001 From: madumas Date: Sat, 3 Oct 2026 20:46:46 -0400 Subject: [PATCH 1/3] store: Exclude every listed key in FindDerivedQuery `id != any($excluded)` holds as soon as the id differs from one element of the array, so with two or more excluded keys no row was excluded. `Queue::get_derived` reads the database at the block before the queue and relies on this list to hide children that queued blocks remove or rewrite, so `loadRelated` could return entities that a queued block had already removed. Use `id <> all($excluded)`. Add store tests that hold the writer and call `get_derived` while the block is queued: one removal (control), two removals, and a removal plus a creation. --- store/postgres/src/relational_queries.rs | 4 +- store/test-store/tests/postgres/writable.rs | 106 ++++++++++++++++++++ 2 files changed, 109 insertions(+), 1 deletion(-) diff --git a/store/postgres/src/relational_queries.rs b/store/postgres/src/relational_queries.rs index d87b950adc1..60ada6e1622 100644 --- a/store/postgres/src/relational_queries.rs +++ b/store/postgres/src/relational_queries.rs @@ -2241,7 +2241,9 @@ impl<'a> QueryFragment for FindDerivedQuery<'a> { // 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("); + // `id <> all(..)` excludes every listed key; `id != any(..)` + // would hold for any row once two or more keys are listed + out.push_sql(" <> all("); self.excluded_keys.push_bind_param(&mut out)?; out.push_sql(") and "); } diff --git a/store/test-store/tests/postgres/writable.rs b/store/test-store/tests/postgres/writable.rs index 7c17e8f201f..5ade4c2c558 100644 --- a/store/test-store/tests/postgres/writable.rs +++ b/store/test-store/tests/postgres/writable.rs @@ -41,6 +41,14 @@ 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 PoolCreated @entity(immutable: true) { id: Bytes!, token0: Bytes!, @@ -69,6 +77,8 @@ 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(); } /// Inserts test data into the store. @@ -316,6 +326,102 @@ 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(); + let head = subgraph_store + .least_block_ptr(&deployment.hash) + .await + .unwrap() + .map(|ptr| ptr.number); + assert!( + matches!(head, Some(1) | Some(2)), + "block 3 must still be queued, database head is {head:?}" + ); + 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 is excluded (worked before the fix) +#[test] +fn get_derived_pending_one_removal() { + derived_with_pending(vec![remove_child("x")], &["w"]); +} + +/// Two queued removals: with `!= any(..)` nothing was excluded +#[test] +fn get_derived_pending_two_removals() { + derived_with_pending(vec![remove_child("w"), remove_child("x")], &[]); +} + +/// A queued removal plus a queued creation: two excluded keys +#[test] +fn get_derived_pending_removal_and_creation() { + derived_with_pending( + vec![remove_child("x"), set_child("y", "p0", 5)], + &["w", "y"], + ); +} + #[test] fn restart() { run_test(|store, writable, _, deployment| async move { From 78e60f0457f401103e3c3d3b27d150ed09cf9aa0 Mon Sep 17 00:00:00 2001 From: madumas Date: Sat, 3 Oct 2026 20:48:09 -0400 Subject: [PATCH 2/3] store: Exclude queued keys no longer related in get_derived In `Queue::get_derived`, a queued write whose `@derivedFrom` field no longer points to the parent was dropped instead of excluding its key. The database, read at the block before the queue, then still returned the previous version of that child under the old parent, so `loadRelated` could return a child that a queued block had moved to another parent. A newer queued version always supersedes the database row, related or not: exclude its key. Add a store test that moves a child to another parent in a queued block. --- store/postgres/src/writable.rs | 10 ++++++---- store/test-store/tests/postgres/writable.rs | 6 ++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/store/postgres/src/writable.rs b/store/postgres/src/writable.rs index 633688aeb1a..3ff7f3ea3d6 100644 --- a/store/postgres/src/writable.rs +++ b/store/postgres/src/writable.rs @@ -1344,12 +1344,14 @@ 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)), + // A newer queued version supersedes the database row even + // when it is no longer related: exclude its key + EntityOp::Write { key, .. } => (key.clone(), None), + EntityOp::Remove { key } => (key.clone(), None), }) } diff --git a/store/test-store/tests/postgres/writable.rs b/store/test-store/tests/postgres/writable.rs index 5ade4c2c558..5fa3ad34ebf 100644 --- a/store/test-store/tests/postgres/writable.rs +++ b/store/test-store/tests/postgres/writable.rs @@ -422,6 +422,12 @@ fn get_derived_pending_removal_and_creation() { ); } +/// A queued write that moves `x` to another parent must exclude `x` +#[test] +fn get_derived_pending_parent_change() { + derived_with_pending(vec![set_child("x", "p1", 5)], &["w"]); +} + #[test] fn restart() { run_test(|store, writable, _, deployment| async move { From 18e452b28182790429c72447e22a11d7dcbfbe07 Mon Sep 17 00:00:00 2001 From: Maksim Dimitrov Date: Mon, 23 Nov 2026 13:47:40 +0200 Subject: [PATCH 3/3] store: Filter queued ids from get_derived in Rust Queue::get_derived now loads the matching database rows and drops those whose id has a queued change, instead of sending every queued id of the type to Postgres as an exclusion array. Results are unchanged: the SQL already excluded by id, and FindDerivedQuery has no LIMIT or ORDER BY. Add a store test where a queued batch removes an onchain entity and a file data source recreates its id; it fails if database rows are matched by key instead of id. --- store/postgres/src/deployment_store.rs | 5 +- store/postgres/src/relational.rs | 5 +- store/postgres/src/relational_queries.rs | 19 +--- store/postgres/src/writable.rs | 25 ++--- store/test-store/tests/postgres/writable.rs | 114 +++++++++++++++++--- 5 files changed, 114 insertions(+), 54 deletions(-) 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 60ada6e1622..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,18 +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. - // `id <> all(..)` excludes every listed key; `id != any(..)` - // would hold for any row once two or more keys are listed - out.push_sql(" <> all("); - 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 3ff7f3ea3d6..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 @@ -1348,10 +1347,8 @@ impl Queue { EntityOp::Write { key, entity } if is_related(derived_query, entity) => { (key.clone(), Some(entity.clone())) } - // A newer queued version supersedes the database row even - // when it is no longer related: exclude its key - EntityOp::Write { key, .. } => (key.clone(), None), - EntityOp::Remove { key } => (key.clone(), None), + // Removed, or no longer related: still hides the database row + EntityOp::Write { key, .. } | EntityOp::Remove { key } => (key.clone(), None), }) } @@ -1370,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))) @@ -1548,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 5fa3ad34ebf..a73777aaeef 100644 --- a/store/test-store/tests/postgres/writable.rs +++ b/store/test-store/tests/postgres/writable.rs @@ -49,6 +49,10 @@ const SCHEMA_GQL: &str = " id: ID!, parent: Parent! } + type FileChild @entity { + id: ID!, + parent: Parent! + } type PoolCreated @entity(immutable: true) { id: Bytes!, token0: Bytes!, @@ -79,6 +83,7 @@ lazy_static! { 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. @@ -100,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(); @@ -213,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. @@ -384,15 +407,7 @@ fn derived_with_pending(queued: Vec, expected: &'static [&'stat transact_entity_operations(&subgraph_store, &deployment, block_pointer(3), queued) .await .unwrap(); - let head = subgraph_store - .least_block_ptr(&deployment.hash) - .await - .unwrap() - .map(|ptr| ptr.number); - assert!( - matches!(head, Some(1) | Some(2)), - "block 3 must still be queued, database head is {head:?}" - ); + 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"); @@ -401,19 +416,19 @@ fn derived_with_pending(queued: Vec, expected: &'static [&'stat }) } -/// Control: one queued removal is excluded (worked before the fix) +/// 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: with `!= any(..)` nothing was excluded +/// 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: two excluded keys +/// A queued removal plus a queued creation #[test] fn get_derived_pending_removal_and_creation() { derived_with_pending( @@ -422,12 +437,83 @@ fn get_derived_pending_removal_and_creation() { ); } -/// A queued write that moves `x` to another parent must exclude `x` +/// 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 {