Re: bug: query returns different result with and without memoization.

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

Re: bug: query returns different result with and without memoization.

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
Вложения:
On Mon, Jul 27, 2026 at 9:46 PM David Rowley  wrote:
> For reference, I was experimenting with the attached. What do you think?

I looked over your patch, but I'm afraid it's not correct.

IIUC, your patch inspects innerrel->baserestrictinfo and only collects
the outer arg of a two-arg OpExpr.

First, this can pick the wrong arg.  If the Param isn't a whole side
of the qual, we end up adding a bogus cache key while still missing
the Param itself.  Consider the qual "t1.twenty - t0.ten = 0" in this
query:

    SELECT sum(c) FROM (
      SELECT t0.unique1,
        (SELECT count(*) FROM tenk1 t2 JOIN tenk1 t1
            ON t1.unique1 = t2.hundred + t0.ten
          WHERE t1.twenty - t0.ten = 0) AS c
      FROM tenk1 t0 WHERE t0.unique1 < 200) s;

With your patch I get:

        ->  Memoize
              Cache Key: (t2.hundred + t0.ten), 0
              Cache Mode: logical
              ->  Index Scan using tenk1_unique1 on tenk1 t1
                    Index Cond: (unique1 = (t2.hundred + t0.ten))
                    Filter: ((twenty - t0.ten) = 0)

That is, the constant 0 becomes a cache key, while t0.ten is still
missing from the keys.

And running this query I get wrong result:

  sum
--------
 148000

where the correct result is 100000.

Second, I'm not convinced that base quals are the only place such a
Param can appear.  It can also appear on the inner side of a join
clause, as in "t1.hundred + t0.ten = t2.hundred", where only the outer
side becomes a cache key.  It could also be in innerrel->reltarget, or
inside a subquery RTE that wasn't pulled up, and no amount of base
qual scanning will reach those.

That is what worries me most about this approach: it requires us to
enumerate every place a Param might be used, and if we ever miss one,
we are back to the same kind of wrong results.

Besides correctness, I'm a bit concerned that returning false discards
the Memoize path entirely, and that a qual only has to contain a Param
to reach that test.  Taking the same query with a plain join clause
and varying only the qual on t1:

    SELECT sum(c) FROM (
      SELECT (SELECT count(*) FROM tenk1 t1
              INNER JOIN tenk1 t2 ON t1.unique1 = t2.hundred
              WHERE ) AS c
      FROM tenk1 t0 WHERE t0.unique1 < 2) s;

none of these can use Memoize any more with your patch, though none of
them is broken today:

    WHERE t1.twenty = t1.four + t0.ten            -- sides don't match
    WHERE t1.twenty IS DISTINCT FROM t0.ten       -- not an OpExpr
    WHERE t1.twenty = t0.ten OR t1.four = t0.two  -- not an OpExpr

along with any Param whose type has no hash opclass.  Today each of
those gets a working Memoize node that simply flushes the cache when
the Param changes.  So I'm concerned about the plan regression in
cases that never had a problem.

So I'd like to propose the attached patch.  Rather than looking for
every place a Param might be used, it requires that every PARAM_EXEC
Param appearing in a cache key expression is also a cache key in its
own right.  Then matching the keys implies matching the Param, and the
set we have to examine is bounded, because it's just the key list we
already built.

The patch then also makes cache keys of the Params used outside the
cache keys: in the relation's base quals, its targetlist, and on the
inner side of the join clauses.  It's what stops the cache being
purged on every invocation of a correlated subplan.  It's only an
optimization, so it's ok if we miss a place a Param might be used.

- Richard

Re: bug: query returns different result with and without memoization.

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
Вложения:
On Fri, Sep 11, 2026 at 4:10 PM Yilin Zhang  wrote:
> From the earlier discussion we learned that when a Param's type has no
> hash opclass (geometric types such as point and box, domains over such
> types, and custom types), memoize_add_cache_key() fails and the Memoize
> path is abandoned entirely.  Among types commonly used in production,
> point has no hash or btree opclass at all, which can increase the scan
> cost severalfold.

Good point.  I agree that we should not give up Memoize only because a
buried Param is not hashable.  For such a Param, purging the cache
whenever it changes is enough to get correct results.

But I think we don't need to track the unhashable Params separately.
I think it's simpler to put into keyparamids only the Params that we
know are determined by the cache keys.  These are the nestloop Params
that replace the outer rel's Vars in the keys, because the inner scan
can only reference the outer rel through the keys.  Also, in binary
mode, a Param that is a cache key by itself.  Any other Param will
purge the cache when it changes.

While working on this, I found another wrong-results issue.
pull_paramids() also collects PARAM_EXTERN Params, so in a generic
plan an external Param in the cache key can be mistaken for the
executor Param with the same number, and then the cache is not purged
when that executor Param changes.  The above change fixes this too.

Attached is v3, which is split into two patches.

0001 is the fix and is intended for back-patching.  It makes each
Param buried inside a cache key expression a cache key by itself, so
the cache entries can still be reused across rescans of the enclosing
plan.  If a buried Param is not hashable, we just leave it to the
purging.  It also includes the keyparamids changes above.

