Re: pg_*_advice: tsv load failure, etc.

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

Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Aug 27, 2026 at 1:18 PM Noah Misch  wrote:
> An Opus 4.8 review of pg_*_advice commits wrote test cases, attached, for
> several malfunctions.  The test patch also contains its markdown report.  A
> lot of its findings are more like long-term bugfix opportunities than open
> items, but I recommend treating at least these as an open item batch:
>
> ### 1. An empty (non-NULL) stashed advice string persists a TSV line the loader rejects

That's a bug.

> ### 3. pg_start_stash_advice_worker() destroys an existing pg_stash_advice.tsv when persistence was off at boot, silently losing all persisted advice
>
> I wasn't 100% convinced this is unintentional, but Opus is more convinced.
> Worth a look from you.

This seems like complaining that when you turn the lights off the room
gets really dark. You should only start the worker if you're hoping
for what is currently in memory to get written out to disk. In this
example, what's in memory is nothing, so the file is removed instead.

> ### 14. Stash-supplied advice silently overrides an explicitly-set pg_plan_advice.advice for the same query; the precedence is documented nowhere
>
> I do feel the GUC should preempt the stash.  Best to solidify this behavior
> before release.

IMHO, it's impossible to look at
pg_plan_advice_get_supplied_query_advice() and think that the current
behavior was anything but intentional. Of course, that doesn't mean
it's optimal, but if you'd like to propose changing it, I suggest
starting a new thread on that specific topic and making some kind of
argument for your preferred behavior. I suspect a lot of people are
going to think that this thread is just about bug-fixing, rather than
proposed behavior changes. I'm fine with changing this if others
agree.

> Here's the second tier, as I see it:
>
> ### 5. pg_plan_advice.advice / stash advice changes are silently ignored by an already-cached generic plan

This is a planner control feature; it does not affect behavior other
than at plan time. I don't see that as a bug. That said, I think it
would be perfectly valid for someone to try to figure a way for advice
stash changes to invalidate plans, but I suspect that will require
significant new infrastructure. Plan invalidation is generally tied to
catalog modifications, and here we would instead want to tie it to a
plan ID. We could do that by adding a custom invalidation type to
sinval.h just for the use of pg_stash_advice, but would be a pretty
serious piece of core infrastructure for an as-yet-unproven contrib
module to use to solve a problem which (for all we know now) may have
little practical impact.

> ### 8. pg_set_stashed_advice stores advice with no syntax validation, so malformed advice is accepted then emits a plan-time WARNING on every execution and applies nothing

I'm not saying we couldn't change this, but I think changing it right
before release would be a questionable decision. The revised behavior
would probably be nicer for users, but I think it would only be
slightly nicer. Also, we should weigh any potential benefit against
the risk of messing something up under time pressure. Overall, I feel
like this is a feature request that is arriving about six months too
late. If someone feels motivated to work on it, they can do it for
v20. It would be a backward-incompatibility, but I think the number of
people intentionally storing invalid strings in their advice stashes
will be very small, so I don't think it would be enough of a backward
incompatibility to worry about.

Looking through the other findings in this report:

#2 suggests that we should add a CHECK_FOR_INTERRUPTS() call in some
code path. That seems like a bug fix to me, so I'll work on that.

#4 says GEQO doesn't know about plan advice. That's true. The observed
behavior is implied by this statement in the documentation: "... the
use of plan advice can only affect which plan the planner chooses from
among those it believes to be viable. It can never force the choice of
a plan which the planner refused to consider in the first place."
Maybe we should add a specific mention of GEQO. I see that an XXX
about GEQO has crept into the committed version of
contrib/pg_plan_advice/README, and that should be replaced with
something more appropriate.

#6 purports to be a bug, but seems like pedantry.

#7 looks like it might be a real bug. I will investigate.

#9 is wrong about what the behavior should be. There could be an
argument for tidying something up here, but I don't think it really
matters.

#10 is similar to #7 and might also be a real bug. I will investigate.

#11 doesn't seem valid. I had no intent of making that case work as
described, and I don't think it would be useful.

#12 is already fixed.

#13 seems like there might be some behavior in there that somebody
might like to change for some reason at some point, but there's no
clear defect.

#15 and #16 are design behavior.

#17 seems like another place where maybe there's some room for
improvement and maybe there isn't, but I don't think we need to worry
about it right now.

#18 is bogus.

#19 might be a real bug, but needs validation, and can't be easily
validated with in-core code.

#20 seems like it might be suboptimal behavior, but it's not
immediately clear to me what would be better, and it seems unlikely to
matter very much in practice. I'm open to proposed changes if someone
wants to spend time thinking about this.

Overall, I think this report does more to show that this feature is
good shape than otherwise. Claude's best candidate for a major bug
only affects users who stash advice strings for queries that don't
need a stashed advice string. Certainly, that and a few of the other
things shown here are worth correcting, but if somebody showed me the
subset of this list that actually consists of valid issues and told me
that was what we'd had to fix in 19.1 or 19.2 or whatever, I would be
genuinely delighted that we had somehow gotten enough people using
pg_plan_advice and pg_stash_advice to find this kind of thing.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
Вложения:
On Fri, Aug 28, 2026 at 10:21 AM Robert Haas  wrote:
> That's a bug.

Here's a patch. Still working on the rest.

-- 
Robert Haas
EDB: http://www.enterprisedb.com

Re: pg_*_advice: tsv load failure, etc.

