Partition-aware simplification of constant IN lists after partition pruning

Поиск
Список
Период
Сортировка
Искать

Partition-aware simplification of constant IN lists after partition pruning

От:
baotiao@gmail.com
Дата:
Вложения:
Hi hackers,

A colleague constructed a case with a bigint primary key, 1024 HASH
partitions, and one million rows. I reproduced a performance issue:
partition pruning determines the correct target partition for each
constant in an IN list, but each retained child still receives the
entire list, including IDs that cannot belong to that child.

For example, when 1000 IDs map to 1000 different partitions, each child
has only one relevant ID. Nevertheless, all 1000 child scans have the
same 1000-element ScalarArrayOpExpr. This leads to repeated processing
of the full array during planning and execution.

The attached psql script contains the original constant lists and runs
VACUUM ANALYZE before the queries. It uses ordinary IN (...) clauses,
not an IN (VALUES ...) subquery or an array parameter. The setup is:

    CREATE TABLE prune_repro (
        id bigint NOT NULL PRIMARY KEY
    ) PARTITION BY HASH (id);

    -- Create 1024 partitions, modulus 1024, remainders 0..1023.
    -- Insert generate_series(1, 1000000).

I tested the attachment on PostgreSQL 18.6, arm64 macOS, with
shared_buffers=128MB, enable_partition_pruning=on,
max_parallel_workers_per_gather=0, and jit=off. One run of
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) gave:

    Case                      IDs   Partitions  Planning ms  Execution ms
    All IDs in one partition  953       1          0.576         0.051
    One ID per partition     1000    1000        116.780        55.116

These are illustrative timings, not a benchmark of the cost of IN
processing alone. The queries return 953 and 1000 rows respectively;
the script also checks count(DISTINCT tableoid). The second plan has
exactly 1000 child scans, so the remaining 24 partitions are pruned.
I also observed the same behavior in a local 19devel checkout at
f2d7570cdde75fd67acb279063b2701806662035.

A representative child from the second query is shown below, with the
array elided for readability:

    Seq Scan on prune_repro_p0
      (cost=2.50..22.02 rows=624 width=0)
      (actual rows=1.00 loops=1)
      Filter: (id = ANY ('{all 1000 IDs}'::bigint[]))
      Rows Removed by Filter: 967

Across the 1000 child scans, the sum of estimated rows is 706992,
whereas the actual output is 1000 rows. The plan chooses sequential
scans and examines 976466 rows. VACUUM ANALYZE does not resolve this.

Looking at the implementation, scalararraysel() processes the full
constant array independently for each retained child. For this bigint
IN list, execution uses hashed ScalarArrayOpExpr evaluation, but each
child's ExprState builds its own hash table from the full array. This
is repeated array processing across children, rather than a linear
search through all 1000 IDs for every scanned row.

Would it make sense to use the partition bounds to simplify constant
ScalarArrayOpExpr quals for each child? For this single-column HASH
key case, each constant can already be mapped to its partition during
pruning. Passing only the relevant constants to each child, and
reducing a singleton list to an equality, could both reduce repeated
work and improve the child row estimates and scan choices. I have not
implemented a patch yet; I would appreciate feedback on the approach
and where such simplification should fit in the planner.

I found two related discussions:

[1] Optimize planner memory consumption for huge arrays
    https://www.postgresql.org/message-id/CAExHW5sUuN7JGp1rdGhg2B_SLvcRAVPc3cM-hOV0mf8K_HfQhQ%40mail.gmail.com

    This discusses array selectivity estimation work being repeated
    for each partition, primarily from the memory-consumption angle.

[2] avoid bitmapOR-ing indexes with scan condition inconsistent with
    partition constraint
    https://www.postgresql.org/message-id/228337.1605212074%40sss.pgh.pa.us

    This discusses simplifying child restrictions using partition
    constraints and using the result in row estimates, but also notes
    the inability to prove clauses from satisfies_hash_partition().

Regards,
Baotiao

Re: Partition-aware simplification of constant IN lists after partition pruning

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Baotiao,

I reproduced your case on 18.6, on 19devel at the commit you named
(f2d7570cdde), and on master; all three observations hold exactly --
1000 seq-scan children each carrying the full 1000-element array, the
706992-vs-1000 estimate, and ~976k rows examined.

The measurement that stood out is that the dominant cost is plan choice,
not the repeated array work.  Keeping the full array but forcing the
index only drops execution (same 706992 estimate, 1000 rows read).
Giving each child only the one constant that maps to it takes the
estimate to 1, so the planner picks the index on its own, and the whole
query goes from ~185 ms to ~25 ms here (-87%).

