Skip to content

perf(postgres-driver): skip relation array types when loading user defined types - #11587

Merged
ovr merged 1 commit into
masterfrom
postgres-loaduserdefinedtypes-profiling
Aug 18, 2026
Merged

ovr merged 1 commit into
masterfrom
postgres-loaduserdefinedtypes-profiling

Conversation

@ovr

@ovr ovr commented Aug 18, 2026

Copy link
Copy Markdown
Member

Check List

  • Tests have been run in packages where changes have been made if available
  • Linter has been run for changed code
  • Tests for the changes have been added if not covered yet
  • Docs have been added / updated if required

Description of Changes Made (if issue reference is not provided)

#11149 made loadUserDefinedTypes select all of typcategory = 'A' so that array-typed columns map to text, but Postgres creates a row type and an array over it for every relation, so that returns one row per relation in the database — on a multi tenant deployment with a schema per tenant this reached ~63k rows, and the quadratic map build behind it blocked the event loop for minutes on every cold driver. Arrays over relation row types are now skipped, which brings the same database down to ~116 rows while leaving everything the driver actually maps in place: _text 1009 and _int4 1007 that #11149 relies on, enums, enum arrays, extension types such as hll, and arrays over a standalone CREATE TYPE ... AS (...). Verified on postgres:16 (150 schemas of 20 tables: 3317 rows before, 108 after) and on CrateDB 5.10, which inherits this through CrateDriver and returns the same 24 rows for both queries. A stream (user defined type) test covers both a composite array and a domain column, and it fails with Unable to detect type if the relkind <> 'c' carve-out is removed.

@ovr
ovr requested a review from a team as a code owner August 18, 2026 12:49
@github-actions github-actions Bot added driver:postgres Issues relating to the Postgres driver javascript Pull requests that update Javascript code data source driver labels Aug 18, 2026
@claude

claude Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 29s —— View job


Review complete — approach is sound; 1 medium, 3 low. Main gap: the O(n²) map build behind the reported stall is untouched.

Full review (4 inline comments)
  • Read the diff and surrounding driver code
  • Check catalog query semantics / regressions
  • Check test coverage
  • Post findings

Summary

The diagnosis is correct and the catalog query is right. t.typelem → element type, typtype = 'c' → composite, relkind <> 'c' → the row type belongs to a real relation rather than a standalone CREATE TYPE ... AS (...). That excludes exactly the auto-generated per-relation array types and keeps enums, enum arrays, extension types, _text/_int4, and arrays over standalone composites. The JOIN pg_class can't drop anything unintended either, since typtype = 'c' always implies a non-zero typrelid. Correlated NOT EXISTS on pg_type.oid is index-driven, so the query itself doesn't get slower. CrateDriver inheriting this is fine and was checked against 5.10 per the description.

No security surface here — the query is static with no interpolation, and it runs against catalog tables only.

Findings