0002 is for master only.  It also makes cache keys of the upper-level
Params used in the inner rel's base quals, targetlist and the inner
side of its join clauses, which currently purge the cache whenever
they change.  This is a trade-off: instead of purging the cache on
each change, we keep the entries and reuse them if the same Param
value comes back.  If the values do not repeat across rescans, the old
entries just take up memory until they are evicted, and the planner
cannot tell the difference since it costs Memoize per rescan with an
empty cache.

I plan to push them (or at least 0001, back-patched to 14) in a few
days if there are no objections, since the next minor release is just
around the corner.

- Richard

Re: bug: query returns different result with and without memoization.

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Richard,

Played with your v3 and did some fuzz testing, did not find any correctness issue.

LGTM!

Thanks,

Re: bug: query returns different result with and without memoization.

От:
"Yilin Zhang" <jiezhilove@126.com>
Дата:
At 2026-10-28 10:23:43, "Richard Guo" <guofenglinux@gmail.com> wrote:
>Good point.  I agree that we should not give up Memoize only because a
>buried Param is not hashable.  For such a Param, purging the cache
>whenever it changes is enough to get correct results.
>...
>I plan to push them (or at least 0001, back-patched to 14) in a few
>days if there are no objections, since the next minor release is just
>around the corner.

Hi,
Thank you for working on this bug.
Yes, the code in v3 is simpler and more effective.
LGTM.

Best regards,
Yilin Zhang

Re: bug: query returns different result with and without memoization.

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
On Fri, Oct 30, 2026 at 3:03 PM Yilin Zhang  wrote:
> At 2026-10-28 10:23:43, "Richard Guo"  wrote:
> >I plan to push them (or at least 0001, back-patched to 14) in a few
> >days if there are no objections, since the next minor release is just
> >around the corner.

> Thank you for working on this bug.
> Yes, the code in v3 is simpler and more effective.
> LGTM.

Pushed both and back-patched 0001 to v14.

- Richard


Re: bug: query returns different result with and without memoization.

От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Mon, Nov 2, 2026 at 10:46 AM Richard Guo  wrote:
> Pushed both and back-patched 0001 to v14.

Thanks for working on this!

Codex reported me that, after this change, the same query can fail with
enable_memoize enabled but succeed with it disabled, as shown below.
Is this a bug?

Here are the steps to reproduce it:

--------------------------------------
CREATE TEMP TABLE mo AS
SELECT g % 100 + 1 AS k FROM generate_series(1, 10000) g;

CREATE TEMP TABLE mi AS
SELECT g AS k FROM generate_series(1, 10000) g;

CREATE UNIQUE INDEX ON mi (k);
ANALYZE mo;
ANALYZE mi;

SET enable_memoize = off;

SELECT count(*)
FROM mo JOIN mi USING (k)
WHERE mi.k < ALL (VALUES (10001), (10002));

SET enable_memoize = on;

SELECT count(*)
FROM mo JOIN mi USING (k)
WHERE mi.k < ALL (VALUES (10001), (10002));
--------------------------------------

Regards,

-- 
Fujii Masao


Re: bug: query returns different result with and without memoization.

От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Mon, Nov 2, 2026 at 11:32 AM Fujii Masao  wrote:
> Codex reported me that, after this change, the same query can fail with
> enable_memoize enabled but succeed with it disabled, as shown below.
> Is this a bug?

Codex found another case where the same query fails with enable_memoize
enabled but succeeds with it disabled. Here are the steps to reproduce it:

--------------------------------------
CREATE TEMP TABLE mo AS
SELECT g % 100 + 1 AS k FROM generate_series(1, 10000) g;

CREATE TEMP TABLE mi AS
SELECT g AS k FROM generate_series(1, 10000) g;

CREATE UNIQUE INDEX ON mi (k);
ANALYZE mo;
ANALYZE mi;

SET enable_memoize = off;

SELECT count(*)
FROM mo JOIN mi USING (k)
WHERE CASE WHEN mi.k < 0
           THEN mi.k = (SELECT 1 / (k - k) FROM mo LIMIT 1)
           ELSE true END;

SET enable_memoize = on;

SELECT count(*)
FROM mo JOIN mi USING (k)
WHERE CASE WHEN mi.k < 0
           THEN mi.k = (SELECT 1 / (k - k) FROM mo LIMIT 1)
           ELSE true END;
--------------------------------------

Regards,

-- 
Fujii Masao


Re: bug: query returns different result with and without memoization.

От:
Richard Guo <guofenglinux@gmail.com>
Дата:
Вложения:
On Mon, Nov 2, 2026 at 11:33 AM Fujii Masao  wrote:
> Codex reported me that, after this change, the same query can fail with
> enable_memoize enabled but succeed with it disabled, as shown below.
> Is this a bug?

Thanks for the report!  Yes, both are bugs, and they have the same
cause.  When looking for Params to make cache keys of, we collect
every PARAM_EXEC Param we find, but only those supplied by outer query
levels are safe to evaluate as cache keys.

In your first query, the output Param of the ALL SubPlan is made a
cache key, but it has no value outside the SubPlan's testexpr, hence
the "plan should not reference subplan's variable" error.  In your
second query, the initPlan's output Param is made a cache key, so
Memoize runs the initPlan when it evaluates the cache keys, even
though the CASE arm that needs it is never taken.

Attached is a patch that fixes it by making cache keys only of the
Params listed in some outer query level's plan_params.  I plan to
back-patch it to v14.

- Richard
FAQ