From 2018a606c7fad53767e9e7facb4e535b08f33e49 Mon Sep 17 00:00:00 2001 From: Matt Edmonston Date: Tue, 24 Nov 2026 02:32:24 +0000 Subject: [PATCH] fix(rpc): run volatile set-returning functions exactly once A volatile SETOF function called with count=true executed twice (page, then total), and limit=0 on a SETOF scalar or composite one compiled to LIMIT 0 so the function never ran, unlike SETOF . Evaluate the call once in a MATERIALIZED CTE that the page, the has_next look-ahead and the total all read. limit=0 now runs the function once and returns no rows for every result kind. Stable and immutable functions keep their plan. --- CHANGELOG.md | 13 ++ docs/rpc.md | 13 +- internal/compile/golden_test.go | 6 +- internal/compile/rpc.go | 69 ++++++--- .../testdata/rpc_volatile_rows_count.http | 1 + .../testdata/rpc_volatile_rows_count.sql | 11 ++ .../rpc_volatile_rows_limit_zero.http | 1 + .../testdata/rpc_volatile_rows_limit_zero.sql | 10 ++ .../rpc_volatile_values_limit_zero.http | 1 + .../rpc_volatile_values_limit_zero.sql | 5 + .../testdata/rpc_volatile_values_page.http | 1 + .../testdata/rpc_volatile_values_page.sql | 5 + test/e2e_volatile_once_test.go | 136 ++++++++++++++++++ 13 files changed, 252 insertions(+), 20 deletions(-) create mode 100644 internal/compile/testdata/rpc_volatile_rows_count.http create mode 100644 internal/compile/testdata/rpc_volatile_rows_count.sql create mode 100644 internal/compile/testdata/rpc_volatile_rows_limit_zero.http create mode 100644 internal/compile/testdata/rpc_volatile_rows_limit_zero.sql create mode 100644 internal/compile/testdata/rpc_volatile_values_limit_zero.http create mode 100644 internal/compile/testdata/rpc_volatile_values_limit_zero.sql create mode 100644 internal/compile/testdata/rpc_volatile_values_page.http create mode 100644 internal/compile/testdata/rpc_volatile_values_page.sql create mode 100644 test/e2e_volatile_once_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 937a6fc..993a7c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,19 @@ becomes the release notes of the next tag. ## [Unreleased] +### Fixed + +- **Volatile `SETOF` RPCs ran more than once or not at all.** `count=true` + executed a volatile set-returning function twice (rows, then the total), + and `limit=0` on a `SETOF ` or `SETOF ` one compiled to + `LIMIT 0`, so the function never ran while the `SETOF
` form did. + A volatile set-returning function now runs exactly once per request + whatever `count`, `limit`, `offset` or `limit=0` say: its output is + materialised in a CTE that the page, the `has_next` look-ahead and the + total read. `limit=0` is consistent across result kinds (function runs + once, no rows, total still reported). Stable and immutable functions are + unchanged. + ## [0.20.0] - 2026-11-24 ### Security diff --git a/docs/rpc.md b/docs/rpc.md index de71197..744b84e 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -234,8 +234,17 @@ exception is the `auth.mint_type` composite: it is emitted raw (`to_jsonb(__fn.v)`, shapes `jwt` / `jwt_set`) so the claims keep their JSON numbers (`exp` must be numeric for verification), and exec signs them. -Volatile functions use exactly the same shapes; only the transaction policy -differs. +Volatile functions use the same shapes and the same transaction policy as +above, with one difference for set-returning ones: the call is evaluated +exactly once per request, whatever `count`, `limit`, `offset` or `limit=0` +say. The compiler materialises it in a leading +`WITH __call AS MATERIALIZED (SELECT ... FROM fn(...))` CTE and the page, the +`has_next` look-ahead row and the `count=true` total all read that CTE +instead of calling the function again. `limit=0` returns no rows for every +result kind (`SETOF
`, `SETOF `, `SETOF `), still +runs the function once, and still reports the total under `count=true`. +Stable and immutable functions keep the plain `FROM fn(...)` plan: they have +no side effects, so re-reading them is invisible. ## Volatile functions are mutations diff --git a/internal/compile/golden_test.go b/internal/compile/golden_test.go index d6f62e7..37ca2b1 100644 --- a/internal/compile/golden_test.go +++ b/internal/compile/golden_test.go @@ -121,6 +121,10 @@ func goldenCatalog() *introspect.Catalog { }, }, &introspect.Function{ Schema: "public", Name: "post_array", ReturnType: "_posts", ReturnTypeSchema: "public", Volatility: introspect.VolatilityStable, + }, &introspect.Function{ + Schema: "public", Name: "vol_posts", ReturnType: "posts", ReturnTypeSchema: "public", ReturnsSet: true, Volatility: introspect.VolatilityVolatile, + }, &introspect.Function{ + Schema: "public", Name: "vol_ints", ReturnType: "int4", ReturnTypeSchema: pg, ReturnsSet: true, Volatility: introspect.VolatilityVolatile, }, &introspect.Function{ Schema: "public", Name: "post_tab", ReturnType: "record", ReturnTypeSchema: pg, ReturnsSet: true, Volatility: introspect.VolatilityStable, ReturnColumns: []introspect.FuncArg{ @@ -357,7 +361,7 @@ func TestGolden(t *testing.T) { } // goldenOnlyRPCs are the functions goldenCatalog adds to the fixture. -var goldenOnlyRPCs = map[string]bool{"noop": true, "greet": true, "sum_all": true, "mood_counts": true, "user_stats": true, "post_array": true, "post_tab": true} +var goldenOnlyRPCs = map[string]bool{"noop": true, "greet": true, "sum_all": true, "mood_counts": true, "user_stats": true, "post_array": true, "post_tab": true, "vol_posts": true, "vol_ints": true} // TestGoldenAgainstDatabase executes every golden statement against the // live fixture database (PDBR_TEST_DATABASE_URL; skipped otherwise), each in diff --git a/internal/compile/rpc.go b/internal/compile/rpc.go index 363c9f7..972dd66 100644 --- a/internal/compile/rpc.go +++ b/internal/compile/rpc.go @@ -199,7 +199,8 @@ func (s *stmt) rpcValue(rpc *api.RPC, call string) (*Statement, error) { // over a composite or row type, whose values a FROM item also expands into // columns, so the whole row is read): the function output, bounded by // limit/offset (max_page_size when absent), aggregated in output order -// into a JSON array. +// into a JSON array. A volatile function is evaluated once in a materialized +// CTE; limit=0 then returns [] after reading it for its side effects. func (s *stmt) rpcSetOfValues(rpc *api.RPC, call string) (*Statement, error) { fn := rpc.Function limit, err := s.embedLimit(s.plan.Page) @@ -209,29 +210,55 @@ func (s *stmt) rpcSetOfValues(rpc *api.RPC, call string) (*Statement, error) { if s.plan.Page.Offset < 0 { return nil, errUser(CodeInvalidParameter, "offset must be >= 0") } + once := rpc.Mutation + if once && limit == 0 { + cte := s.callCTE(valueSource(rpc, s.structuredReturn(fn), call)) + return &Statement{SQL: cte + "SELECT '[]'::json AS data\nFROM (SELECT count(*) FROM " + callCTEName + ") AS __n", Shape: setShape(rpc)}, nil + } pageSQL := " LIMIT " + strconv.Itoa(limit) if s.plan.Page.Offset > 0 { pageSQL += " OFFSET " + s.param(s.plan.Page.Offset) } - var from, expr string - shape := ShapeScalar - switch { - case rpc.Mint: - from = fmt.Sprintf("(SELECT __v AS v FROM %s AS __v%s) AS __s", call, pageSQL) - expr = "to_jsonb(__s.v)" - shape = ShapeJWTSet - case rpc.Returns == api.ReturnSetOfComposite, s.structuredReturn(fn) != nil && !strings.HasPrefix(fn.ReturnType, "_"): - from = fmt.Sprintf("(SELECT __v AS v FROM %s AS __v%s) AS __s", call, pageSQL) - if expr, err = s.valueJSON("__s.v", fn, 0); err != nil { - return nil, err - } - default: - from = fmt.Sprintf("(SELECT __v.v FROM %s AS __v(v)%s) AS __s", call, pageSQL) + src := valueSource(rpc, s.structuredReturn(fn), call) + prefix := "" + if once { + prefix = s.callCTE(src) + src = "SELECT v FROM " + callCTEName + } + expr := "to_jsonb(__s.v)" + if !rpc.Mint { if expr, err = s.valueJSON("__s.v", fn, 0); err != nil { return nil, err } } - return &Statement{SQL: fmt.Sprintf("SELECT coalesce(json_agg(%s), '[]'::json) AS data\nFROM %s", expr, from), Shape: shape}, nil + return &Statement{SQL: fmt.Sprintf("%sSELECT coalesce(json_agg(%s), '[]'::json) AS data\nFROM (%s%s) AS __s", prefix, expr, src, pageSQL), Shape: setShape(rpc)}, nil +} + +// callCTEName names the CTE that holds a volatile function's output. +const callCTEName = "__call" + +// callCTE renders the leading WITH clause that evaluates a volatile +// set-returning function exactly once; every later read of the output +// (page, look-ahead row, total) scans this CTE instead of calling the +// function again. +func (s *stmt) callCTE(query string) string { + return "WITH " + callCTEName + " AS MATERIALIZED (" + query + ")\n" +} + +// valueSource renders the query yielding one column v per output value of a +// SETOF call. +func valueSource(rpc *api.RPC, structured *introspect.Column, call string) string { + if rpc.Mint || rpc.Returns == api.ReturnSetOfComposite || structured != nil && !strings.HasPrefix(rpc.Function.ReturnType, "_") { + return fmt.Sprintf("SELECT __v AS v FROM %s AS __v", call) + } + return fmt.Sprintf("SELECT __v.v FROM %s AS __v(v)", call) +} + +func setShape(rpc *api.RPC) Shape { + if rpc.Mint { + return ShapeJWTSet + } + return ShapeScalar } // rpcNode returns the projection node for a table-returning function. @@ -272,15 +299,23 @@ func (s *stmt) rpcRow(rpc *api.RPC, call string) (*Statement, error) { // rpcSetOfRows compiles SETOF
: the list compiler over the function // call as the root row source. Cursors are off (function output has no // stable keyset), so the page carries offset links only; the count subquery -// re-renders the same call, reusing the argument parameters. +// re-renders the same call, reusing the argument parameters. A volatile +// function is evaluated once in a materialized CTE that the page and the +// count both read. func (s *stmt) rpcSetOfRows(rpc *api.RPC, call string) (*Statement, error) { p := *s.plan p.Resource = rpc.Resource s.plan = &p s.rootSource = call + if !rpc.Mutation { + return s.list() + } + columns := s.callCTE("SELECT * FROM " + call) + s.rootSource = callCTEName st, err := s.list() if err != nil { return nil, err } + st.SQL = columns + st.SQL return st, nil } diff --git a/internal/compile/testdata/rpc_volatile_rows_count.http b/internal/compile/testdata/rpc_volatile_rows_count.http new file mode 100644 index 0000000..31a2234 --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_rows_count.http @@ -0,0 +1 @@ +POST /api/rpc/vol_posts?limit=2&offset=1&count=true diff --git a/internal/compile/testdata/rpc_volatile_rows_count.sql b/internal/compile/testdata/rpc_volatile_rows_count.sql new file mode 100644 index 0000000..5fb4b81 --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_rows_count.sql @@ -0,0 +1,11 @@ +-- request: POST /api/rpc/vol_posts?limit=2&offset=1&count=true +WITH __call AS MATERIALIZED (SELECT * FROM "public"."vol_posts"()) +SELECT json_build_object('has_next', coalesce(bool_or(s1.__rn > $2), false), 'has_prev', true, 'total', (SELECT count(*) FROM __call c2), 'n', count(*) FILTER (WHERE s1.__rn <= $2), 'rows', coalesce(json_agg(s1.data ORDER BY s1.__rn ASC) FILTER (WHERE s1.__rn <= $2), '[]'::json)) AS data +FROM ( + SELECT json_build_object('id', t0."id", 'author_id', t0."author_id", 'title', t0."title", 'body', t0."body", 'published', t0."published") AS data, row_number() OVER (ORDER BY t0."id" ASC) AS __rn + FROM __call t0 + ORDER BY t0."id" ASC + LIMIT 3 + OFFSET $1 +) s1 +-- args: [1,3] diff --git a/internal/compile/testdata/rpc_volatile_rows_limit_zero.http b/internal/compile/testdata/rpc_volatile_rows_limit_zero.http new file mode 100644 index 0000000..6b6c418 --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_rows_limit_zero.http @@ -0,0 +1 @@ +POST /api/rpc/vol_posts?limit=0&count=true diff --git a/internal/compile/testdata/rpc_volatile_rows_limit_zero.sql b/internal/compile/testdata/rpc_volatile_rows_limit_zero.sql new file mode 100644 index 0000000..34f14b5 --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_rows_limit_zero.sql @@ -0,0 +1,10 @@ +-- request: POST /api/rpc/vol_posts?limit=0&count=true +WITH __call AS MATERIALIZED (SELECT * FROM "public"."vol_posts"()) +SELECT json_build_object('has_next', coalesce(bool_or(s1.__rn > $1), false), 'has_prev', false, 'total', (SELECT count(*) FROM __call c2), 'n', count(*) FILTER (WHERE s1.__rn <= $1), 'rows', coalesce(json_agg(s1.data ORDER BY s1.__rn ASC) FILTER (WHERE s1.__rn <= $1), '[]'::json)) AS data +FROM ( + SELECT NULL::json AS data, row_number() OVER (ORDER BY t0."id" ASC) AS __rn + FROM __call t0 + ORDER BY t0."id" ASC + LIMIT 1 +) s1 +-- args: [0] diff --git a/internal/compile/testdata/rpc_volatile_values_limit_zero.http b/internal/compile/testdata/rpc_volatile_values_limit_zero.http new file mode 100644 index 0000000..113e12e --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_values_limit_zero.http @@ -0,0 +1 @@ +POST /api/rpc/vol_ints?limit=0 diff --git a/internal/compile/testdata/rpc_volatile_values_limit_zero.sql b/internal/compile/testdata/rpc_volatile_values_limit_zero.sql new file mode 100644 index 0000000..5c4fd53 --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_values_limit_zero.sql @@ -0,0 +1,5 @@ +-- request: POST /api/rpc/vol_ints?limit=0 +WITH __call AS MATERIALIZED (SELECT __v.v FROM "public"."vol_ints"() AS __v(v)) +SELECT '[]'::json AS data +FROM (SELECT count(*) FROM __call) AS __n +-- args: [] diff --git a/internal/compile/testdata/rpc_volatile_values_page.http b/internal/compile/testdata/rpc_volatile_values_page.http new file mode 100644 index 0000000..fcc77a2 --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_values_page.http @@ -0,0 +1 @@ +POST /api/rpc/vol_ints?limit=3&offset=1 diff --git a/internal/compile/testdata/rpc_volatile_values_page.sql b/internal/compile/testdata/rpc_volatile_values_page.sql new file mode 100644 index 0000000..6b718c6 --- /dev/null +++ b/internal/compile/testdata/rpc_volatile_values_page.sql @@ -0,0 +1,5 @@ +-- request: POST /api/rpc/vol_ints?limit=3&offset=1 +WITH __call AS MATERIALIZED (SELECT __v.v FROM "public"."vol_ints"() AS __v(v)) +SELECT coalesce(json_agg(to_json(__s.v)), '[]'::json) AS data +FROM (SELECT v FROM __call LIMIT 3 OFFSET $1) AS __s +-- args: [1] diff --git a/test/e2e_volatile_once_test.go b/test/e2e_volatile_once_test.go new file mode 100644 index 0000000..f2285fb --- /dev/null +++ b/test/e2e_volatile_once_test.go @@ -0,0 +1,136 @@ +package e2e + +import ( + "context" + "encoding/json" + "os" + "testing" + + "github.com/jackc/pgx/v5" + + "github.com/suprbdev/pdbr/internal/config" +) + +func TestVolatileSetReturningRunsOnce(t *testing.T) { + dbURL := os.Getenv("PDBR_TEST_DATABASE_URL") + if dbURL == "" { + t.Skip("PDBR_TEST_DATABASE_URL not set") + } + ctx := context.Background() + conn, err := pgx.Connect(ctx, dbURL) + if err != nil { + t.Fatal(err) + } + defer conn.Close(ctx) + t.Cleanup(func() { + c, err := pgx.Connect(ctx, dbURL) + if err != nil { + t.Errorf("cleanup: %v", err) + return + } + defer c.Close(ctx) + _, _ = c.Exec(ctx, `DROP FUNCTION IF EXISTS public.e2e_once_rows(), public.e2e_once_scalar(), public.e2e_once_composite(), public.e2e_once_stable_rows(); +DROP TYPE IF EXISTS public.e2e_once_pair; DROP TABLE IF EXISTS public.e2e_once_calls`) + }) + setup := ` +DROP TABLE IF EXISTS public.e2e_once_calls CASCADE; +CREATE TABLE public.e2e_once_calls (fn text NOT NULL); +GRANT ALL ON public.e2e_once_calls TO PUBLIC; +CREATE TYPE public.e2e_once_pair AS (a int, b text); +CREATE FUNCTION public.e2e_once_rows() RETURNS SETOF public.posts LANGUAGE plpgsql VOLATILE AS $$ +BEGIN + INSERT INTO public.e2e_once_calls VALUES ('rows'); + RETURN QUERY SELECT * FROM public.posts ORDER BY id LIMIT 4; +END $$; +CREATE FUNCTION public.e2e_once_scalar() RETURNS SETOF int LANGUAGE plpgsql VOLATILE AS $$ +BEGIN + INSERT INTO public.e2e_once_calls VALUES ('scalar'); + RETURN QUERY SELECT g FROM generate_series(1, 4) g; +END $$; +CREATE FUNCTION public.e2e_once_composite() RETURNS SETOF public.e2e_once_pair LANGUAGE plpgsql VOLATILE AS $$ +BEGIN + INSERT INTO public.e2e_once_calls VALUES ('composite'); + RETURN QUERY SELECT g, 'x' || g FROM generate_series(1, 4) g; +END $$` + if _, err := conn.Exec(ctx, setup); err != nil { + t.Fatal(err) + } + if n := dbInt(t, `SELECT count(*) FROM posts`); n < 4 { + t.Skipf("fixture has %d posts, need 4", n) + } + srv := testServer(t, nil).URL + rb := testServer(t, func(c *config.Config) { c.TX.End = "rollback" }).URL + + type result struct { + rows int + total string + } + reqs := []struct { + name string + path string + hdr map[string]string + want result + }{ + {"plain", "", nil, result{4, ""}}, + {"count", "?count=true", nil, result{4, "4"}}, + {"limit=0", "?limit=0", nil, result{0, ""}}, + {"limit=0 count", "?limit=0&count=true", nil, result{0, "4"}}, + {"limit offset count", "?limit=2&offset=1&count=true", nil, result{2, "4"}}, + {"offset", "?offset=3", nil, result{1, ""}}, + {"offset at end count", "?offset=4&count=true", nil, result{0, "4"}}, + {"range", "", map[string]string{"Range": "1-2", "Range-Unit": "items"}, result{-1, ""}}, + {"range count", "", map[string]string{"Range": "1-2", "Range-Unit": "items", "Prefer": "count=exact"}, result{-1, ""}}, + {"count planned", "?count=true", map[string]string{"Prefer": "count=planned"}, result{4, "4"}}, + {"count estimated", "?count=true", map[string]string{"Prefer": "count=estimated"}, result{4, "4"}}, + } + for _, fn := range []struct { + name, tag string + counted bool + }{ + {"e2e_once_rows", "rows", true}, + {"e2e_once_scalar", "scalar", false}, + {"e2e_once_composite", "composite", false}, + } { + for _, rq := range reqs { + if _, err := conn.Exec(ctx, `TRUNCATE public.e2e_once_calls`); err != nil { + t.Fatal(err) + } + res, body := send(t, "POST", srv+"/api/rpc/"+fn.name+rq.path, "{}", rq.hdr) + if res.StatusCode != 200 && res.StatusCode != 206 { + t.Errorf("%s %s: status %d %s", fn.name, rq.name, res.StatusCode, body) + continue + } + calls := dbInt(t, `SELECT count(*) FROM public.e2e_once_calls WHERE fn = '`+fn.tag+`'`) + if calls != 1 { + t.Errorf("%s %s: function ran %d times, want 1", fn.name, rq.name, calls) + } + if n := len(decodeRows(t, body)); rq.want.rows >= 0 && n != rq.want.rows { + t.Errorf("%s %s: %d rows, want %d (%s)", fn.name, rq.name, n, rq.want.rows, body) + } + if fn.counted && rq.want.total != "" { + if got := res.Header.Get("X-Total-Count"); got != rq.want.total { + t.Errorf("%s %s: X-Total-Count %q, want %q", fn.name, rq.name, got, rq.want.total) + } + } + } + if _, err := conn.Exec(ctx, `TRUNCATE public.e2e_once_calls`); err != nil { + t.Fatal(err) + } + res, body := send(t, "POST", rb+"/api/rpc/"+fn.name+"?count=true", "{}", nil) + if res.StatusCode != 200 || len(decodeRows(t, body)) != 4 { + t.Errorf("%s rollback: %d %s", fn.name, res.StatusCode, body) + } + if calls := dbInt(t, `SELECT count(*) FROM public.e2e_once_calls`); calls != 0 { + t.Errorf("%s rollback: %d calls survived", fn.name, calls) + } + } +} + +func decodeRows(t *testing.T, body []byte) []json.RawMessage { + t.Helper() + var rows []json.RawMessage + if err := json.Unmarshal(body, &rows); err != nil { + t.Fatalf("body %s: %v", body, err) + } + return rows +}