Skip to content

Commit 8013105

Browse files
baxenmbotclaude
authored
Revert "perf(db): stop per-id planning of wide #e reads (#9591)" (#9848)
Reverts #9591 (`perf(db): stop per-id planning of wide #e reads`). Hiding the `#e` id arrays from the planner made reads in large communities much slower in prod. This is a straight revert. ## Evidence - **8 → 9 row cliff on the channel head read with `include_aux`:** 125ms at 8 rows, 1.4s at 9 rows, about 2.3s at 20 rows. - **Replica `EXPLAIN ANALYZE`, 20-id aux query:** 130ms with the ids visible to the planner, 2240ms with them hidden. The hidden plan reads and discards about 625k rows in `events_p2026_07_08_legacy`. - **200-id thread page (1,593-reply thread):** | ids | plan | exec | |---|---|---| | visible (this PR) | 78ms | 1,387ms | | hidden (#9591) | 10ms | 18,146ms | #9591 saves planning time but makes execution about 13x slower. - **Prod:** #9591 reached bb-block prod with `main-20261120032502-8d4b301` (2026-11-20 14:48Z). ## Notes - #9674 used the same trick for thread-window aux reads and had the same risk. It's now closed. - Any future change like this should be checked with `EXPLAIN ANALYZE` on the replica first. A test that runs EXPLAIN against a large community is a follow-up, not part of this PR. ## Testing - `cargo test -p buzz-db --lib e_tag` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Bradley Axen <baxen@squareup.com> Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7382130 commit 8013105

2 files changed

Lines changed: 8 additions & 107 deletions

File tree

‎crates/buzz-db/src/runtime/tests.rs‎

Lines changed: 0 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -3693,56 +3693,6 @@ async fn e_tag_any_runs_with_real_binds_on_p_join_and_count() {
36933693
.expect("miss count"),
36943694
0
36953695
);
3696-
3697-
// A thread-page-wide `#e` set binds its arrays through a scalar subquery;
3698-
// the match must be the same with and without the `#p` join. A newer
3699-
// reply targets two of the ids (one row, newest first), and a decoy holds
3700-
// the root id in a tag that is not an `e` tag at position 1, which the
3701-
// containment probe admits and the positional check must reject.
3702-
let mut wide: Vec<String> = (1..=200).map(|i| format!("{i:064x}")).collect();
3703-
wide.push(fx.root_hex.clone());
3704-
let author = nostr::Keys::generate();
3705-
let mentioned = nostr::PublicKey::from_hex(&fx.mentioned_hex).expect("mentioned key");
3706-
let p_tag = nostr::Tag::public_key(mentioned);
3707-
for (content, e_tags, seconds) in [
3708-
(
3709-
"second-reply",
3710-
vec![
3711-
nostr::Tag::parse(["e", fx.root_hex.as_str()]).expect("e tag"),
3712-
nostr::Tag::parse(["e", wide[0].as_str()]).expect("e tag"),
3713-
],
3714-
20,
3715-
),
3716-
(
3717-
"decoy",
3718-
vec![nostr::Tag::parse(["x", "e", fx.root_hex.as_str()]).expect("decoy tag")],
3719-
30,
3720-
),
3721-
] {
3722-
let event = nostr::EventBuilder::new(nostr::Kind::Custom(9), content)
3723-
.tags(e_tags.into_iter().chain([p_tag.clone()]))
3724-
.custom_created_at(nostr::Timestamp::from((fx.root_seconds + seconds) as u64))
3725-
.sign_with_keys(&author)
3726-
.expect("sign wide-match event");
3727-
insert_top_level(&fx.writer, *fx.cid.as_uuid(), fx.channel, &event).await;
3728-
crate::insert_mentions(&fx.writer, fx.cid, &event, Some(fx.channel))
3729-
.await
3730-
.expect("insert mentions");
3731-
}
3732-
q.e_tags = Some(wide);
3733-
for p_tag in [None, Some(fx.mentioned_hex.clone())] {
3734-
q.p_tag_hex = p_tag;
3735-
let rows = event::query_events(&fx.writer, &q)
3736-
.await
3737-
.expect("wide e-tag select");
3738-
assert_eq!(contents(&rows), vec!["second-reply", "writer-reply"]);
3739-
assert_eq!(
3740-
event::count_events(&fx.writer, &q)
3741-
.await
3742-
.expect("wide e-tag count"),
3743-
2
3744-
);
3745-
}
37463696
}
37473697

37483698
#[path = "tests/thread_window_postgres_tests.rs"]

‎crates/buzz-db/src/store/event.rs‎

