Skip to content

fix(pg-meta): order primary key columns by key position and exclude INCLUDE columns - #382

Merged
mattrossman merged 4 commits into
supabase:mainfrom
Rjabov:fix/pg-meta-primary-key-order
Oct 26, 2026
Merged

mattrossman merged 4 commits into
supabase:mainfrom
Rjabov:fix/pg-meta-primary-key-order

Conversation

@Rjabov

@Rjabov Rjabov commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Closes #381

What kind of change does this PR introduce?

Bug fix: data-integrity issue in list_tables (verbose) primary key output.

What is the current behavior?

primary_keys is sorted by each column's physical position in the table rather than its position in the key, and it includes the non-key INCLUDE payload columns of the backing index.

create table membership (
  org_id  int not null,          -- physically column 1
  user_id int not null,          -- physically column 2
  role    text,
  primary key (user_id, org_id)
);

create table inc (a int not null, b int not null, c int not null);
create unique index inc_pk_idx on inc (a) include (b);
alter table inc add constraint inc_pk primary key using index inc_pk_idx;
table declared reported
membership (user_id, org_id) ["org_id","user_id"]
inc (a) INCLUDE (b) ["a","b"]

Root cause in pg-meta/tables.sql: a.attnum = any (i.indkey) is a set-membership test, so each column's position within the key is discarded and the enclosing jsonb_agg has no order by. indkey also spans indnatts, which includes the INCLUDE payload, rather than indnkeyatts.

This is the same defect #317 fixed in the foreign key subquery immediately below, which walks columns with unnest(...) with ordinality and aggregates order by cols.ord. The primary key subquery was not updated at the time.

What is the new behavior?

  • indkey is unnested with ordinality and the aggregate is ordered by that ordinal, so columns come back in constraint-definition order - not attnum, not alphabetical.
  • The unnest is bounded by indnkeyatts, so INCLUDE payload columns are excluded.
  • The implicit comma joins become explicit joins, which is what makes the lateral unnest readable. Output shape is unchanged: to_jsonb(_pk) - 'ord' emits exactly the same keys as before.
  • A comment records why = any (indkey) is wrong, so it doesn't get "simplified" back.

Two regression tests, both using a key order that is deliberately the reverse of the physical column order so any regression to attnum ordering fails immediately - the same shape as the FK ordering test added in #317.

Verification

Windows 11, Node 22 LTS, pnpm 10:

pnpm run build                            -> success
CI=true pnpm vitest run --project unit    -> 212 passed | 5 failed (217)
pnpm typecheck                            -> clean
npx @biomejs/[email protected] ci .             -> Checked 89 files. No fixes applied.

Both new tests pass:

✓ tools > composite primary key preserves constraint-definition column order
✓ tools > primary key excludes non-key INCLUDE columns

The 5 failures are pre-existing and unrelated to this change. They are all normalizeFilename: edge-function.ts imports resolve from node:path, which is platform-dispatched, but strips a hardcoded POSIX prefix (/tmp/user_fn_.../), so on Windows the strip never matches and the full C:\tmp\... path is returned. 3 direct failures in edge-function.test.ts plus 2 downstream in server.test.ts (list edge functions, get edge function). I confirmed the identical 5 failures on clean upstream/main with nothing applied, so they are the baseline, not a regression. Happy to file that separately - node:path/posix looks like the one-line fix, and every caller already forces POSIX semantics with fileURLToPath(..., { windows: false }).

End to end against a real MCP client and server (createSupabaseMcpServer over StreamTransport, PostgreSQL 16.4 via PGlite), calling list_tables with verbose: true:

before   membership  declared (user_id, org_id)   ->  ["org_id","user_id"]
         triple      declared (r, q, p)           ->  ["p","q","r"]
         inc         declared (a) INCLUDE (b)     ->  ["a","b"]

after    membership                               ->  ["user_id","org_id"]
         triple                                   ->  ["r","q","p"]
         inc                                      ->  ["a"]

Single-column primary keys and the composite foreign key output from #317 are unchanged on both builds.

On whether this actually misleads a model

I tested it rather than asserting it, and the result is mostly negative, so it's worth stating plainly: across 18 runs (3 models × 3 questions × before/after, one replicate per cell) 17 answered correctly on both builds. Models generally did not trust primary_keys - 17 of 18 runs called execute_sql and read pg_index/pg_constraint directly. Two runs spontaneously flagged the output as wrong, e.g. "list_tables reports the primary key as ["a","b"], which is misleading: it lumps the INCLUDE column in with the real key column."

The one failure was a weaker model on "what's the primary key on membership?" against the unfixed build, which answered org_id, user_id. Notably its own verification query used information_schema.key_column_usage without order by ordinal_position, so it confirmed the wrong answer.

So the case for this fix is not "agents give wrong answers". It's that primary_keys contradicts the database, that models are paying for a catalog round-trip list_tables exists to save, and that a non-agent consumer of the published package has no fallback at all.

