Skip to content

Commit 0042740

Browse files
committed
perf(postgresql): replace correlated NOT EXISTS with set-based EXCEPT in prune_stale_cooccurrences
The original Pass-3 correlated NOT EXISTS self-join evaluates per-row against unit_entities, hitting a 300s statement_timeout on large graphs (50K+ entities, 1M+ unit_entities). The set-based EXCEPT rewrite materializes the stale cooccurrence set once and deletes against it — same result, ~90x faster (~3.4s vs 300s for 5.7K stale rows). Closes #2660
1 parent 327aa05 commit 0042740

1 file changed

Lines changed: 17 additions & 13 deletions

File tree

hindsight-api-slim/hindsight_api/engine/db/ops_postgresql.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -389,22 +389,26 @@ async def prune_stale_cooccurrences(
389389
entities_table: str,
390390
bank_id: str,
391391
) -> int:
392-
# Scope by joining through entities.bank_id (entity_cooccurrences itself
393-
# has no bank_id column — entities don't span banks, so scoping via
394-
# entity_id_1 is sufficient).
392+
# Materialize the stale cooccurrence target set via EXCEPT and delete
393+
# set-wise. The correlated NOT EXISTS self-join (original Pass-3) evaluates
394+
# per-row and hits a 300s statement_timeout on large graphs (50K+ entities,
395+
# 1M+ unit_entities). The set-based EXCEPT form evaluates once and the
396+
# DELETE joins against the materialized stale set — same result, ~90x faster.
395397
result = await conn.execute(
396398
f"""
397399
DELETE FROM {ec_table} c
398-
USING {entities_table} e
399-
WHERE e.id = c.entity_id_1
400-
AND e.bank_id = $1
401-
AND NOT EXISTS (
402-
SELECT 1
403-
FROM {ue_table} u1
404-
JOIN {ue_table} u2 ON u1.unit_id = u2.unit_id
405-
WHERE u1.entity_id = c.entity_id_1
406-
AND u2.entity_id = c.entity_id_2
407-
)
400+
USING (
401+
SELECT c2.entity_id_1, c2.entity_id_2
402+
FROM {ec_table} c2
403+
JOIN {entities_table} e ON e.id = c2.entity_id_1
404+
WHERE e.bank_id = $1
405+
EXCEPT
406+
SELECT DISTINCT u1.entity_id, u2.entity_id
407+
FROM {ue_table} u1
408+
JOIN {ue_table} u2 ON u1.unit_id = u2.unit_id
409+
) AS stale
410+
WHERE c.entity_id_1 = stale.entity_id_1
411+
AND c.entity_id_2 = stale.entity_id_2
408412
""",
409413
bank_id,
410414
)

0 commit comments

Comments
 (0)