От:
Noah Misch <noah@leadboat.com>
Дата:
On Fri, Aug 28, 2026 at 10:21:29AM -0400, Robert Haas wrote:
> On Thu, Aug 27, 2026 at 1:18 PM Noah Misch  wrote:
> > ### 14. Stash-supplied advice silently overrides an explicitly-set pg_plan_advice.advice for the same query; the precedence is documented nowhere
> >
> > I do feel the GUC should preempt the stash.  Best to solidify this behavior
> > before release.
> 
> IMHO, it's impossible to look at
> pg_plan_advice_get_supplied_query_advice() and think that the current
> behavior was anything but intentional. Of course, that doesn't mean
> it's optimal, but if you'd like to propose changing it, I suggest
> starting a new thread on that specific topic and making some kind of
> argument for your preferred behavior. I suspect a lot of people are
> going to think that this thread is just about bug-fixing, rather than
> proposed behavior changes. I'm fine with changing this if others
> agree.

I agree the pg_plan_advice implementation gives what the code calls "advisors"
precedence over this GUC.  I opined this way because, as a user, I expect
more-specific knobs to override less-specific knobs.  The stash is the less
specific of the two.  That said, I don't plan to pursue this precedence
question further.

> > Here's the second tier, as I see it:
> >
> > ### 5. pg_plan_advice.advice / stash advice changes are silently ignored by an already-cached generic plan
> 
> This is a planner control feature; it does not affect behavior other
> than at plan time. I don't see that as a bug. That said, I think it
> would be perfectly valid for someone to try to figure a way for advice
> stash changes to invalidate plans, but I suspect that will require
> significant new infrastructure. Plan invalidation is generally tied to
> catalog modifications, and here we would instead want to tie it to a
> plan ID. We could do that by adding a custom invalidation type to
> sinval.h just for the use of pg_stash_advice, but would be a pretty
> serious piece of core infrastructure for an as-yet-unproven contrib
> module to use to solve a problem which (for all we know now) may have
> little practical impact.

True, best to leave that as-is.


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
Вложения:
On Fri, Sep 4, 2026 at 3:40 PM Robert Haas  wrote:
> There are still some more things to fix here, so I'll keep working on
> this next week.

Here is a new patch set. Since my last update, I have committed the
previous 0001 as dc33cca1859e2d2500ee8f3c0e564561428b4fcf and the
previous 0002 as 1129570f654e96d45bbc63397079171af29710b9. In this new
patch set, 0001 and 0002 correspond to the previous 0003 and 0004, and
improve the code and documentation in terms of how this feature
interacts with GEQO.

0003 from this patch set corresponds to the previous 0005, but the
scope has been expanded to fix additional problems in the same area of
the code. Generally, all of these problems stem from advice
enforcement (which tries to make the plan obey the advice) being out
of step with advice feedback (which says whether the plan actually did
obey the advice). As far as I have found so far, those things are in
lock step for all of the cases that test_plan_advice exercises, or to
say it differently, they're in lock step for all the kinds of advice
that pg_plan_advice generates itself. But if you write your own custom
advice strings, you can do things that are legal but not what the
advice generator would have done, and then problems ensue. For
example, you could write JOIN_ORDER((a b) c) instead of the more
intuitive JOIN_ORDER(a b c); the meaning is identical either way. This
patch fixes several of the worst issues; see the commit message for
details. There are also some cases that it doesn't fix. I know of two
such cases, one easy and one hard.

The easy problem is with zero-element sublists, like JOIN_ORDER(a ()).
I suspect the correct thing to do is reject this case in the advice
string parser, similar to what
8c9c2e5c09aeda713640ccb26bfca0fdccc310d5 did for FOREIGN_JOIN. I have
not deeply investigated this yet so maybe there's some wrinkle that
needs considering, but I expect fixing this to be straightforward.

The hard problem is finding #10 from Noah's original report, which is
the case where you have two partitions of the same parent table that
have the same name but are in different schemas, and you omit the
schema name from the relation identifier. That is, you have a table,
let's say foo, with partitions bar.foopart and baz.foopart. Instead of
writing something like SEQ_SCAN(foo/bar.foopart) as the advice
generator would do, you choose to write SEQ_SCAN(foo/foopart), making
it ambiguous which child relation you're talking about. What happens
right now is that advice enforcement will enforce that restriction
against both children, but advice feedback will think that doesn't
affect either one, so if you look at the advice feedback with EXPLAIN
or print it out via pg_plan_advice.feedback_warnings, you'll see
"matched, failed" instead of just "matched". Obviously, this kind of
sucks. Of course, the blast radius is limited by the fact that almost
nobody names their partitions this way, but theoretically they could
and nobody likes features that work most of the time.

Unfortunately, it is not at all straightforward to fix this. Pretty
much everything the advice feedback code starts by mapping each
relation identifier to an RTI, and giving up if the number of matches
is not exactly 1. Since the whole purpose of relation identifiers is
to map uniquely to relations appearing in the query, this is in
general fine, but the case described in the previous paragraph breaks
it. Generalizing the logic in the advice feedback code to be able to
handle a relation identifier that maps to multiple RTIs looks like a
bad idea. It would require massive adjustments to the code for a case
that almost nobody has in real life, and the resulting code would be
complicated and hard to understand and probably have corner cases
where the performance is terrible. So I think something else has to
give. A possible zero-order solution is to just document that advice
feedback isn't guaranteed to work properly if you do this, so maybe
you shouldn't. That is obviously not amazing but I think we could live
with it for v19. What I'm thinking is probably better is to impose a
restriction sufficient to keep this case from arising in the first
place, such as:

1. Just rip out all the logic that allows the partition schema to be
omitted, and require it always. This is only sad for people writing
advice strings manually, since generated advice always includes the
schema anyway.

2. Refuse to enforce advice if the partition schema is omitted and
there's more than one partition with the same partition name. This
changes the rule from "you can leave out the partition schema" to "you
can leave out the partition schema when no ambiguity is thereby
created," and it makes the existing behavior of the advice feedback
system correct in retrospect. This seems like it would make just about
nobody sad and therefore be just about perfect, except that I am not
sure there's any way of implementing it that doesn't result in causing
even bigger problems that the one it's trying to solve. More
investigation needed.

Or maybe there is another idea that is better than either of those; I
need to look into this further.

