Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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 ./...
Expand Down
6 changes: 6 additions & 0 deletions docs/mutations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
14 changes: 14 additions & 0 deletions docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
12 changes: 8 additions & 4 deletions internal/compile/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
63 changes: 41 additions & 22 deletions internal/compile/fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion internal/compile/testdata/function_mutation.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
1 change: 1 addition & 0 deletions internal/compile/testdata/function_mutation_columns.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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]]

2 changes: 1 addition & 1 deletion internal/compile/testdata/function_mutation_then.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
6 changes: 3 additions & 3 deletions internal/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
18 changes: 18 additions & 0 deletions internal/exec/limits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
67 changes: 67 additions & 0 deletions test/setof_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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;
`
Expand Down Expand Up @@ -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)
}
})
}
Loading