What I did not test

  • Only against PGlite (PostgreSQL 16.4) and the repo's test harness, not a live Supabase project. indnkeyatts requires PG 11+.
  • One replicate per cell in the model matrix, and those runners were agents with shell access, which lean toward verifying - a plain chat client may lean on list_tables more than these did.

@Rjabov
Rjabov requested a review from a team as a code owner August 25, 2026 15:01
@mattrossman

Copy link
Copy Markdown
Collaborator

I pushed two commits to your branch:

  • A merge of main. server.test.ts was split into per-area files, so the conflict was resolved by taking main's version.
  • A simplification. I trimmed the SQL comment and folded the two regression tests into one in server.database.test.ts, next to the composite FK tests.

The SQL logic is unchanged. Both cases still fail on main and pass here.

@mattrossman

Copy link
Copy Markdown
Collaborator

(tests failing in CI is expected due to lack of secrets in your fork, I ran locally and they behave normally)

@mattrossman
mattrossman merged commit 25d357c into supabase:main Oct 26, 2026
4 of 5 checks passed
@supabase-releaser supabase-releaser Bot mentioned this pull request Oct 26, 2026
mattrossman added a commit that referenced this pull request Oct 28, 2026
array_agg in coalesceRowsToArray followed heap scan order, which is not
guaranteed. ALTER COLUMN rewrites a column's pg_attribute row and moves
it to the end of the heap, so list_tables could return columns out of
order. Add an optional orderBy argument to coalesceRowsToArray and use
columns.ordinal_position when building the table columns.

Adds a test that alters columns and checks the order stays the same.

## What kind of change does this PR introduce?

Bug fix

## What is the current behavior?

Fixes #496

`list_tables` (verbose) builds each table's `columns` with
`array_agg(row_to_json(columns))` and no `ORDER BY`, so the order
follows `pg_attribute` scan order. `ALTER COLUMN ... SET NOT NULL` /
`SET DEFAULT` / `TYPE` write a new `pg_attribute` row version at the end
of the heap, so that column is returned last. `ordinal_position` is
stripped from the output, so the agent can't recover the real order.

## What is the new behavior?

Columns are returned in `ordinal_position` order. `coalesceRowsToArray`
takes an optional `orderBy`, and `listTablesSql` passes
`columns.ordinal_position`. When `orderBy` is omitted, the generated SQL
is unchanged.

No change to tool names, descriptions, input/output schemas or output
shape. This is a server-only fix, so the published `tools/list` contract
is untouched.

## How to Review

<!--
A reviewer should understand what this PR does within 15-30 seconds,
then know where to start reading.

Non-trivial or multi-file PRs must fill in the reading path below.
Trivial single-file changes may delete this section when the review path
is obvious.

- Start from the main public entrypoint or request handler, and follow
the actual execution path before reading tests.
- Use bold numbered areas, each with one or two indented bullets: the
exact files, then what to inspect.
- Use exact repository-relative paths, and avoid line numbers while the
branch is still changing.
- Prefer project-facing language such as `interface`, `extension point`,
or `contract` over internal design jargon.
- Don't repeat the PR purpose or the verification commands here. Keep
the section scannable.
-->

1. **Column aggregation**
   - `packages/mcp-server-supabase/src/pg-meta/index.ts`
- `coalesceRowsToArray` gains an optional `orderBy` placed inside
`array_agg(...)` before `FILTER`. `listTablesSql` is its only caller.

2. **Tests**
   - `packages/mcp-server-supabase/src/server.database.test.ts`
- `list tables returns columns in ordinal position order after ALTER
COLUMN` checks the observable column order from the `list_tables` tool
after the ALTERs that reorder the heap.

**Review questions**

<!-- Four to six short questions covering the reviewer's judgment calls.
-->

- [ ] Is the public contract minimal and intentional?
- [ ] Do the main execution paths preserve existing behavior?
- [ ] Do failures stop safely?
- [ ] Do tests protect observable behavior rather than implementation
details?

## Verification

- Regression test without the fix fails:
  ```
× tools > list tables returns columns in ordinal position order after
ALTER COLUMN
  - Expected
  + Received
    Array [
  -   "id",
  -   "email",
      "name",
      "age",
  +   "email",
  +   "id",
    ]
  ```
- With the fix it passes.
- `pnpm --filter @supabase/mcp-server-supabase test:unit --run`: 34
files, 736 tests passed.
- `pnpm --filter @supabase/mcp-server-supabase test:integration --run`
(stdio, after a fresh build): 7/7 passed.
- `biome check`, `tsc --noEmit` and the package build are clean.

I reviewed the diff and ran the tests above locally.

## Additional context

Same class of issue as #381 / #382 (primary key column order).

---------

Co-authored-by: Matt Rossman <[email protected]>
Rodriguespn pushed a commit that referenced this pull request Oct 29, 2026
🤖 I have created a release *beep* *boop*
---


<details><summary>mcp-server-supabase: 0.15.0</summary>

##
[0.15.0](mcp-server-supabase-v0.14.0...mcp-server-supabase-v0.15.0)
(2026-10-29)


### Features

