Skip to content

perf(postgres-driver): build user defined types map in linear time - #11586

Merged
ovr merged 1 commit into
masterfrom
pretoria
Aug 18, 2026
Merged

ovr merged 1 commit into
masterfrom
pretoria

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

loadUserDefinedTypes built its oid -> typname map with a reduce that spread the accumulator on every row, copying the whole map n times — quadratic and fully synchronous, so it blocks the event loop. This went unnoticed while the query only selected typcategory in ('U', 'E') (~20 rows on a stock Postgres), but #11149 added 'A' so that array-typed columns get mapped, and Postgres auto-creates an array type for every relation, so the row count now scales with the number of tables in the database rather than with the number of actual user defined types. This replaces the spread-reduce with an in-place loop.

Measured on postgres:16, SELECT count(*) FROM pg_type WHERE typcategory in ('U', 'E', 'A'):

tables in database rows spread reduce in-place loop
0 313 6.3 ms 0.12 ms
5000 5313 2355 ms 0.45 ms
~20000 - 35116 ms 1.10 ms

`loadUserDefinedTypes` built its oid -> typname map with a reduce that
spread the accumulator on every row, copying the whole map n times. That
is quadratic and fully synchronous, so it blocks the event loop.

This went unnoticed while the query only selected `typcategory in ('U', 'E')`
(~20 rows on a stock Postgres). #11149 added `'A'` so that array-typed
columns get mapped, and Postgres auto-creates an array type for every
relation — the row count now scales with the number of tables in the
database, not with the number of actual user defined types.

Measured on postgres:16, `SELECT count(*) FROM pg_type WHERE typcategory
in ('U', 'E', 'A')`:

| tables in database | rows | spread reduce | in-place loop |
| ------------------ | ---- | ------------- | ------------- |
| 0                  |  313 |        6.3 ms |       0.12 ms |
| 5000               | 5313 |       2355 ms |       0.45 ms |
| ~20000             |   -  |      35116 ms |       1.10 ms |

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@ovr
ovr requested a review from a team as a code owner August 18, 2026 12:01
@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 55s —— View job


Review: correct and behavior-preserving — 0 blocking, 2 low (non-blocking, pre-existing)

Full review
  • Gather context (diff vs origin/master, surrounding PostgresDriver code)
  • Verify behavior equivalence of the rewrite
  • Check performance claim
  • Look for related issues (tests, docs, concurrency)
  • Post review

Verdict

The change is correct and the reasoning in the description holds. packages/cubejs-postgres-driver/src/PostgresDriver.ts:318-324 replaces an O(n²) spread-reduce with a single in-place pass. Nice catch on the interaction with #11149 — adding typcategory = 'A' is exactly what turns this from "20 rows, invisible" into "one row per relation, tens of seconds of blocked event loop".

Behavior equivalence — worth stating explicitly since the rewrite flips duplicate-key precedence:

  • Old: { [current.oid]: ..., ...prev } spreads prev last, so on a duplicate oid the earliest row wins.
  • New: the loop overwrites, so the last row wins.

This is a no-op in practice because pg_type.oid is the table's primary key, so SELECT oid ... FROM pg_type can never return a duplicate. No functional change. ✅

Also verified the consumer is unaffected: getTypeParser-style lookup at PostgresDriver.ts:270-271 uses dataTypeID in this.userDefinedTypes, and numeric row.oid still coerces to the same string key as before.

Non-blocking observations

1. The map still scales with table count (PostgresDriver.ts:303-316) — low

This PR fixes the quadratic build, but the underlying query still returns one array type per relation, so on a ~20k-table database you retain a ~20k-entry map per driver instance and transfer those rows on first connect. That's now milliseconds and a few MB rather than 35 s, so it's fine — but if this ever needs tightening, narrowing the 'A' branch (e.g. only array types whose element type is itself a user-defined type) would attack the row count rather than the loop. Explicitly not suggesting a typnamespace <> 'pg_catalog'::regnamespace filter: the 'U' category legitimately needs pg_catalog entries (uuid, json, jsonb, bytea, …), so that would be a behavior change.

2. Concurrent first-connect does redundant work — low, pre-existing

loadUserDefinedTypes guards on if (!this.userDefinedTypes) (PostgresDriver.ts:296) but sets the field only after the await. Several connections opening simultaneously on a cold pool can each run the pg_type query and each build the map. Harmless (idempotent, last write wins) and it predates this PR — but it was a multiplier on the old quadratic cost, and caching the in-flight promise instead of the result would close it. Out of scope here.

Testing / docs

  • No test added. The check list acknowledges this, and I'd agree a unit test isn't very valuable for a mechanical loop rewrite — asserting "the map is built in linear time" is a benchmark, not a test. If you want cheap coverage, a test that stubs conn.query with a few rows and asserts the resulting userDefinedTypes map would at least lock in the oid → typname mapping (including the 'E' → varchar / 'A' → text CASE contract) against future refactors of this function. Optional.
  • No docs needed — internal, no API or config surface change.

Nothing else to flag. LGTM.

• branch [`pretoria`](https://github.com/cube-js/cube/tree/pretoria)

@ovr
ovr merged commit 4e8dd9b into master Aug 18, 2026
24 checks passed
@ovr
ovr deleted the pretoria branch August 18, 2026 12:15
ovr added a commit that referenced this pull request Aug 18, 2026
…11586)

`loadUserDefinedTypes` built its oid -> typname map with a reduce that
spread the accumulator on every row, copying the whole map n times. That
is quadratic and fully synchronous, so it blocks the event loop.

This went unnoticed while the query only selected `typcategory in ('U', 'E')`
(~20 rows on a stock Postgres). #11149 added `'A'` so that array-typed
columns get mapped, and Postgres auto-creates an array type for every
relation — the row count now scales with the number of tables in the
database, not with the number of actual user defined types.

Measured on postgres:16, `SELECT count(*) FROM pg_type WHERE typcategory
in ('U', 'E', 'A')`:

| tables in database | rows | spread reduce | in-place loop |
| ------------------ | ---- | ------------- | ------------- |
| 0                  |  313 |        6.3 ms |       0.12 ms |
| 5000               | 5313 |       2355 ms |       0.45 ms |
| ~20000             |   -  |      35116 ms |       1.10 ms |

This branch was successfully deployed

1 active deployment
Preview — 28d2934f 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