Skip to content
Open
Show file tree
Hide file tree
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
5 changes: 1 addition & 4 deletions store/postgres/src/deployment_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1100,13 +1100,10 @@ impl DeploymentStore {
site: Arc<Site>,
derived_query: &DerivedEntityQuery,
block: BlockNumber,
excluded_keys: &[EntityKey],
) -> Result<BTreeMap<EntityKey, Entity>, 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(
Expand Down
5 changes: 1 addition & 4 deletions store/postgres/src/relational.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,12 +664,9 @@ impl Layout {
conn: &mut AsyncPgConnection,
derived_query: &DerivedEntityQuery,
block: BlockNumber,
excluded_keys: &[EntityKey],
) -> Result<BTreeMap<EntityKey, Entity>, 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();

Expand Down
17 changes: 2 additions & 15 deletions store/postgres/src/relational_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2188,13 +2188,12 @@ impl<'a> Query for FindManyQuery<'a> {

impl<'a, Conn> RunQueryDsl<Conn> 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>,
}

Expand All @@ -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,
}
}
Expand All @@ -2235,16 +2232,6 @@ impl<'a> QueryFragment<Pg> 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)?;
Expand Down
27 changes: 12 additions & 15 deletions store/postgres/src/writable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,11 +349,10 @@ impl SyncStore {
&self,
key: &DerivedEntityQuery,
block: BlockNumber,
excluded_keys: Vec<EntityKey>,
) -> Result<BTreeMap<EntityKey, Entity>, 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
Expand Down Expand Up @@ -1344,12 +1343,12 @@ impl Queue {
) -> impl Iterator<Item = (EntityKey, Option<Entity>)> + '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),
})
Comment on lines +1346 to 1352

@dimitrovmaksim dimitrovmaksim Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#6458 introduced skipDuplicates for immutable entities: a duplicate insert doesn't fail the subgraph; when it reaches the table, ON CONFLICT DO NOTHING drops it, so the stored version stays.

With that in mind, does "a newer queued version supersedes the database row" hold for a queued duplicate of a skipDuplicates entity? For example, with a stored t { parent: p0 } and a queued duplicate t { parent: p1 }, what does loadRelated(p0) return while the block is queued, and after the flush?

Not sure how often skipDuplicates is used, but it is a real path.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I traced this through and it's real, and slightly wider than get_derived.

With a stored t { parent: p0 } and a queued duplicate t { parent: p1 } in a later block (so RowGroup::append_row doesn't see the original and the duplicate is queued; the insert's ON CONFLICT DO NOTHING discards it at write time):

Read while queued master this PR after flush
get(t) p1 p1 p0
loadRelated(p0) t nothing t
loadRelated(p1) t t nothing

So get and loadRelated(p1) already return the duplicate on master, and this PR adds loadRelated(p0). There's also a cache-side variant: EntityCache::as_modifications inserts the duplicate's data into the entity LFU cache, so later blocks can read it until it's evicted.

One way to fix all read paths at once is to drop these inserts before they're queued, since they're no-ops once written:

// in WritableStore::transact_block_operations, before Batch::new  
let keys: BTreeSet<EntityKey> = mods  
    .iter()  
    .filter(|m| matches!(m, EntityModification::Insert { .. })  
        && m.key().entity_type.skip_duplicates())  
    .map(|m| m.key().clone())  
    .collect();  
if !keys.is_empty() {  
    let existing = self.writer.get_many(keys).await?;  
    mods.retain(|m| !(matches!(m, EntityModification::Insert { .. })  
        && m.key().entity_type.skip_duplicates()  
        && existing.contains_key(m.key())));  
}  

On top of that, as_modifications should not cache keys of skipDuplicates types it produced a modification for, so later blocks read them from the store. This costs one get_many per block that inserts skipDuplicates entities. Other types are unaffected.

A store test for the scenario above: write t { parent: p0 } and flush, pause the writer, queue t { parent: p1 }, then check get(t), loadRelated(p0) and loadRelated(p1) before and after the flush. It fails on master at get(t) and passes with the change. Happy to open this as a separate PR if you'd prefer to keep this one to get_derived.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @chriswessels, it probably makes sense as a separate PR, so feel free to open one and I'll review it.

}

Expand All @@ -1368,16 +1367,14 @@ impl Queue {
},
);

let excluded_keys: Vec<EntityKey> = 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<EntityKey, Entity> = entities_in_queue
.into_iter()
.filter_map(|(key, entity)| entity.map(|entity| (key, entity)))
Expand Down Expand Up @@ -1546,7 +1543,7 @@ impl Writer {
key: &DerivedEntityQuery,
) -> Result<BTreeMap<EntityKey, Entity>, 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,
}
}
Expand Down
200 changes: 199 additions & 1 deletion store/test-store/tests/postgres/writable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!,
Expand Down Expand Up @@ -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.
Expand All @@ -90,7 +105,9 @@ async fn insert_test_data(store: Arc<DieselSubgraphStore>) -> 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();

Expand Down Expand Up @@ -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<DieselSubgraphStore>,
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.
Expand Down Expand Up @@ -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<dyn WritableStore>, parent: &str) -> Vec<String> {
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<String> = 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<EntityOperation>, 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<String> = 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<dyn WritableStore>) -> Vec<String> {
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<String> = 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 {
Expand Down
Loading