Lines changed: 8 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,7 @@ fn push_event_filters(qb: &mut QueryBuilder<sqlx::Postgres>, col_prefix: &str, q
844844
if let Some(ref e_tags) = q.e_tags {
845845
if !e_tags.is_empty() {
846846
qb.push(" AND ");
847-
push_e_tag_match(qb, col_prefix, e_tags);
847+
push_exact_tag_match(qb, col_prefix, "e", e_tags);
848848
}
849849
}
850850

@@ -1316,64 +1316,28 @@ pub(crate) async fn fetch_with_read_deadline(
13161316
/// `[["t","t"]]` is contained in `["t","other"]`, and `[["e",id]]` in
13171317
/// `["x","e",id]`. Over-matching before `LIMIT` lets a non-matching newer row
13181318
/// take the slot, so containment stays only as the GIN-indexed prefilter
1319-
/// (one array bind, so the SQL text does not change with `values`) and the
1320-
/// positional check makes the predicate exact.
1319+
/// (one array-bound test, so planner cost does not scale with `values`) and
1320+
/// the positional check makes the predicate exact.
13211321
fn push_exact_tag_match(
13221322
qb: &mut QueryBuilder<sqlx::Postgres>,
13231323
col_prefix: &str,
13241324
name: &str,
13251325
values: &[String],
13261326
) {
1327-
push_tag_match(qb, col_prefix, name, values, false);
1328-
}
1329-
1330-
/// Above this many `#e` values, [`push_e_tag_match`] hides them from the
1331-
/// planner's selectivity estimate. Hiding plans faster from one value up, but
1332-
/// visible values keep a narrow read's per-value plan; at 8 they cost at most
1333-
/// ~0.6 ms of extra planning.
1334-
const E_TAG_ESTIMATED_VALUES_MAX: usize = 8;
1335-
1336-
/// [`push_exact_tag_match`] for `#e`. Planning a bound array estimates GIN
1337-
/// selectivity once per element in every partition, about 0.07 ms per value:
1338-
/// a 201-id thread-page aux closure spent ~14 ms planning against ~1 ms
1339-
/// executing, on every page, because its custom plan never yields to the
1340-
/// cached generic one. Past [`E_TAG_ESTIMATED_VALUES_MAX`] values the arrays
1341-
/// are read through a scalar subquery, which the planner estimates as one
1342-
/// unknown value (the estimate a cached generic plan already uses for these
1343-
/// reads) while the GIN index still serves the containment at run time.
1344-
fn push_e_tag_match(qb: &mut QueryBuilder<sqlx::Postgres>, col_prefix: &str, values: &[String]) {
1345-
let opaque = values.len() > E_TAG_ESTIMATED_VALUES_MAX;
1346-
push_tag_match(qb, col_prefix, "e", values, opaque);
1347-
}
1348-
1349-
fn push_tag_match(
1350-
qb: &mut QueryBuilder<sqlx::Postgres>,
1351-
col_prefix: &str,
1352-
name: &str,
1353-
values: &[String],
1354-
opaque_values: bool,
1355-
) {
1356-
// `ANY((SELECT $n)::T[])` is an array expression over an InitPlan, while
1357-
// `ANY((SELECT $n))` would compare against a subquery's rows instead.
1358-
let (open, close, text_cast) = if opaque_values {
1359-
("(SELECT ", ")", "::text[]")
1360-
} else {
1361-
("", "", "")
1362-
};
13631327
let containments: Vec<serde_json::Value> = values
13641328
.iter()
13651329
.map(|value| serde_json::json!([[name, value]]))
13661330
.collect();
1367-
qb.push(format!("({col_prefix}tags @> ANY({open}"))
1331+
qb.push(format!("({col_prefix}tags @> ANY("))
13681332
.push_bind(containments)
13691333
.push(format!(
1370-
"{close}::jsonb[]) AND EXISTS (SELECT 1 FROM jsonb_array_elements({col_prefix}tags) AS tag \
1334+
"::jsonb[]) AND EXISTS (SELECT 1 FROM jsonb_array_elements({col_prefix}tags) AS tag \
13711335
WHERE tag->>0 = "
13721336
))
13731337
.push_bind(name.to_owned())
1374-
.push(format!(" AND tag->>1 = ANY({open}"))
1338+
.push(" AND tag->>1 = ANY(")
13751339
.push_bind(values.to_vec())
1376-
.push(format!("{close}{text_cast})))"));
1340+
.push(")))");
13771341
}
13781342

13791343
/// Whether `q` must run as an unnamed statement, so Postgres plans it with the
@@ -1695,7 +1659,7 @@ fn count_events_sql(q: &EventQuery) -> QueryBuilder<sqlx::Postgres> {
16951659
if let Some(ref e_tags) = q.e_tags {
16961660
if !e_tags.is_empty() {
16971661
qb.push(" AND ");
1698-
push_e_tag_match(&mut qb, col_prefix, e_tags);
1662+
push_exact_tag_match(&mut qb, col_prefix, "e", e_tags);
16991663
}
17001664
}
17011665

@@ -3116,19 +3080,6 @@ mod e_tag_filter_shape_tests {
31163080
assert!(!sql[..fence_end].contains("ORDER BY"));
31173081
assert!(!sql[..fence_end].contains("LIMIT"));
31183082
assert!(sql[fence_end..].contains("ORDER BY created_at DESC, id ASC LIMIT "));
3119-
// A wide `#e` set reaches the planner as one unknown value, not 188
3120-
// estimated elements; a narrow one keeps its bound-value estimate.
3121-
assert!(sql.contains("tags @> ANY((SELECT $"));
3122-
assert!(sql.contains("tag->>1 = ANY((SELECT $"));
3123-
for (ids, opaque) in [
3124-
(1, false),
3125-
(E_TAG_ESTIMATED_VALUES_MAX, false),
3126-
(E_TAG_ESTIMATED_VALUES_MAX + 1, true),
3127-
] {
3128-
q.e_tags = Some((0..ids).map(|i| format!("{i:064x}")).collect());
3129-
let qb = build_query_events_sql(&q, Range::All, page_limit(&q));
3130-
assert_eq!(qb.sql().as_str().contains("(SELECT $"), opaque, "{ids} ids");
3131-
}
31323083
}
31333084

31343085
/// Only a one-channel, one-root read of channel-message kinds without a

0 commit comments

Comments
 (0)