* `submit_feedback` and `delete_feedback` tools
([#474](#474))
([f50318a](f50318a))
* mark client-caused tool errors as ToolCallerError
([#480](#480))
([4a619c1](4a619c1))
* **mcp-server-supabase:** detect instant elicitation cancels
([#483](#483))
([5ad1a2a](5ad1a2a))


### Bug Fixes

* **mcp-server-supabase:** return a tool error when a confirmation
expires ([#490](#490))
([5ab9a98](5ab9a98))
* **mcp-server-supabase:** use POSIX path resolution for edge function
filenames ([#393](#393))
([55d2d24](55d2d24))
* **mcp:** don't split an UPDATE on a semicolon inside a dollar-quoted
value ([#482](#482))
([9f07410](9f07410))
* **mcp:** don't split an UPDATE on a semicolon inside a quoted value
([#459](#459))
([6d93b50](6d93b50))
* **pg-meta:** order list_tables columns by ordinal position
([c242e63](c242e63))
* **pg-meta:** order primary key columns by key position and exclude
INCLUDE columns ([#382](#382))
([25d357c](25d357c))
</details>

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: supabase-releaser[bot] <223506987+supabase-releaser[bot]@users.noreply.github.com>
barryroodt pushed a commit that referenced this pull request Nov 4, 2026
…tables (#508)

Closes #507

## What kind of change does this PR introduce?

Bug fix, plus an optional `partition_of` output field.

## What is the current behavior?

`list_tables` reports the FK clones Postgres creates for partitions as
separate foreign keys, so one FK is listed once per partition. Nothing
in the output marks a partition's parent.

## What is the new behavior?

The relationships subquery filters `conparentid = 0`, the predicate
`pg_dump` uses, so each FK is reported once. FKs declared directly on a
partition are still reported.

Partitions carry `partition_of`, their immediate parent in the same
`schema.name` format as `name`, in both compact and verbose output:

```jsonc
{ "name": "public.events_2025", "rls_enabled": false, "rows": 0, "partition_of": "public.events" }
```

A sub-partition points to its own parent, not the root. Other tables
omit the field, including `INHERITS` children. A partition still names
its parent when the parent's schema isn't in `schemas`, as
`target_table` already does.

No change to tool names, descriptions or input schemas. `partition_of`
is optional in the output schema. Databases without partitioned tables
get identical output.

## How to Review

1. **Query**
   - `packages/mcp-server-supabase/src/pg-meta/tables.sql`
- One predicate in the relationships subquery. `conparentid` rather than
`relispartition`, which would also hide FKs declared on or pointing at a
partition.
- One scalar subquery for `partition_of`. It filters the parent on
`relkind = 'p'`, because `INHERITS` children also have `pg_inherits`
rows.

2. **Output**
- `packages/mcp-server-supabase/src/pg-meta/types.ts`,
`packages/mcp-server-supabase/src/tools/database-operation-tools.ts`
   - `partition_of` is omitted when null, like `comment`.

3. **Tests**
- `packages/mcp-server-supabase/src/server.database.test.ts`, next to
the composite-FK tests:
- Clones on both sides of an FK are dropped, while an FK declared on a
partition is kept.
- `partition_of` in both modes for a root, a partition, a sub-partition,
a partition in another schema, an `INHERITS` parent and its child.

**Review questions**

- [ ] Is the immediate parent, rather than the root, what you want in
`partition_of`?
- [ ] Is the public contract minimal and intentional?
- [ ] Do the main execution paths preserve existing behavior?
- [ ] Do tests protect observable behavior rather than implementation
details?

## Verification

Without the fix, the FK test fails (trimmed):

```
× tools > partition clones of an FK are not reported as separate constraints
AssertionError: expected [ { …(5) }, { …(5) }, { …(5) } ] to deeply equal [ { …(5) } ]
+     "name": "order_items_order_id_fkey1",
+     "target_table": "public.orders_p0",
+     "name": "order_items_order_id_fkey2",
+     "target_table": "public.orders_p1",
```

Without `partition_of`, the `partition_of` test fails with `expected
undefined to be 'public.events'`. It also fails if `INHERITS` children
are marked, if `partition_of` points to the root, or if it uses the
partition's schema instead of the parent's.

With the fix, the CI steps pass locally:

- `biome ci .`: clean
- Management API types regenerated: no diff
- `pnpm run build` and `pnpm run test:packed-platform-consumer`: 3/3
- `vitest --coverage --project unit --project integration`: 752 passed
- `typecheck`: clean
- `tables.sql` on PostgreSQL 15.19 and 17.11 with the schema from #507,
plus sub-, default and cross-schema partitions, a detached partition and
`INHERITS` children: each FK reported once, `partition_of` set only on
partitions

The `test` job's 5 e2e tests need `ANTHROPIC_API_KEY`, which fork PRs
don't receive (same as #382 and #497).

I reviewed the diff and ran the checks above locally. I used AI tooling
while developing it.

## Additional context

Same class of fix as #382 and #497. `partition_of` follows the
suggestion in #507.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

list_tables reports primary key columns in attnum order, and includes non-key INCLUDE columns

3 participants