Skip to content

Commit 3801bbc

Browse files
richvdhphil-flex
authored andcommitted
Fix a potentially-huge sql query (matrix-org#7274)
We could end up looking up tens of thousands of events, which could cause large amounts of data to be logged to the postgres log.
1 parent 6de707a commit 3801bbc

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

changelog.d/7274.bugfix

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a sql query introduced in Synapse 1.12.0 which could cause large amounts of logging to the postgres slow-query log.

synapse/storage/data_stores/main/event_federation.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -173,19 +173,28 @@ def _get_auth_chain_difference_txn(
173173
for event_id in initial_events
174174
}
175175

176+
# The sorted list of events whose auth chains we should walk.
177+
search = [] # type: List[Tuple[int, str]]
178+
176179
# We need to get the depth of the initial events for sorting purposes.
177180
sql = """
178181
SELECT depth, event_id FROM events
179182
WHERE %s
180-
ORDER BY depth ASC
181183
"""
182-
clause, args = make_in_list_sql_clause(
183-
txn.database_engine, "event_id", initial_events
184-
)
185-
txn.execute(sql % (clause,), args)
184+
# the list can be huge, so let's avoid looking them all up in one massive
185+
# query.
186+
for batch in batch_iter(initial_events, 1000):
187+
clause, args = make_in_list_sql_clause(
188+
txn.database_engine, "event_id", batch
189+
)
190+
txn.execute(sql % (clause,), args)
186191

187-
# The sorted list of events whose auth chains we should walk.
188-
search = txn.fetchall() # type: List[Tuple[int, str]]
192+
# I think building a temporary list with fetchall is more efficient than
193+
# just `search.extend(txn)`, but this is unconfirmed
194+
search.extend(txn.fetchall())
195+
196+
# sort by depth
197+
search.sort()
189198

190199
# Map from event to its auth events
191200
event_to_auth_events = {} # type: Dict[str, Set[str]]

0 commit comments

Comments
 (0)