From 84f4774f292b17964fc48f2b7068901f320a5282 Mon Sep 17 00:00:00 2001 From: Matt Edmonston Date: Tue, 24 Nov 2026 02:33:31 +0000 Subject: [PATCH 1/2] test(compile): benchmark the FuzzFilter iteration; cap fuzz minimisation at 1s The fuzzer stalled at 0 execs/sec for most of a run because each new interesting input was minimised for up to 60s (the default fuzzminimizetime) while the workers made no progress. The schemas were already built once; an iteration costs about 370us of compilation. --- Makefile | 2 +- internal/compile/fuzz_test.go | 63 +++++++++++++++++++++++------------ 2 files changed, 42 insertions(+), 23 deletions(-) diff --git a/Makefile b/Makefile index 5bc09a5..e1b43d4 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ bench: ## Run compile benchmarks $(GO) test -bench=. -benchmem -run=^$$ ./internal/compile/ fuzz: ## Fuzz the filter compiler for 30s - $(GO) test -fuzz=FuzzFilter -fuzztime=30s ./internal/compile/ + $(GO) test -fuzz=FuzzFilter -fuzztime=30s -fuzzminimizetime=1s ./internal/compile/ lint: ## Run golangci-lint golangci-lint run ./... diff --git a/internal/compile/fuzz_test.go b/internal/compile/fuzz_test.go index ba126a1..e8aa85a 100644 --- a/internal/compile/fuzz_test.go +++ b/internal/compile/fuzz_test.go @@ -28,6 +28,46 @@ import ( // offset and offset-cursor pagination (with and without distinctOn), and // through a custom mutation whose payload compiles to a Then statement. func FuzzFilter(f *testing.F) { + compileWith, baseline := filterHarness(f) + + f.Add("a@example.com", "admin", 5) + f.Add(`'; DROP TABLE users; --`, `"]}`, -1) + f.Add("%_\\", "'", 0) + f.Add("", "", 1<<30) + + f.Fuzz(func(t *testing.T, email, tag string, n int) { + for i, stmt := range compileWith(t, email, tag, n) { + if stmt == nil { + continue + } + if stmt.SQL != baseline[i].SQL { + t.Fatalf("SQL text varied with input values:\n--- baseline ---\n%s\n--- got ---\n%s", baseline[i].SQL, stmt.SQL) + } + if len(stmt.Args) != len(baseline[i].Args) { + t.Fatalf("parameter count varied: %d != %d", len(stmt.Args), len(baseline[i].Args)) + } + then, want := stmt.Then, baseline[i].Then + if (then == nil) != (want == nil) || then != nil && (then.SQL != want.SQL || len(then.Args) != len(want.Args)) { + t.Fatalf("Then statement varied with input values:\n--- baseline ---\n%+v\n--- got ---\n%+v", want, then) + } + } + }) +} + +// BenchmarkFuzzFilterExec times one FuzzFilter iteration (every operation +// compiled for one value set), the unit the fuzzer's execs/sec counts. +func BenchmarkFuzzFilterExec(b *testing.B) { + compileWith, _ := filterHarness(b) + b.ResetTimer() + for i := 0; i < b.N; i++ { + compileWith(b, "a@example.com", "admin", 5) + } +} + +// filterHarness builds the schemas and operations FuzzFilter drives once, and +// returns the function compiling every operation for one value set together +// with the statements compiled for a baseline value set. +func filterHarness(f testing.TB) (func(t testing.TB, email, tag string, n int) []*compile.Statement, []*compile.Statement) { built := buildContrib(f) aggBuilt := buildAggregates(f) @@ -221,28 +261,7 @@ func FuzzFilter(f *testing.F) { f.Fatal("the custom mutation compiled without a Then statement") } - f.Add("a@example.com", "admin", 5) - f.Add(`'; DROP TABLE users; --`, `"]}`, -1) - f.Add("%_\\", "'", 0) - f.Add("", "", 1<<30) - - f.Fuzz(func(t *testing.T, email, tag string, n int) { - for i, stmt := range compileWith(t, email, tag, n) { - if stmt == nil { - continue - } - if stmt.SQL != baseline[i].SQL { - t.Fatalf("SQL text varied with input values:\n--- baseline ---\n%s\n--- got ---\n%s", baseline[i].SQL, stmt.SQL) - } - if len(stmt.Args) != len(baseline[i].Args) { - t.Fatalf("parameter count varied: %d != %d", len(stmt.Args), len(baseline[i].Args)) - } - then, want := stmt.Then, baseline[i].Then - if (then == nil) != (want == nil) || then != nil && (then.SQL != want.SQL || len(then.Args) != len(want.Args)) { - t.Fatalf("Then statement varied with input values:\n--- baseline ---\n%+v\n--- got ---\n%+v", want, then) - } - } - }) + return compileWith, baseline } // FuzzSpatial is FuzzFilter for the PostGIS path: WKT strings and bounding-box From 14a11bc2438e4afe8f97ab5f87c3c8426044e868 Mon Sep 17 00:00:00 2001 From: Matt Edmonston Date: Tue, 24 Nov 2026 02:33:31 +0000 Subject: [PATCH 2/2] fix(security)!: bound the result list of set-returning mutations The result list of a volatile SETOF function exposed as a custom mutation compiles with LIMIT limits.max_page_size, in both the call statement and the statement pair, and the cost estimate charges it that many rows instead of 10. The function still runs to completion. BREAKING CHANGE: a custom mutation's SETOF result list holds at most limits.max_page_size items. --- CHANGELOG.md | 8 +++ docs/mutations.md | 6 ++ docs/upgrading.md | 14 ++++ internal/compile/functions.go | 12 ++-- .../compile/testdata/function_mutation.sql | 2 +- .../testdata/function_mutation_columns.sql | 1 + .../testdata/function_mutation_then.sql | 2 +- internal/exec/exec.go | 6 +- internal/exec/limits_test.go | 18 +++++ test/setof_e2e_test.go | 67 +++++++++++++++++++ 10 files changed, 127 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4230b48..5d82251 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ becomes the release notes of the next tag. ## [Unreleased] +### Changed + +- **Breaking:** the result list of a volatile `SETOF` function exposed as a + custom mutation holds at most `limits.max_page_size` items (the function + still runs to completion) and the cost estimate charges it that many rows; + it was unbounded and costed as 10 rows + ([upgrading](docs/upgrading.md#set-returning-mutation-result-lists-hold-at-most-a-page)). + ## [0.31.0] - 2026-11-24 ### Added diff --git a/docs/mutations.md b/docs/mutations.md index 691cdaf..47c6560 100644 --- a/docs/mutations.md +++ b/docs/mutations.md @@ -164,6 +164,12 @@ The result field is named the way PostGraphile names it: | `void` | no result field | | the `auth.mint_type` composite | the composite's name (`jwt: String`, the signed token) | +A `SETOF` result list (rows, composites or scalars) holds at most +`limits.max_page_size` items, like a set-returning query function, and the +cost estimate charges it that many rows. The function still runs to +completion and writes everything it writes; only the returned list is cut +off, so a function that must return more rows pages inside the function. + Functions returning an anonymous `record` without `OUT` parameters (or `SETOF record`) are not exposed, as in PostGraphile: the shape of the row is only known per call (PostgreSQL requires a column definition list to read it), diff --git a/docs/upgrading.md b/docs/upgrading.md index 4084c59..25da66a 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -260,6 +260,20 @@ connection instead. | `searchPosts(term: "")` returns every matching row | at most `limits.max_page_size` rows | | `{ searchPosts { … postsByAuthorId { nodes { … } } } }` costs 10 × its selection | `max_page_size` × its selection, so a nested connection below it may now exceed `limits.max_cost` | +### Set-returning mutation result lists hold at most a page + +The result list of a volatile `SETOF` function exposed as a custom mutation +(`publishPosts { posts { … } }`) had no `LIMIT` and was costed as 10 rows. +It now holds at most `limits.max_page_size` items (100 by default) and the +cost estimate charges it that many rows, like a `SETOF` query function. The +function itself still runs to completion; only the returned list is cut off. +A function that must return more rows pages inside the function. + +| Before | After | +|---|---| +| `publishPosts` returns every row the function returned | at most `limits.max_page_size` rows | +| `publishPosts { posts { … commentsByPostId { nodes { … } } } }` costs 10 × its selection | `max_page_size` × its selection | + ### Smaller behaviour changes | Before | After | diff --git a/internal/compile/functions.go b/internal/compile/functions.go index 2122ee5..f889173 100644 --- a/internal/compile/functions.go +++ b/internal/compile/functions.go @@ -305,7 +305,11 @@ func (s *stmt) functionMutation(meta *schema.FieldMeta, f *ast.Field) (string, e var first, second string if table != nil { alias := s.alias("t") - first = fmt.Sprintf("SELECT coalesce(json_agg(%s::text), '[]'::json) AS data\nFROM %s AS %s", alias, call, alias) + from := fmt.Sprintf("%s AS %s", call, alias) + if fn.ReturnsSet { + from = fmt.Sprintf("(SELECT * FROM %s LIMIT %d) AS %s", call, s.maxPageSize, alias) + } + first = fmt.Sprintf("SELECT coalesce(json_agg(%s::text), '[]'::json) AS data\nFROM %s", alias, from) second, err = then.functionRowsPayload(fn, table, f, payloadType, fields) } else { var results []*ast.Field @@ -535,19 +539,19 @@ func (s *stmt) functionPayload(fn *introspect.Function, call string, f *ast.Fiel } sub := s.alias("s") from = fmt.Sprintf("(SELECT coalesce(json_agg(%s.data), '[]'::json) AS data FROM (\n%s\n) AS %s) AS __agg", - sub, indent(fmt.Sprintf("SELECT %s AS data\nFROM %s AS %s%s", jsonExpr, call, rowAlias, joinLaterals(lats))), sub) + sub, indent(fmt.Sprintf("SELECT %s AS data\nFROM %s AS %s%s\nLIMIT %d", jsonExpr, call, rowAlias, joinLaterals(lats), s.maxPageSize)), sub) case fnComposite: expr, err := s.fnCompositeJSON("__v.v", fn, comp, resultSel, 1) if err != nil { return "", err } - from = fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM (SELECT %s AS v) AS __v) AS __agg", expr, call) + from = fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM (SELECT %s AS v LIMIT %d) AS __v) AS __agg", expr, call, s.maxPageSize) default: value, err := s.fnValueJSON("__v", fn, resultField) if err != nil { return "", err } - from = fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM %s AS __v) AS __agg", value, call) + from = fmt.Sprintf("(SELECT coalesce(json_agg(%s), '[]'::json) AS data FROM (SELECT __v FROM %s AS __v LIMIT %d) AS __v(__v)) AS __agg", value, call, s.maxPageSize) } resultExpr = "__agg.data" case row != nil || shape == fnRows: diff --git a/internal/compile/testdata/function_mutation.sql b/internal/compile/testdata/function_mutation.sql index 9edbb43..d906ff1 100644 --- a/internal/compile/testdata/function_mutation.sql +++ b/internal/compile/testdata/function_mutation.sql @@ -53,7 +53,7 @@ FROM (SELECT "public"."retry_probe"() AS v) AS __fn -- field: publishPosts SELECT coalesce(json_agg(__t_1::text), '[]'::json) AS data -FROM "public"."publish_posts"("post_ids" => $1::"pg_catalog"."_int4") AS __t_1 +FROM (SELECT * FROM "public"."publish_posts"("post_ids" => $1::"pg_catalog"."_int4") LIMIT 100) AS __t_1 -- args: [[1,2]] -- then: SELECT json_build_object('posts', (SELECT coalesce(json_agg(__s_5.data ORDER BY __s_5.n), '[]'::json) FROM ( diff --git a/internal/compile/testdata/function_mutation_columns.sql b/internal/compile/testdata/function_mutation_columns.sql index 7783725..901bf1c 100644 --- a/internal/compile/testdata/function_mutation_columns.sql +++ b/internal/compile/testdata/function_mutation_columns.sql @@ -3,6 +3,7 @@ SELECT json_build_object('posts', __agg.data) AS data FROM (SELECT coalesce(json_agg(__s_2.data), '[]'::json) AS data FROM ( SELECT json_build_object('id', __t_1."id", 'title', __t_1."title") AS data FROM "public"."publish_posts"("post_ids" => $1::"pg_catalog"."_int4") AS __t_1 + LIMIT 100 ) AS __s_2) AS __agg -- args: [[1,2]] diff --git a/internal/compile/testdata/function_mutation_then.sql b/internal/compile/testdata/function_mutation_then.sql index 0bd8b46..c75efe1 100644 --- a/internal/compile/testdata/function_mutation_then.sql +++ b/internal/compile/testdata/function_mutation_then.sql @@ -38,7 +38,7 @@ SELECT json_build_object('integer', ($1::json -> 'integer'), 'again', ($1::json -- field: publishPosts SELECT coalesce(json_agg(__t_1::text), '[]'::json) AS data -FROM "public"."publish_posts"("post_ids" => $1::"pg_catalog"."_int4") AS __t_1 +FROM (SELECT * FROM "public"."publish_posts"("post_ids" => $1::"pg_catalog"."_int4") LIMIT 100) AS __t_1 -- args: [[1,2]] -- then: SELECT json_build_object('first', (SELECT coalesce(json_agg(__s_3.data ORDER BY __s_3.n), '[]'::json) FROM ( diff --git a/internal/exec/exec.go b/internal/exec/exec.go index c92d84d..d223eff 100644 --- a/internal/exec/exec.go +++ b/internal/exec/exec.go @@ -1199,8 +1199,8 @@ func (m *measurer) connection(sel ast.SelectionSet, depth int) (rows, once measu } // setReturningList reports whether f is a list returned by a set-returning -// function (a root function or a computed column), which the compiler cuts -// at the page-size cap. +// function (a root function, a computed column or the result of a custom +// mutation), which the compiler cuts at the page-size cap. func setReturningList(f *ast.Field, meta schema.Meta) bool { if meta == nil || f.ObjectDefinition == nil || f.Definition == nil || f.Definition.Type.NamedType != "" { return false @@ -1209,7 +1209,7 @@ func setReturningList(f *ast.Field, meta schema.Meta) bool { if fm == nil || fm.Function == nil || !fm.Function.ReturnsSet { return false } - return fm.Kind == schema.KindFunction || fm.Kind == schema.KindComputed + return fm.Kind == schema.KindFunction || fm.Kind == schema.KindComputed || fm.Kind == schema.KindPayloadResult } // fieldCostMultiplier returns the @costMultiplier override bound to a field, diff --git a/internal/exec/limits_test.go b/internal/exec/limits_test.go index b80ac89..7d2f516 100644 --- a/internal/exec/limits_test.go +++ b/internal/exec/limits_test.go @@ -360,3 +360,21 @@ func TestCostRasterFields(t *testing.T) { } } } + +// TestCostMutationResultListPricedAtPageSize charges the result list of a +// custom mutation returning SETOF rows like a connection without first: the +// page-size cap rows the compiled LIMIT fetches, each with its nested +// connection. +func TestCostMutationResultListPricedAtPageSize(t *testing.T) { + cat := testutil.FixtureCatalog() + cat.Functions = append(cat.Functions, &introspect.Function{ + Schema: "public", Name: "publish_posts", + Args: []introspect.FuncArg{{Name: "post_ids", PGType: "_int4", TypeSchema: "pg_catalog"}}, + ReturnType: "posts", ReturnTypeSchema: "public", ReturnsSet: true, Volatility: introspect.VolatilityVolatile, + }) + list := costWith(t, cat, `mutation { publishPosts(input: {postIds: [1]}) { posts { id commentsByPostId { nodes { id body } } } } }`, nil) + conn := cost(t, `{ allPosts { nodes { id commentsByPostId { nodes { id body } } } } }`, nil) + if want := conn - 99; list != want { + t.Errorf("mutation result list costs %d, want %d like the same rows through a connection (less its nodes fields, plus the payload)", list, want) + } +} diff --git a/test/setof_e2e_test.go b/test/setof_e2e_test.go index e6cc223..f688bd3 100644 --- a/test/setof_e2e_test.go +++ b/test/setof_e2e_test.go @@ -20,6 +20,15 @@ $$; CREATE FUNCTION setof_e2e.many_numbers() RETURNS SETOF integer STABLE LANGUAGE sql AS $$ SELECT generate_series(1, 5000) $$; +CREATE FUNCTION setof_e2e.bulk_users() RETURNS SETOF public.users VOLATILE LANGUAGE sql AS $$ + SELECT u.* FROM public.users u, generate_series(1, 2000) +$$; +CREATE FUNCTION setof_e2e.bulk_numbers() RETURNS SETOF integer VOLATILE LANGUAGE sql AS $$ + SELECT generate_series(1, 5000) +$$; +CREATE FUNCTION setof_e2e.bulk_pairs() RETURNS TABLE (a integer, b text) VOLATILE LANGUAGE sql AS $$ + SELECT g, 'x' FROM generate_series(1, 5000) g +$$; GRANT USAGE ON SCHEMA setof_e2e TO anonymous, app_user; GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA setof_e2e TO anonymous, app_user; ` @@ -94,3 +103,61 @@ func TestSetReturningListsBounded(t *testing.T) { } }) } + +// TestSetReturningMutationResultBounded: the result list of a volatile SETOF +// function exposed as a custom mutation holds at most limits.max_page_size +// items, whether the payload reads tables (a second statement) or not, and +// the cost estimate charges it that many rows. +func TestSetReturningMutationResultBounded(t *testing.T) { + execAll(t, testConn(t), setofSchemaSQL) + t.Cleanup(func() { execAll(t, testConn(t), `DROP SCHEMA IF EXISTS setof_e2e CASCADE`) }) + serve := func(mutate func(*config.Config)) string { + return testServer(t, func(c *config.Config) { + c.Schema.Schemas = []string{"public", "setof_e2e"} + if mutate != nil { + mutate(c) + } + }).URL + } + count := func(t *testing.T, url, query, field, result string) int { + t.Helper() + var out struct { + Data map[string]map[string]json.RawMessage `json:"data"` + Errors []json.RawMessage `json:"errors"` + } + if err := json.Unmarshal([]byte(postRaw(t, url, query, nil)), &out); err != nil || len(out.Errors) > 0 { + t.Fatalf("%s: %v %s", query, err, out.Errors) + } + var items []json.RawMessage + if err := json.Unmarshal(out.Data[field][result], &items); err != nil { + t.Fatalf("%s: %v: %s", query, err, out.Data[field][result]) + } + return len(items) + } + + def := serve(nil) + small := serve(func(c *config.Config) { c.Limits.MaxPageSize = 7 }) + for _, tc := range []struct{ name, query, field, result string }{ + {"rows", `mutation { bulkUsers(input: {}) { users { id } } }`, "bulkUsers", "users"}, + {"rows with relations", `mutation { bulkUsers(input: {}) { users { id postsByAuthorId(first: 1) { nodes { id } } } } }`, "bulkUsers", "users"}, + {"scalars", `mutation { bulkNumbers(input: {}) { integers } }`, "bulkNumbers", "integers"}, + {"composites", `mutation { bulkPairs(input: {}) { results { a b } } }`, "bulkPairs", "results"}, + } { + t.Run(tc.name, func(t *testing.T) { + if n := count(t, def, tc.query, tc.field, tc.result); n != 100 { + t.Errorf("default page size: %d items, want 100", n) + } + if n := count(t, small, tc.query, tc.field, tc.result); n != 7 { + t.Errorf("max_page_size 7: %d items, want 7", n) + } + }) + } + + t.Run("cost", func(t *testing.T) { + url := serve(func(c *config.Config) { c.Limits.MaxCost = 10000 }) + q := `mutation { bulkUsers(input: {}) { users { id email postsByAuthorId { totalCount nodes { id title body } } } } }` + if got := postRaw(t, url, q, nil); !strings.Contains(got, `"code":"cost_exceeded"`) { + t.Errorf("%s: %s, want cost_exceeded", q, got) + } + }) +}