-- 
Robert Haas
EDB: http://www.enterprisedb.com

Re: pg_*_advice: tsv load failure, etc.

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Wed, Sep 9, 2026 at 7:16 PM Robert Haas  wrote:
>
> The hard problem is finding #10 from Noah's original report, which is
> the case where you have two partitions of the same parent table that
> have the same name but are in different schemas, and you omit the
> schema name from the relation identifier. That is, you have a table,
> let's say foo, with partitions bar.foopart and baz.foopart. Instead of
> writing something like SEQ_SCAN(foo/bar.foopart) as the advice
> generator would do, you choose to write SEQ_SCAN(foo/foopart), making
> it ambiguous which child relation you're talking about. What happens
> right now is that advice enforcement will enforce that restriction
> against both children, but advice feedback will think that doesn't
> affect either one, so if you look at the advice feedback with EXPLAIN
> or print it out via pg_plan_advice.feedback_warnings, you'll see
> "matched, failed" instead of just "matched". Obviously, this kind of
> sucks. Of course, the blast radius is limited by the fact that almost
> nobody names their partitions this way, but theoretically they could
> and nobody likes features that work most of the time.
>
> Unfortunately, it is not at all straightforward to fix this. Pretty
> much everything the advice feedback code starts by mapping each
> relation identifier to an RTI, and giving up if the number of matches
> is not exactly 1. Since the whole purpose of relation identifiers is
> to map uniquely to relations appearing in the query, this is in
> general fine, but the case described in the previous paragraph breaks
> it. Generalizing the logic in the advice feedback code to be able to
> handle a relation identifier that maps to multiple RTIs looks like a
> bad idea. It would require massive adjustments to the code for a case
> that almost nobody has in real life, and the resulting code would be
> complicated and hard to understand and probably have corner cases
> where the performance is terrible. So I think something else has to
> give. A possible zero-order solution is to just document that advice
> feedback isn't guaranteed to work properly if you do this, so maybe
> you shouldn't. That is obviously not amazing but I think we could live
> with it for v19. What I'm thinking is probably better is to impose a
> restriction sufficient to keep this case from arising in the first
> place, such as:
>
> 1. Just rip out all the logic that allows the partition schema to be
> omitted, and require it always. This is only sad for people writing
> advice strings manually, since generated advice always includes the
> schema anyway.
>
> 2. Refuse to enforce advice if the partition schema is omitted and
> there's more than one partition with the same partition name. This
> changes the rule from "you can leave out the partition schema" to "you
> can leave out the partition schema when no ambiguity is thereby
> created," and it makes the existing behavior of the advice feedback
> system correct in retrospect. This seems like it would make just about
> nobody sad and therefore be just about perfect, except that I am not
> sure there's any way of implementing it that doesn't result in causing
> even bigger problems that the one it's trying to solve. More
> investigation needed.

What is your plan with cross- release compatibility for the mini
language and what advice strings are valid across releases? On some
level, idea 1 seems like the most appealing because a) it seems quick
to do before beta 4 b) it's the easiest to back down from if you find
a good way to support this later. If you don't require the schema and
later have to do that, you could have advice strings that no longer
work. Take this with a grain of salt, as I have neither used the
feature nor looked at its code :)

- Melanie


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Sep 10, 2026 at 2:13 PM Robert Haas  wrote:
> 0003 Disallow empty sublists within JOIN_ORDER(). New in this version
> of the patch set. Trivial fix for a gap in parse-time validation of
> advice strings.
>
> 0004 Disallow partition name without partition schema. As per Melanie
> and Nathan's preferred direction.

I've committed these two.

-- 
Robert Haas


Re: pg_*_advice: tsv load failure, etc.

От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
Вложения:
On Wed, Sep 9, 2026 at 4:16 PM Robert Haas  wrote:
> Generally, all of these problems stem from advice
> enforcement (which tries to make the plan obey the advice) being out
> of step with advice feedback (which says whether the plan actually did
> obey the advice). As far as I have found so far, those things are in
> lock step for all of the cases that test_plan_advice exercises, or to
> say it differently, they're in lock step for all the kinds of advice
> that pg_plan_advice generates itself.

AI found a related case and prepared the attached patch:
pg_plan_advice generates Gather advice for a set-operation upper relation
that it cannot enforce. This is on REL_19_STABLE at b368bdd2.

Reproducer:

  load 'pg_plan_advice';
  create table t (a int);
  set max_parallel_workers_per_gather = 1;
  set min_parallel_table_scan_size = 0;
  set parallel_setup_cost = 0;
  set parallel_tuple_cost = 0;
  set enable_gathermerge = off;

  explain (costs off, plan_advice)
    select a from t union select a from t;