# Severity Location Issue
1 Medium PostgresDriver.ts:333-336 The quadratic reduce — the thing the commit message blames for the multi-minute event-loop stall — is untouched. Row-count reduction hides it for this deployment, but typcategory in ('U','E') is still unbounded (enums per tenant schema), so the same curve returns. One-line fix.
2 Low PostgresDriver.ts:327 Behavior change worth stating as an accepted trade-off: whole-row arrays (array_agg(t), a my_table[] column reached via user sql: or a view) went from mapping to text to throwing Unable to detect type. Suggested a lazy per-oid fallback if the cliff matters.
3 Low test/PostgresDriver.test.ts:150-196 No test covers the exclusion half of the change, so widening the filter back to all of typcategory = 'A' would pass silently and lose the fix. Also _text/_int4 from #11149 are verified only by hand, not by the suite.
4 Low PostgresDriver.ts:306 Comment typo "NON EXIST" → NOT EXISTS; suggested folding the commit-message rationale (why it's safe, why relkind <> 'c') into the comment.

Not run

I did not run yarn test for this package — the driver tests need Docker/testcontainers to start postgres:16, which isn't available in this environment. Correctness claims above are from reading the catalog semantics, not from execution; the row-count and CrateDB numbers in the description are unverified by me.

· branch `postgres-loaduserdefinedtypes-profiling`

@ovr
ovr force-pushed the postgres-loaduserdefinedtypes-profiling branch from cf5f17a to 7a9fc13 Compare August 18, 2026 12:50
@claude

claude Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 8s —— View job


Review: approach is sound, one perf gap left on the table — 0 blocking, 1 medium, 3 low (all previously filed, still open)

Full review — click to expand

Todos

  • Gather context (diff, PostgresDriver.ts, subclasses, test setup)
  • Classify request → code review
  • Check existing review threads for staleness / duplicates
  • Analyze SQL correctness, perf, tests
  • Post review

Verdict

The diagnosis is right and the fix is the correct shape. Postgres creates a composite row type plus an array over it for every relation, so typcategory = 'A' was making the map scale with catalog size instead of with types in use. The NOT EXISTS carve-out on relkind <> 'c' correctly keeps what the driver actually needs — _text (1009), _int4 (1007) that #11149 relies on, enums and enum arrays, extension types, and arrays over a standalone CREATE TYPE ... AS (...) (relkind = 'c') — while dropping the per-relation noise. The rewrite to an aliased pg_type t is mechanically correct, and typrelid is always non-zero for composite element types so the pg_class join is safe. Verification numbers in the description (3317 → 108 on postgres:16, 24 → 24 on CrateDB) match what I'd expect. MaterializeDriver and RedshiftDriver override loadUserDefinedTypes, so the only other inheritor of this query is CrateDriver, which the description covers.

Findings

This is a synchronize re-run on an unchanged tree (7a9fc13, same blob SHAs). All four threads I filed earlier are still unresolved and still applicable at the same lines, so I did not post duplicates — re-affirming them here instead:

Severity Location Concern
Medium PostgresDriver.ts:331-334 The O(n²) reduce ({ [oid]: name, ...prev }) — the thing the commit message names as blocking the event loop for minutes — is untouched. Cutting rows 63k → 116 hides it for this deployment, but typcategory in ('U','E') is still unbounded (enums per tenant schema), so the same curve returns. One-line fix; worth doing in the same PR.
Low PostgresDriver.ts:303-306 Comment typo "NON EXIST" → NOT EXISTS, and it explains what is filtered but not why it's safe or why relkind <> 'c' is the carve-out. The commit message's rationale belongs in the code.
Low PostgresDriver.ts:327 Accepted-trade-off worth stating: a relation row-type array (array_agg(t), or a column declared my_table[], reachable via a user-authored model sql:) used to map to text and now throws Unable to detect type. That's "throws" vs. the commit message's typcategory = 'C' comparison, which was "never mapped". A lazy per-oid lookup on miss would keep the win without the cliff.
Low PostgresDriver.test.ts:196 The new test pins the half that's kept (composite array + domain) but nothing observes that relation row-type arrays are now excluded — widening the filter back would pass silently and lose the perf fix. Also _text/_int4 aren't asserted despite #11149 depending on them. Nit: the created type/domain leak into the shared container.

Security: nothing relevant — no user input reaches this SQL, it's a static catalog query. Docs: not required for an internal driver change.

Not done

I did not run the driver test suite — it needs Docker/testcontainers (PostgresDBRunner.startContainer), which isn't available in this job. The stream (user defined type) assertions look correct by inspection but are unverified here.

• branch `postgres-loaduserdefinedtypes-profiling`

//
// Postgres creates a row type for every relation and an array type over it, so
// selecting all of typcategory = 'A' returns one row per relation in the database.
// That's why there is a NON EXIST filter.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo — "NON EXIST" should be NOT EXISTS, and the comment explains what is filtered but not the part a future reader will actually stumble on: why it is safe to drop those oids (relation row-type arrays only appear as a column type for whole-row aggregates, which this driver does not issue) and why relkind <> 'c' is the carve-out (it keeps standalone CREATE TYPE ... AS (...)). Suggest folding the commit-message rationale in here:

Suggested change
// That's why there is a NON EXIST filter.
// Postgres creates a row type for every relation and an array type over it, so
// selecting all of typcategory = 'A' returns one row per relation in the database,
// which does not scale on deployments with many schemas/tables. The NOT EXISTS
// below drops arrays over relation row types: they can only be the type of a
// column for whole-row aggregates, which this driver never issues. Arrays over a
// standalone CREATE TYPE ... AS (...) have relkind = 'c' and are kept.

@claude

claude Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 1s —— View job


Review: approach is sound — 0 blocking, 3 low. Correction: my earlier "medium" (O(n²) map build) was wrong and I've resolved it.

Full review — click to expand

Todos

  • Gather context (diff vs origin/master, PostgresDriver.ts, test file, subclasses)
  • Classify request → code review
  • Audit existing threads for staleness / duplicates
  • Analyze SQL correctness, perf, tests, security
  • Post review

Verdict

Synchronize re-run on an unchanged tree (69ab7c8, same blob SHAs as the tree I reviewed at 7a9fc13 — only the commit was rewritten). The change itself is correct and the right shape.

Postgres creates a composite row type plus an array over it for every relation, so typcategory = 'A' made the map scale with catalog size rather than with types in use. The NOT EXISTS carve-out is precise: t.typelem → element type, e.typtype = 'c' → composite, c.relkind <> 'c' → that row type belongs to a real relation rather than a standalone CREATE TYPE ... AS (...). So it drops exactly the auto-generated per-relation array types and keeps _text (1009) / _int4 (1007) that #11149 depends on, enums, enum arrays, extension types, and arrays over standalone composites. The JOIN pg_class can't over-filter, since typtype = 'c' always implies non-zero typrelid. The correlated subquery is oid-index-driven, so the query doesn't get slower. MaterializeDriver and RedshiftDriver override loadUserDefinedTypes; the only other inheritor is CrateDriver, which the description covers (24 rows both ways on 5.10).

Security: nothing relevant — static catalog SQL, no interpolation, no user input. Docs: not required for an internal driver change.

Correction to my earlier review

I previously filed a Medium claiming the reduce((prev, cur) => ({...prev})) map build was untouched. That code no longer exists — 4e8dd9b (already on master) replaced it with a linear for loop, and PostgresDriver.ts:331-337 is that loop. The finding was invalid; I've resolved that thread.

Findings — all three previously filed, still unresolved, still applicable at the same lines, so no duplicates posted

Severity Location Concern
Low PostgresDriver.ts:306 Comment typo "NON EXIST" → NOT EXISTS; the comment says what is filtered but not why it's safe or why relkind <> 'c' is the carve-out. The commit message's rationale belongs in the code.
Low PostgresDriver.ts:327 Accepted trade-off worth stating: a relation row-type array (array_agg(t), a my_table[] column, reachable via a user-authored model sql:) used to map to text and now throws Unable to detect type. A lazy per-oid lookup on miss would keep the win without the cliff.
Low PostgresDriver.test.ts:196 The test pins the half that's kept (composite array + domain) but nothing observes that relation row-type arrays are now excluded — widening the filter back would pass silently and lose the fix. _text/_int4 also aren't asserted despite #11149 depending on them. Nit: the created type/domain leak into the shared container.

Not run

I did not run the driver suite — it needs Docker/testcontainers (PostgresDBRunner.startContainer), unavailable in this job. Correctness claims above are from reading catalog semantics; the row-count and CrateDB numbers in the description are unverified by me.

• branch `postgres-loaduserdefinedtypes-profiling`

…fined types

#11149 needed array-typed columns to map to `text`, and selected all of
`typcategory = 'A'` to get there. Postgres creates a row type and an array
over it for every relation, so that selects one row per relation in the
database: the map stopped scaling with the types in use and started scaling
with the size of the catalog. On a multi tenant deployment with a schema per
tenant this reached ~63k rows, and the map build behind it is quadratic.

Those relation array types are only ever the type of a column for queries
that aggregate whole rows, which this driver does not issue, and a plain
composite column is already unsupported since `typcategory = 'C'` has never
been loaded. Arrays over a standalone `CREATE TYPE ... AS (...)` are kept,
they are real user defined types.

Measured on postgres:16 with 150 schemas of 20 tables, 3209 relations:

| query                | rows |
| -------------------- | ---- |
| typcategory in UEA   | 3317 |
| this one             |  108 |

The oids #11149 relies on are unaffected: `_text` 1009 and `_int4` 1007 are
still loaded, as are enums, enum arrays and extension types such as hll.
CrateDB, which inherits this through CrateDriver, returns the same 24 rows
for both queries and supports the correlated NOT EXISTS.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@ovr
ovr force-pushed the postgres-loaduserdefinedtypes-profiling branch from 69ab7c8 to bc6446c Compare August 18, 2026 12:56
@claude

claude Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 43s —— View job


Review: approach is sound — 0 blocking, 2 low (both already-filed threads, no duplicates posted)

Full review — click to expand

Todos

  • Gather context (diff vs origin/master, PostgresDriver.ts, test file, subclasses)
  • Classify request → code review
  • Audit existing threads for staleness / duplicates
  • Analyze SQL correctness, perf, tests, security
  • Post review

Verdict

Synchronize re-run. Tree is functionally identical to what I reviewed at 69ab7c8/7a9fc13; the only content change since is the code comment wording (NON EXIST → NOT EXIST). The change itself remains correct and the right shape.

Postgres creates a composite row type plus an array over it for every relation, so typcategory = 'A' made the map scale with catalog size rather than with types in use. The NOT EXISTS carve-out is precise: t.typelem → element type, e.typtype = 'c' → composite, c.relkind <> 'c' → the row type belongs to a real relation rather than a standalone CREATE TYPE ... AS (...). It drops exactly the auto-generated per-relation array types and keeps _text (1009) / _int4 (1007) that #11149 depends on, enums, enum arrays, extension types, and arrays over standalone composites. The JOIN pg_class can't over-filter, since typtype = 'c' always implies non-zero typrelid. The correlated subquery is oid-index-driven, so the query itself doesn't get slower.

The map build at PostgresDriver.ts:331-337 is the linear for loop from 4e8dd9b (already on master) — I filed a Medium against a quadratic reduce in an earlier run; that was wrong, and I resolved that thread. No new perf concern here.

MaterializeDriver and RedshiftDriver override loadUserDefinedTypes, so the only other inheritor of this query is CrateDriver, which the description covers (24 rows both ways on 5.10).

Security: nothing relevant — static catalog SQL, no interpolation, no user input. Docs: not required for an internal driver change.

Findings — both previously filed and still unresolved, so re-affirming rather than duplicating

Severity Location Concern
Low PostgresDriver.ts:306 Comment still reads NOT EXIST (SQL keyword is NOT EXISTS), and it explains what is filtered but not why it's safe or why relkind <> 'c' is the carve-out. The commit message's rationale belongs in the code. Thread is marked outdated by GitHub since the line moved, but the substance stands.
Low PostgresDriver.ts:327 Accepted trade-off worth stating in the comment: a relation row-type array (array_agg(t), a my_table[] column, reachable via a user-authored model sql:) used to map to text and now throws Unable to detect type. A lazy per-oid lookup on miss would keep the win without the cliff.

The test-coverage thread I filed earlier (nothing observes that relation row-type arrays are now excluded; _text/_int4 not asserted) has been resolved on the PR, so I'm not re-raising it.

Not run

I did not run the driver suite — it needs Docker/testcontainers (PostgresDBRunner.startContainer), unavailable in this job. Correctness claims above are from reading catalog semantics; the row-count and CrateDB numbers in the description are unverified by me.

• branch `postgres-loaduserdefinedtypes-profiling`

@ovr
ovr merged commit 4547e08 into master Aug 18, 2026
16 checks passed
@ovr
ovr deleted the postgres-loaduserdefinedtypes-profiling branch August 18, 2026 13:00
@codecov

codecov Bot commented Aug 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.15%. Comparing base (6088edf) to head (bc6446c).
⚠️ Report is 4 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (6088edf) and HEAD (bc6446c). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (6088edf) HEAD (bc6446c)
cubesql 1 0
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #11587       +/-   ##
===========================================
- Coverage   84.06%   59.15%   -24.91%     
===========================================
  Files         257      227       -30     
  Lines       81582    18157    -63425     
  Branches        0     3672     +3672     
===========================================
- Hits        68581    10741    -57840     
+ Misses      13001     6868     -6133     
- Partials        0      548      +548     
Flag Coverage Δ
cube-backend 59.15% <ø> (?)
cubesql ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

ovr added a commit that referenced this pull request Aug 18, 2026
…fined types (#11587)

#11149 needed array-typed columns to map to `text`, and selected all of
`typcategory = 'A'` to get there. Postgres creates a row type and an array
over it for every relation, so that selects one row per relation in the
database: the map stopped scaling with the types in use and started scaling
with the size of the catalog.

Those relation array types are only ever the type of a column for queries
that aggregate whole rows, which this driver does not issue, and a plain
composite column is already unsupported since `typcategory = 'C'` has never
been loaded. Arrays over a standalone `CREATE TYPE ... AS (...)` are kept,
they are real user defined types.

Measured on postgres:16 with 150 schemas of 20 tables, 3209 relations:

| query                | rows |
| -------------------- | ---- |
| typcategory in UEA   | 3317 |
| this one             |  108 |

This branch was successfully deployed

1 active deployment
Preview — bc6446c7 Deployed Aug 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data source driver driver:postgres Issues relating to the Postgres driver javascript Pull requests that update Javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

⌂ Proxy