> each child's ExprState builds its own hash table from the full array.
> This is repeated array processing across children

The hash tables are cheap to build (under 0.5% of the profile); the
execution cost is probing them once per row of the seq scan the estimate
caused.  And reducing a singleton to id = C barely moves anything
(~0.45 ms over all 1000 children) -- what moves the plan is each child
seeing only its own constants.

On planning, scalararraysel is ~93% of it: one eqsel per element per
child, each redoing examine_variable / selectivity / aclcheck, so with
one id per partition it grows as children x constants.  In a sweep here
the child plans flip from index to seq between 250 and 500 ids, which is
the estimate crossing over.

> Would it make sense to use the partition bounds to simplify constant
> ScalarArrayOpExpr quals for each child?

For the hash case the irrelevant constants cannot be dropped the way [2]
does it, since satisfies_hash_partition() is not something predtest can
refute.  But pruning already maps each constant to its partition to reach
the 1000 live children, so that mapping exists at that point; reusing it
to restrict each child's array to the constants that reach it looks more
tractable than proving anything from the hash constraint.  The range/list
case is the one that could instead ride the partition-constraint approach
in [2].

One caveat on the numbers: my "split" is a UNION ALL with a Subquery Scan
per child, so its execution is an upper bound on what an in-place rewrite
would achieve; and I measured on x86 with autovacuum off, while you were
on arm64 macOS.

Happy to share the full script and numbers if useful.

Regards,
Manu


Re: Partition-aware simplification of constant IN lists after partition pruning

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi zthhh,

> In my test, the original IN query already uses Parallel Index Only Scans.
> Each of the 1000 scanned partitions returns one row, with zero heap
> fetches, and all buffer accesses are hits. Nevertheless, execution takes
> about 987 ms.

You're right that the cost isn't just the seq-scan choice, and it isn't the
index work either.  I reproduced your plan shape on 18.6, on 19devel
(f2d7570) and on master; all three agree.

Each child reports "Index Searches: 1" -- one descent per child, not one per
array element.  The time is in shipping the plan to the parallel workers.
Under perf, the leader spends ~41% in nodeToString -> outDatum, printing each
child's 1000-element bigint array byte by byte, and the workers spend ~37% in
stringToNode -> readDatum parsing them back; the index probes are ~2.6%.  In
your plan the Gather returns its first row at 651 of 973 ms; in the same shape
here, 287 of 418 ms, while the 1000 child scans together take 17.7 ms.

Toggling only parallelism on the same full-array index plan, execution goes
from 14.0 ms to 419 ms.  The same plan with the Gather but 0 workers launched
is still 290 ms: the leader serializes the plan anyway, and the 1000-element
array is in every child.

Even serially, the full array still costs at execution with the index: 14.0 ms
vs 5.9 ms when each child carries only its own constant, because
_bt_preprocess_keys sorts and de-dups the 1000 keys per child before its
single descent.

So the restriction helps both cases, for different reasons: it takes the
estimate to 1 (which is what picked the seq scan in the original report) and
it shrinks what each child preprocesses and what the Gather ships.  Measured
against today's IN, same binary: the serial seq-scan case is 186.8 ms wall
(planning 129.5, execution 42.9); your VALUES rewrite is 25.4 ms (planning
10.5, execution 13.5); and restricting each child's array in place is 29.0 ms
(planning 21.5, execution 5.9).  That is an 84% wall drop in the serial case
and 94% in your parallel shape; with the estimate corrected the planner no
longer parallelizes at all.  The VALUES rewrite is a good workaround that
needs no planner change.

For where a fix would live: pruning already maps each constant to its
partition once (prune_append_rel_partitions is ~1% here), and that mapping is
in hand in expand_partitioned_rtentry, where restricting each live child to
its own constants gives the right 1000 rows.  Range and list partitioning
could instead refute the irrelevant constants through the partition
constraint, but hash cannot, since satisfies_hash_partition() isn't something
predtest can refute -- reusing pruning's mapping is the route that also covers
hash.

I couldn't match your exact cost settings (your child index-only scan is
priced at 352 vs 25.9 here), so I reproduced both of your plan shapes with
explicit knobs rather than inferring them.

Attached are the measurements (scenarios, timings with 95% CIs, and the perf
breakdown), the raw median/CI summary, and the throwaway prototype I used to
bound the benefit -- measurement-only, single-column hash, not a proposal.
The full logs and repro harness are available if useful.

Regards,
Manu
FAQ