This produces a Gather above the Parallel Append and generates:

  GATHER((unnamed_subquery unnamed_subquery#2))

Feeding that advice back already reports it as only partially matched:

  set pg_plan_advice.advice =
    'GATHER((unnamed_subquery unnamed_subquery#2))';
  set parallel_setup_cost = 1000000;
  explain (costs off)
    select a from t union select a from t;

The second plan has no Gather, despite the supplied advice, and reports:

  GATHER((unnamed_subquery unnamed_subquery#2)) /* partially matched */

The Gather belongs to the set-operation upper relation. That relation is
built by plan_set_operations(), where pg_plan_advice has no hook to enforce
the generated advice. This is also consistent with the documented
limitation that set-operation planning cannot currently be controlled.

The attached patch records which PlannerInfo objects contain set
operations, maps their RTIs into the final flattened range table, and
omits GATHER and GATHER_MERGE advice for those upper relations. It retains
Gather advice within set-operation input queries and for flattened union
all append relations.

I have not manually reviewed the C changes. The following passed:

  make check
  make -C src/test/isolation check
  make -C contrib/pg_plan_advice check
  make -C src/test/modules/test_plan_advice check

The pg_plan_advice regression additions cover union at the top level and
in a subquery, Gather within intersect inputs, and flattened union all.

--
Nik

Re: pg_*_advice: tsv load failure, etc.

От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
Вложения:
On Wed, Sep 9, 2026 at 4:16 PM Robert Haas  wrote:
> Generally, all of these problems stem from advice
> enforcement (which tries to make the plan obey the advice) being out
> of step with advice feedback (which says whether the plan actually did
> obey the advice).

AI found another case and prepared the attached patch. A single-target
PARTITIONWISE entry on a plain table disables every scan path,
although the advice only says that the table must not participate in a
partitionwise join.

  load 'pg_plan_advice';
  create table plain (i int);
  set pg_plan_advice.advice = 'PARTITIONWISE(plain)';
  explain (costs off, plan_advice) select * from plain;

This produces:

  Seq Scan on plain
    Disabled: true
  Supplied Plan Advice:
    PARTITIONWISE(plain) /* matched, failed */

pgpa_planner_apply_scan_advice() treats this single-target PARTITIONWISE
entry as an Append/MergeAppend scan restriction. For the plain table,
that clears all available scan methods. The feedback walker then
looks for a partitionwise scan and reports failure.

The patch uses the preprocessed RTE inheritance flag to treat this as a
matched no-op. It also handles the equivalent PARTITIONWISE((plain)) form.
This is on REL_19_STABLE at b73d13c3, and the patch applies cleanly to
master at 374522aa.

I have not manually reviewed the C changes. The pg_plan_advice regression
suite, its foreign-scan TAP test, and the test_plan_advice TAP test pass.

Nik

Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Wed, Sep 23, 2026 at 1:17 PM Nikolay Samokhvalov  wrote:
> AI found another case and prepared the attached patch.

This is just a quick note to say I have seen these reports and am
working on them. I hope to have a patch set by tomorrow.

-- 
Robert Haas


Re: pg_*_advice: tsv load failure, etc.

От:
Dongpo Liu <poe.liu@pm.me>
Дата:
Вложения:
Hi,

On Mon, Aug 31, 2026 Jakub Wartak wrote:
> Perhaps adding one statement to the docs would be good enough to cover
> it for now, like: "In order to change the already cached plans, issue
> ANALYZE on relevant tables."

Attached is a doc patch for item 5.  I understand that Robert and Noah
agreed to leave the behavior as-is.  This patch only documents it.

I did not use the ANALYZE wording, because ANALYZE does not reliably
invalidate cached plans.  vac_update_relstats() writes the pg_class
tuple only if a value changed, so an ANALYZE that leaves the pg_class
statistics unchanged sends no relcache invalidation:

LOAD 'pg_plan_advice';
CREATE TABLE t (a int PRIMARY KEY);
INSERT INTO t SELECT generate_series(1, 10000);
VACUUM ANALYZE t;
SET plan_cache_mode = force_generic_plan;
PREPARE q AS SELECT * FROM t WHERE a = $1;
EXPLAIN (COSTS OFF) EXECUTE q(1);   -- Index Only Scan
SET pg_plan_advice.advice = 'SEQ_SCAN(t)';
EXPLAIN (COSTS OFF) EXECUTE q(1);   -- still Index Only Scan
ANALYZE t;
EXPLAIN (COSTS OFF) EXECUTE q(1);   -- still Index Only Scan
INSERT INTO t SELECT generate_series(10001, 12000);
ANALYZE t;
EXPLAIN (COSTS OFF) EXECUTE q(1);   -- Seq Scan

The same happens when another session changes an advice stash.

The patch adds a paragraph to the Limitations section of pg_plan_advice
and a short pointer in pg_stash_advice.  It says that advice is consulted
only at plan time, mentions DISCARD PLANS for the current session, and
refers to PREPARE for when other sessions re-plan.

Best regards,
Dongpo Liu



On Sunday, October 4th, 2026 at 2:25 PM, Jakub Wartak  wrote:

> On Fri, Aug 28, 2026 at 4:21 PM Robert Haas  wrote:
> >
> >
> > > ### 5. pg_plan_advice.advice / stash advice changes are silently ignored by an already-cached generic plan
> >
> > This is a planner control feature; it does not affect behavior other
> > than at plan time. I don't see that as a bug. That said, I think it
> > would be perfectly valid for someone to try to figure a way for advice
> > stash changes to invalidate plans, but I suspect that will require
> > significant new infrastructure. Plan invalidation is generally tied to
> > catalog modifications, and here we would instead want to tie it to a
> > plan ID. We could do that by adding a custom invalidation type to
> > sinval.h just for the use of pg_stash_advice, but would be a pretty
> > serious piece of core infrastructure for an as-yet-unproven contrib
> > module to use to solve a problem which (for all we know now) may have
> > little practical impact.
>
> FWIW, this was already discussed back in the day I think in [1]. I wouldn't
> remeber it otherwise if not the mailing list, but apparently ANALYZE on the
> table affected was enough to trigger the change [2]. Perhaps adding one
> statement to the docs would be good enough to cover it for now, like: "In
> order to change the already cached plans, issue ANALYZE on relevant tables."
> (because apparently without it it now confused 2 people and 1 AI ;))
>
> -J.
>
> [1] - https://www.postgresql.org/message-id/CA%2BTgmoYO0qtqz%2BV7S4q0e_dLhLrrsMxA51t5wks_y8Skv6cdRQ%40mail.gmail.com
> [2] - https://www.postgresql.org/message-id/CA%2BTgmob8O4TbZVr2zoqm5m-Zp6fj-8iBh%3D0u-xfiy5Xr5MNFCQ%40mail.gmail.com
>
>
>
>
>

Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
Вложения:
On Thu, Sep 24, 2026 at 5:02 PM Robert Haas  wrote:
> This is just a quick note to say I have seen these reports and am
> working on them. I hope to have a patch set by tomorrow.

Well, that certainly didn't happen. This has turned out to be
complicated. Here's a new patch set, which doesn't fix everything, but
fixes some things. The first three are fixes for brown-paper-bag bugs
that I discovered while investigating Nik's reports. The last is a fix
for the problem Ayush Tiwari reported back on September 10th. Briefly,
0001 fixes a goof in the introduction of child_append_relid_sets,
which was added to support pg_plan_advice, so the goof could result in
advice being wrong, but here I test it more directly via
pg_overexplain. 0002 fixes a problem where a variable was used for two
things but was the right value in only one of those places, and can
result in PARTITIONWISE advice going missing. 0003 fixes a problem
where NO_GATHER advice should be emitted for partitioned tables, and
isn't. And 0004 fixes Ayush's complaint that advice feedback for stuff
like JOIN_ORDER((a b)) shows up as only partially matched when in fact
it is fully matched. I plan to commit these patches and back-patch
them to v19 relatively quickly, barring objections.

There are more problems that aren't fixed. What Nik's report on
September 21st shows is that we sometimes generate plan advice for set
operations even though we're not able to enforce such advice for lack
of proper planner hooks. I spent a very long time trying to get that
case exactly right, but I'm not confident that I have managed to do
so, which is why there's no patch for that included here. Nik's report
on September 23rd is arguably not a bug at all. Generally, we don't
promise that supplying stupid advice won't mess up your plan, and
PARTITIONWISE(plain_table) is arguably stupid advice. On the other
hand, INDEX_SCAN(some_table no_such_index) won't mess up your plan
because we consider it *inapplicable* advice rather than *stupid*
advice, and that categorization causes it to not do anything. There's
a reasonable argument that PARTITIONWISE(plain_table) ought to be
treated similarly, although whether that rises to the level of being a
bug rather than an unimplemented feature seems pretty debatable.

There's also a residual problem with NO_GATHER(): after 0003, we no
longer omit it for partitioned tables, but we still include it for
their children, and that doesn't actually accomplish anything useful,
because we don't generate gather paths for individual children of a
partitionwise table, only for the partitioning root. In some ways,
this is similar to the set operation problem that Nik pointed out:
advice gets generated which is conceptually reasonable, but doesn't
make sense in practice. The reasons are different: for set operations,
we lack a hook to enforce it; for NO_GATHER on partition children,
enforcement is unnecessary because nothing else can happen.

On top of all that, I'm still looking into one more problem discovered
along the way as well, but I'm not ready to write about that, yet.

-- 
Robert Haas
Databricks

Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
Вложения:
On Mon, Oct 5, 2026 at 1:01 PM Robert Haas  wrote:
> On top of all that, I'm still looking into one more problem discovered
> along the way as well, but I'm not ready to write about that, yet.

Here's v7, adding one more patch to fix the "one more problem"
mentioned, inserted into the sequences as 0003. Note that this breaks
ABI compatibility, but I nevertheless plan to back-patch to v19. cc:
rmt, in case they wish to weigh in.

0001-0003 all fix related deficiencies in child_append_relid_sets
handling. 0001 fixes the failure to fix up the RTIs stored in that
field at setrefs time; 0002 fixes pg_plan_advice's failure to set the
scan type properly for scans derived from child_append_relid_sets;
0003 fixes loss of child_append_relid_sets when (Merge)Append nodes
bearing them are subsequently elided. All of these solve problems
related to plan advice and partitioning, especially multi-level
partitioning, which I appear to have significantly under-tested. 0004
is unrelated to child_append_relid_sets, but still related to
partitioning: NO_GATHER can be left out of plan advice where it's
actually needed. And 0005 still fixes
JOIN_ORDER((whole_group_multiply_delimited)) scenarios.

Sorry for all the mistakes. :-(

-- 
Robert Haas
Databricks

Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
Вложения:
On Sun, Oct 4, 2026 at 8:38 AM Dongpo Liu  wrote:
> The patch adds a paragraph to the Limitations section of pg_plan_advice
> and a short pointer in pg_stash_advice.  It says that advice is consulted
> only at plan time, mentions DISCARD PLANS for the current session, and
> refers to PREPARE for when other sessions re-plan.

I think it's a good idea to add something to the documentation about
this issue, but I'm not entirely convinced by this wording. In
particular:

"The new advice is used the next time the statement is planned" => To
me, this sort of makes it seem like you could just leave
pg_plan_advice.advice set the whole time, which is not a realistic
approach. Or else as though it will remember the advice that it didn't
use this time and use it next time re-planning actually happens, which
it won't.

"Plans cached by other sessions are re-planned only when something
else invalidates them; see ." => I feel
like there are two ways to read this. One possible reading is that
replanning doesn't happen on every use of the cache, but only when
there is a reason to replan. That's just the definition of a cache.
The other possible reading is that invalidation is the only thing that
can trigger replanning, which isn't true;
for example, the other session could have a custom plan, or it could
execute DISCARD PLANS itself.

Here's my rewrite. (Also, I committed my latest round of bug-fix patches.)

-- 
Robert Haas
Databricks

Re: pg_*_advice: tsv load failure, etc.

От:
Dongpo Liu <poe.liu@pm.me>
Дата:
Hi Robert,                                                                                         
                                                                                                      
Thanks for the rewrite. The v2 wording is clearer, and the patch looks good to me.                                                           
                                                                                                      
Best regards,                                                                                      
Dongpo Liu


On Friday, October 9th, 2026 at 9:15 PM, Robert Haas  wrote:

> On Sun, Oct 4, 2026 at 8:38 AM Dongpo Liu  wrote:
> > The patch adds a paragraph to the Limitations section of pg_plan_advice
> > and a short pointer in pg_stash_advice.  It says that advice is consulted
> > only at plan time, mentions DISCARD PLANS for the current session, and
> > refers to PREPARE for when other sessions re-plan.
> 
> I think it's a good idea to add something to the documentation about
> this issue, but I'm not entirely convinced by this wording. In
> particular:
> 
> "The new advice is used the next time the statement is planned" => To
> me, this sort of makes it seem like you could just leave
> pg_plan_advice.advice set the whole time, which is not a realistic
> approach. Or else as though it will remember the advice that it didn't
> use this time and use it next time re-planning actually happens, which
> it won't.
> 
> "Plans cached by other sessions are re-planned only when something
> else invalidates them; see ." => I feel
> like there are two ways to read this. One possible reading is that
> replanning doesn't happen on every use of the cache, but only when
> there is a reason to replan. That's just the definition of a cache.
> The other possible reading is that invalidation is the only thing that
> can trigger replanning, which isn't true;
> for example, the other session could have a custom plan, or it could
> execute DISCARD PLANS itself.
> 
> Here's my rewrite. (Also, I committed my latest round of bug-fix patches.)
> 
> --
> Robert Haas
> Databricks
>


Re: pg_*_advice: tsv load failure, etc.

От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Fri, Oct 9, 2026 at 9:15 PM Robert Haas  wrote:
>
> On Sun, Oct 4, 2026 at 8:38 AM Dongpo Liu  wrote:
> > The patch adds a paragraph to the Limitations section of pg_plan_advice
> > and a short pointer in pg_stash_advice.  It says that advice is consulted
> > only at plan time, mentions DISCARD PLANS for the current session, and
> > refers to PREPARE for when other sessions re-plan.
>
> I think it's a good idea to add something to the documentation about
> this issue, but I'm not entirely convinced by this wording. In
> particular:
> [..patch..]

LGTM for me too, thanks!

-J.


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Oct 12, 2026 at 2:08 AM Jakub Wartak
 wrote:
> LGTM for me too, thanks!

Thanks. I will plan to commit this after rc1 is wrapped.

-- 
Robert Haas
Databricks


Re: pg_*_advice: tsv load failure, etc.

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Вложения:
Hello

I/Claude noticed one more issue with pg_stash_advice:
if the worker fails to write pg_stash_advice.tsv, the changes it was
trying to save are treated as saved by the next worker.

Any ERROR in pgsa_write_to_disk() makes the worker exit, and the
postmaster restarts it later. stashes_ready is already set, so the new
worker doesn't load the file, and it initializes last_change_count
from the current change_count.

From that point the worker considers everything in memory clean, the
file is only rewritten after some later change or at a clean shutdown.
An immediate shutdown or a crash in between reloads the old file, and
the changes are gone, even though the worker was running for much
longer than persist_interval.

The attached patch starts last_change_count from 0 in a worker that
didn't load the file itself. This writes at the first opportunity
whenever unsaved changes exist. It can cause one redundant rewrite
after a restart, which seems harmless. I also moved the change_count
read in the loading branch before setting stashes_ready, otherwise a
backend change between the two could be counted as loaded.

A TAP test is included for reproduction and as a permanent test case
if we want it.

Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Oct 12, 2026 at 11:43 AM Robert Haas  wrote:
> Thanks. I will plan to commit this after rc1 is wrapped.

Done.

-- 
Robert Haas
Databricks


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
Вложения:
On Wed, Sep 23, 2026 at 1:17 PM Nikolay Samokhvalov  wrote:
> AI found another case and prepared the attached patch. A single-target
> PARTITIONWISE entry on a plain table disables every scan path,
> although the advice only says that the table must not participate in a
> partitionwise join.
>
>   load 'pg_plan_advice';
>   create table plain (i int);
>   set pg_plan_advice.advice = 'PARTITIONWISE(plain)';
>   explain (costs off, plan_advice) select * from plain;

Here's another set of patches, finally addressing this and your other
report, plus related problems that I found while digging around in
this area.

0001 fixes multiple problems with NO_GATHER advice. It's questionable
whether I've really defined NO_GATHER correctly, but I certainly
thought I had at the time I wrote the documentation, and yet the
behavior of the code does not match the documentation, and the
documentation is not as clear about all the details as it should be,
so this tries to clean some of that up without redefining anything too
much.

0002 arranges to suppress generation of plan advice from unflattened
set operations, which is what you reported on September 21st. Manually
written advice still won't work, but we can't enforce such advice
without new planner hooks, which is out of scope for this release.

0003 marks PARTITIONWISE(plain_table) advice inapplicable, which is
what you reported in this email. I think somebody could justifiably
take the position that this is not, strictly speaking, a bug fix,
because we should never generate PARTITIONWISE(plain_table), and
there's no meaningful way to do anything useful with it, so whatever.
However, when I initially coded this up, it caused a test failure,
because without 0f7dfd7936b9e99f9aeca00f52ab1692898ffff4 we actually
did generate such advice in a few regression test cases, but
apparently not in a way that changed the plan, so there was nothing in
the advice feedback for test_plan_advice to notice. With this commit,
if such bogus advice is generated, test_plan_advice sees the
"inapplicable" feedback and complains. So I think it's a good idea to
back-patch this into 19, because it's arguably a bug, and because
changing it also makes it easier to notice other bugs.

My plan is to get all of these committed and back-patched to
REL_19_STABLE before we wrap rc2. Thanks all for the reports, and
sorry it's taking me a while to grind through these. I really have
spent a lot of time on it, trust me...

-- 
Robert Haas
Databricks

Re: pg_*_advice: tsv load failure, etc.

От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello Robert,

17.10.2026 00:44, Robert Haas wrote:
On Wed, Sep 23, 2026 at 1:17 PM Nikolay Samokhvalov <nik@postgres.ai> wrote:
AI found another case and prepared the attached patch. A single-target
PARTITIONWISE entry on a plain table disables every scan path,
although the advice only says that the table must not participate in a
partitionwise join.
Here's another set of patches, finally addressing this and your other
report, plus related problems that I found while digging around in
this area.

Could you please look at instability in 001_persist.pl found by natural
testing [1]:?
[10:27:25.048](0.445s) # die: error running SQL: 'psql:<stdin>:2: ERROR:  stash modifications are not allowed because "pg_stash_advice.tsv" has not been loaded yet'
# while running 'psql --no-psqlrc --no-align --tuples-only --quiet --dbname port=29827 host=/tmp/o4DZxN3eiX dbname='postgres' --file - --variable ON_ERROR_STOP=1' with sql '
#     SELECT pg_create_advice_stash('stash_a');
#     SELECT pg_set_stashed_advice('stash_a', 1001, 'IndexScan(t)');
#     SELECT pg_set_stashed_advice('stash_a', 1002, E'line1\\nline2\\ttab\\\\backslash');
#     SELECT pg_set_stashed_advice('stash_a', 1003, '');
#     SELECT pg_create_advice_stash('stash_b');
#     SELECT pg_set_stashed_advice('stash_b', 2001, 'SeqScan(t)');
# ' at /home/bf/bf-build/culicidae/REL_19_STABLE/pgsql/contrib/pg_stash_advice/t/001_persist.pl line 24.

The failure is pretty clear and can be easily reproduced with this sleep:
--- a/contrib/pg_stash_advice/stashpersist.c
+++ b/contrib/pg_stash_advice/stashpersist.c
@@ -146,2 +146,3 @@ pg_stash_advice_worker_main(Datum main_arg)
         pgsa_read_from_disk();
+pg_usleep(random() % 200000);
         pg_atomic_test_set_flag(&pgsa_state->stashes_ready);

It also makes the test fail other ways:
t/001_persist.pl .. 1/?
#   Failed test 'stashes survived restart'
#   at t/001_persist.pl line 44.
#          got: ''
#     expected: 'stash_a|2
# stash_b|1'
...

#   Failed test 'entry contents survived restart with special characters intact'
#   at t/001_persist.pl line 49.
#          got: ''
#     expected: 'stash_a|1001|IndexScan(t)
# stash_a|1002|line1
# line2 tab\backslash
# stash_b|2001|SeqScan(t)'
...

Probably, the fix can wait as it's the first failure of the test in 6
months.

[1] https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=culicidae&dt=2026-10-19%2008%3A24%3A45

Best regards,
Alexander

Re: pg_*_advice: tsv load failure, etc.

От:
Dongpo Liu <poe.liu@pm.me>
Дата:
On Friday, October 23rd, 2026 at 5:41 PM, Robert Haas  wrote:

> #19 might be a real bug, but needs validation, and can't be easily
> validated with in-core code.

Hi Robert,

I am still getting used to how discussions are organized on this list. I
posted a reproducer and patch in a separate thread [1]. Since the
related discussion is continuing here, I thought it might be helpful to
add a link here as well.

I confirmed #19 with a small test-only CustomScan provider. When a
CustomScan replaces a join within a larger join, EXPLAIN (PLAN_ADVICE)
can fail with "plan node has no RTIs". The patch makes pgpa_relids()
return CustomScan.custom_relids.

When you have a chance, I would appreciate your thoughts on the patch. I
would also welcome your advice on adding a join case to test_extensible
for regression coverage.

[1] https://www.postgresql.org/message-id/sSMpyoJ12CV5Y3uS-T_8Z3M1xsJBELBd-Vh5DmlC9_jy9TOqMuWzr8-TuXrBpL8AlPlyEFkyQ4wX5guJCyVizY-R2UET0DpIEeA1aSsUjk4%3D%40pm.me

Best regards,
Dongpo Liu




Re: pg_*_advice: tsv load failure, etc.

От:
Dongpo Liu <poe.liu@pm.me>
Дата:
Hi,

I reviewed the patch, and it looks good to me. The change is small
and effective. I ran the tests locally: the new TAP test fails
without the fix and passes with it.

The possible extra write after a worker restart is one more write of
a small file, so I don't think it is a problem. I also tried to keep
the last saved change count in shared memory to prevent that write.
It works, but it adds shared state only to save one write, so I
agree with the approach in your patch.

Regards,
Dongpo Liu


Re: pg_*_advice: tsv load failure, etc.

От:
Jakub Wartak <jakub.wartak@enterprisedb.com>
Дата:
On Fri, Oct 16, 2026 at 11:45 PM Robert Haas  wrote:
[..]
> My plan is to get all of these committed and back-patched to
> REL_19_STABLE before we wrap rc2. Thanks all for the reports, and
> sorry it's taking me a while to grind through these. I really have
> spent a lot of time on it, trust me...

As promised, I've took very quick look using TPC-H queries using that script
from the beggining of the project (tpch-vs-pg_plan_advise) that I've used
for finding initial problems (before there was built-in hairness). I've run it
on the the master (from yesterday) and compared to: master+v8. In short: LGTM,
but haven't looked at code.

Most of the plans seem to be identical to naked eye and 100% correct in terms
of joins, lookup types, paths, it's just that sometimes that v8 introduced more
parallelism that was happening without it. E.g. for Q7 for master+v8 it went
from:

# planner
GroupAggregate
  Group Key: n1.n_name, n2.n_name, (EXTRACT(year FROM lineitem.l_shipdate))
  ->  Gather Merge
        Workers Planned: 2
        ->  Sort
              Sort Key: n1.n_name, n2.n_name, (EXTRACT(year FROM
lineitem.l_shipdate))
              ->  Hash Join
[..]

# captured advice
    JOIN_ORDER(customer n2 orders lineitem (supplier n1))
    MERGE_JOIN_PLAIN(n2)
    NESTED_LOOP_PLAIN(orders lineitem)
    HASH_JOIN(n1 (supplier n1))
    SEQ_SCAN(supplier n1)
    INDEX_SCAN(n2 public.pk_nation orders public.orders_o_custkey_idx lineitem
    public.pk_lineitem)
    INDEX_ONLY_SCAN(customer public.customer_c_nationkey_c_custkey_idx)
    GATHER_MERGE((supplier lineitem orders customer n1 n2))

# wiping rel stats and got this plan after that using that above advice:
Finalize GroupAggregate
  Group Key: n1.n_name, n2.n_name, (EXTRACT(year FROM lineitem.l_shipdate))
  ->  Gather Merge
        Workers Planned: 2
        ->  Partial GroupAggregate
              Group Key: n1.n_name, n2.n_name, (EXTRACT(year FROM
lineitem.l_shipdate))
              ->  Sort
                    Sort Key: n1.n_name, n2.n_name, (EXTRACT(year FROM
lineitem.l_shipdate))
                    ->  Hash Join
[..]

which translates to more or less as I understand it that in adviced plan case,
it just added even more parallelism just after the sort. Anyway I think it's
known limitation as per sgml: "It is currently not possible to control any
aspect of the planner's behavior with respect to aggregation. This includes
both whether aggregates are computed by sorting (..)", so fine by me, I was
just surprised by this and it looks like it is not really deterministic (I can
dig further, but it's of scope anyway and it's not worth it).

-J.


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Oct 23, 2026 at 11:54 AM Dongpo Liu  wrote:
> I am still getting used to how discussions are organized on this list. I
> posted a reproducer and patch in a separate thread [1]. Since the
> related discussion is continuing here, I thought it might be helpful to
> add a link here as well.

I'll check other threads after I finish this one. Everyone, please
stop adding more unrelated reports to this thread. Until the release
of v19, add any new threads to the open items list.

Thanks,

-- 
Robert Haas
Databricks


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, Oct 16, 2026 at 1:05 PM Zsolt Parragi  wrote:
> I/Claude noticed one more issue with pg_stash_advice:
> if the worker fails to write pg_stash_advice.tsv, the changes it was
> trying to save are treated as saved by the next worker.

Oops. Thanks for the patch. I committed it, but...

> A TAP test is included for reproduction and as a permanent test case
> if we want it.

...I decided against including the test case, and dropped it.

-- 
Robert Haas
Databricks


Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Tue, Oct 20, 2026 at 2:59 PM Alexander Lakhin  wrote:
> Could you please look at instability in 001_persist.pl found by natural
> testing [1]:?
> [10:27:25.048](0.445s) # die: error running SQL: 'psql::2: ERROR:  stash modifications are not allowed because "pg_stash_advice.tsv" has not been loaded yet'
> # while running 'psql --no-psqlrc --no-align --tuples-only --quiet --dbname port=29827 host=/tmp/o4DZxN3eiX dbname='postgres' --file - --variable ON_ERROR_STOP=1' with sql '
> #     SELECT pg_create_advice_stash('stash_a');
> #     SELECT pg_set_stashed_advice('stash_a', 1001, 'IndexScan(t)');
> #     SELECT pg_set_stashed_advice('stash_a', 1002, E'line1\\nline2\\ttab\\\\backslash');
> #     SELECT pg_set_stashed_advice('stash_a', 1003, '');
> #     SELECT pg_create_advice_stash('stash_b');
> #     SELECT pg_set_stashed_advice('stash_b', 2001, 'SeqScan(t)');
> # ' at /home/bf/bf-build/culicidae/REL_19_STABLE/pgsql/contrib/pg_stash_advice/t/001_persist.pl line 24.

I'm guessing that this is fixed by Zsolt's patch, which I just committed.

I also committed my previous round of fixes, so I think that closes
out this thread, and I have closed out the open item.

Again, if anyone finds more issues, please start new threads about
those, and add them to the open items list if 19final isn't out yet.
If you find issues later, feel free to send me an off-list email or PM
me on Discord to follow up, if I don't notice here.

Thanks,

-- 
Robert Haas
Databricks


Re: pg_*_advice: tsv load failure, etc.

От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
Вложения:
On Thu, Oct 29, 2026 at 9:59 AM Robert Haas  wrote:
> I'm guessing that this is fixed by Zsolt's patch, which I just committed.

The 001_persist.pl race Alexander reported still reproduces after
6f16120176 on REL_19_STABLE (61553eacad on master).

Adding pg_usleep(1000000); immediately after pgsa_read_from_disk()
in pg_stash_advice_worker_main(), before stashes_ready is set, makes
the unchanged test on REL_19_STABLE fail at
pg_create_advice_stash('stash_a'):

ERROR:  stash modifications are not allowed because
"pg_stash_advice.tsv" has not been loaded yet

The "loaded" log line used by the test after restart also comes before
stashes_ready is set. Once the first race is avoided, the delayed test
fails again when creating stash_c after the first restart.

The attached test-only patch waits for stash creation to succeed at
startup, for the expected stashes to appear after each restart, and for
stash modifications to be allowed after the final empty restart. The
focused TAP test passes with and without the delay on both branches.
The sleep is only for reproduction; it is not in the patch. AI prepared
the patch; I have not manually reviewed it.

Nik

Re: pg_*_advice: tsv load failure, etc.

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Thu, Oct 29, 2026 at 7:27 PM Nikolay Samokhvalov  wrote:
> The attached test-only patch waits for stash creation to succeed at
> startup, for the expected stashes to appear after each restart, and for
> stash modifications to be allowed after the final empty restart. The
> focused TAP test passes with and without the delay on both branches.
> The sleep is only for reproduction; it is not in the patch. AI prepared
> the patch; I have not manually reviewed it.

Looks OK, except for a few cosmetic things. I have committed it and
back-patched to v19.

-- 
Robert Haas
Databricks


Re: pg_*_advice: tsv load failure, etc.

От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
> Looks OK, except for a few cosmetic things. I have committed it and
> back-patched to v19.

thanks!

Nik


FAQ