Repository navigation
fix(lakebase): recycle pool connections and pass through dropped pool options - #719
billmcmillin wants to merge 10 commits into
Conversation
… options getLakebasePgConfig() built the pg.Pool config from a fixed list of 11 keys, so maxLifetimeSeconds, application_name, keepAlive, query_timeout and options were silently dropped. Without a lifetime, pool connections were never recycled. Access granted through Unity Catalog claims in a Lakebase OAuth token stops working 4 hours after the token is minted while the connection stays open, so a busy pool kept failing with "permission denied" until the app restarted. - Pass the five options through to pg.Pool, keeping the explicit key list. - Default maxLifetimeSeconds to 1800 (30 minutes); an explicit 0 is kept. - Warn when maxLifetimeSeconds is 0 or above 9000 (2.5 hours): the 4-hour lapse, less up to an hour of token age at login, less a 30-minute margin. - Ignore a negative or non-finite maxLifetimeSeconds, with a warning, and use the default. pg-pool would otherwise close every connection as soon as it opens (negative) or never recycle (NaN). - Document maxLifetimeSeconds, including that held clients are only recycled on release, and regenerate the API docs. - Add unit tests for the default, the warnings and the pass-through. - Add tools/lakebase-soak.ts, a soak harness that runs a real pool against a sandbox endpoint and checks connection age, token age at login, application_name and table access. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Bill McMillin <bill.mcmillin@databricks.com>
calvarjorge
left a comment
There was a problem hiding this comment.
Thanks Bill, this looks good. The pass-through and the 30-minute default fix the issue, and the tests, lint, build and typecheck all pass locally. Two small comments inline; neither blocks the merge.
pg-pool passes maxLifetimeSeconds * 1000 to setTimeout. Above 2^31 - 1 ms (about 24.8 days), Node fires the timer after 1 ms, so every connection closed after a single use. Treat those values like Infinity: warn and use the default. Compare in milliseconds so 2147483 s is kept and fractional values just past the limit are rejected. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Bill McMillin <bill.mcmillin@databricks.com>
|
@calvarjorge @pkosiec - any preference on keeping this and #731 separate? I can combine them if that would simplify things. |
|
@calvarjorge @pkosiec Thanks for approving and re-running this. CI fails at Could a maintainer repush #731 (the ORM follow-up for #730) is stacked on this PR and will need the same once it's reviewed. |
calvarjorge
left a comment
There was a problem hiding this comment.
The library fix looks right. The harness has a few pass/fail bugs (inline); fine to fix them or move it to its own PR, as you offered.
| } | ||
| : {}), | ||
| }; | ||
| const passed = Object.values(checks).every(Boolean); |
There was a problem hiding this comment.
A run stopped with Ctrl-C still passes: passed ignores stopRequested.
There was a problem hiding this comment.
Good catch, fixed in 679268d: a stopped run now fails through a new ran_full_duration check, so the summary shows why
| run_crossed_token_boundary: durationH * 60 > TOKEN_BOUNDARY_MINUTES, | ||
| no_auth_errors: authErrors === 0, | ||
| no_query_errors: queriesFailed === 0, | ||
| connections_recycled: |
There was a problem hiding this comment.
This passes when the run is shorter than the lifetime, e.g. --lifetime-seconds 9000 --minutes 75; also require maxAge ≥ lifetime − interval?
There was a problem hiding this comment.
fixed in a351fe2: connections_recycled now also requires the oldest pool connection to reach the lifetime, less one interval and the probe slack. Checked live on a fresh Lakebase project:
--lifetime-seconds 1800 --minutes 3: oldest connection 149 s, soconnections_recyclednow fails.--lifetime-seconds 60 --minutes 4: 5 connections, each replaced at 60 s, so it passes.
Replayed against my earlier saved runs, it only changes the result for three short smoke runs that never reached the lifetime. The 260-minute runs still pass.
Testing the Ctrl-C fix live, I found it didn't work through the documented pnpm exec tsx command. One Ctrl-C reaches the harness as a SIGINT from the terminal, a SIGTERM from pnpm 1 ms later and a SIGINT relayed by tsx 30 ms after that. With no SIGTERM handler, the harness died before writing a summary, so ran_full_duration never ran.
0754e2a treats SIGTERM like SIGINT, and signals within a second of the first as the same stop request. A later Ctrl-C still quits immediately. A terminal-style Ctrl-C to the process group now writes the summary (incomplete: true, ran_full_duration: false, exit 1) under pnpm exec tsx, tsx and node --import tsx.
|
|
||
| // ── Pool under test ────────────────────────────────────────────────── | ||
|
|
||
| const pool: Pool = createLakebasePool({ |
There was a problem hiding this comment.
Without query_timeout/keepAlive, a query on a dead socket can hang the run with no summary.
There was a problem hiding this comment.
Fixed in 75ddc1a: the harness now sets query_timeout (one interval) and keepAlive (with a 10 s initial delay). Live test with every probe read blocked by an ACCESS EXCLUSIVE lock held for 4 minutes: a 2-minute run used to take 261 s and record no errors; now it ends on time at 122 s, records Query read timeout and fails.
| `connections=${pool.totalCount} connects=${connects} mints=${mints} ` + | ||
| `ok=${queriesOk} failed=${queriesFailed} auth_errors=${authErrors}`, | ||
| ); | ||
| const nextTickAt = startedAt + (tick + 1) * INTERVAL_MS; |
There was a problem hiding this comment.
After a sleep this fires all the missed ticks back to back; schedule from Date.now()?
There was a problem hiding this comment.
Fixed in 3df0c07. Instead of Date.now() + interval, it schedules the next point on the interval grid that's still ahead. That skips missed ticks the same way, but doesn't drift by each tick's own duration. Live test, freezing the harness for 45 s with 10 s ticks: before, the missed ticks ran 1 s apart (72, 73, 74, 75 s); now the next tick comes 10 s after resuming (81 s) and stays on the grid.
The soak harness recorded a Ctrl-C stop as `incomplete` but left it out of `passed`, so a run stopped after the one-hour token boundary still passed and exited 0. Add a `ran_full_duration` check so a stopped run always fails and the summary shows why. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Bill McMillin <bill.mcmillin@databricks.com>
`connections_recycled` only checked that no pool connection outlived the lifetime, so a run shorter than the lifetime passed without seeing any connection recycled. Also require the oldest connection to reach the lifetime, less one interval and the probe slack. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Bill McMillin <bill.mcmillin@databricks.com>
… exec Under `pnpm exec tsx`, one Ctrl-C reaches the harness as a SIGINT from the terminal, a SIGTERM from pnpm 1 ms later and a SIGINT relayed by tsx 30 ms after that. The harness had no SIGTERM handler, so pnpm's SIGTERM killed it before it wrote a summary, and `ran_full_duration` never ran. Treat SIGTERM like SIGINT, and signals within a second of the first as the same stop request; only a later signal quits immediately. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Bill McMillin <bill.mcmillin@databricks.com>
A query on a dead socket never settles, so the harness never finished or wrote a summary. Set `query_timeout` to one interval (at least the probe's sleep plus 10 s), so a stuck query fails the run as a query error instead. Also enable TCP keep-alive with a 10 s initial delay, since the OS default waits 2 hours before its first probe. The timeout is recorded in the start event. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Bill McMillin <bill.mcmillin@databricks.com>
… back Ticks were scheduled from the start time, so after a sleep or a slow tick every missed tick ran immediately, one after another. Schedule the next tick at the next point on the interval grid that's still ahead: missed ticks are skipped, and normal ticks stay on the grid instead of drifting by each tick's own duration. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Bill McMillin <bill.mcmillin@databricks.com>
|
Update to my CI request above: the head is now |
Fixes #718.
Summary
createLakebasePool()drops mostpgpool options, includingmaxLifetimeSeconds, so pool connections are never recycled. Access granted through Unity Catalog claims in a Lakebase OAuth token stops working 4 hours after the token is minted, while the connection stays open. A busy pool keeps its connections past that point, and from then on every query that relies on that access fails with42501 permission denied, until the app restarts.This PR passes the dropped options through and recycles connections every 30 minutes by default.
Root cause
getLakebasePgConfig()builds thepg.Poolconfig from a fixed list of 11 keys:LakebasePoolConfigextendspg'sPoolConfig, so any other option type-checks and is then silently dropped. Two of the consequences:maxLifetimeSecondsis always pg-pool's default of 0 (never recycle). In a live soak onmain, pool connections were 4.3 hours old by the end of the run.application_name,keepAlive,query_timeoutandoptionsnever reach the server. Onmain, every soak connection reported an emptyapplication_name.Lakebase checks the token only at login, so connections on native Postgres grants keep working however old they get. Claims access doesn't: on
main, it lapsed 240.5 minutes after the token was minted, on every connection, while liveness queries on the same connections kept succeeding.Changes
packages/lakebase/src/pool-config.ts(the fix)maxLifetimeSeconds,application_name,keepAlive,query_timeoutandoptionsthrough topg.Pool.workspaceClient,endpoint,loggerandtelemetry, which must not reachpg. Andhost,maxand the other pool options are normalised byparsePoolConfig()first, which a spread could overwrite. The cost is that the nextpgoption a caller needs has to be added to the list too.maxLifetimeSecondsto 1800 (30 minutes). The default only has to be well under the safe limit below. Recycling is cheap: a recycled connection logs in again with the cached token, so it doesn't mint a new one. The value is resolved with??, so an explicit0(never recycle) is still honoured.resolveMaxLifetimeSeconds()logs a warning when the lifetime is0, or above 9000 seconds (2.5 hours), and returns it unchanged; it doesn't cap. The limit is the 4-hour lapse, less up to an hour of token age at login (Lakebase rejects expired tokens, so a token is at most an hour old when a connection opens), less a 30-minute margin for a client held past its lifetime, login time and clock skew.maxLifetimeSecondslogs a warning and falls back to the default. Otherwise pg-pool would close every connection as soon as it opens (negative), or never recycle (NaN, which it turns into 0). Before this PR the value was dropped, so apps passing one work today. That's why this warns rather than throws.packages/lakebase/src/types.tsmaxLifetimeSecondsonLakebasePoolConfig. It's inherited fromPoolConfig; it's redeclared only to carry the docs.docs/docs/api/appkit/Interface.LakebasePoolConfig.mdpnpm docs:buildfrom the doc comment above.packages/lakebase/src/__tests__/connection-lifetime.test.ts(new)createLakebasePool()and a static password, then readspool.optionsto see what reachedpg.Pool. Construction is lazy, so no connection is opened and no credentials are requested.PG*,LAKEBASE_ENDPOINTandDATABRICKS_CLIENT_IDenvironment variables before each test, so a developer's shell can't change the results.packages/lakebase/src/__tests__/pool-timeouts.test.tstest.eachblock checks each of the five options reachespool.options. It follows the pattern of the timeout test already in this file.tools/lakebase-soak.ts(new, not published, not run in CI)application_nameand table access. It imports the package from source, so the same command comparesmainwith a branch.application_name, and optionally reads a probe table. Slots are added on a ramp, so connections open throughout a token's life. It disables the idle timeout, so connections live long enough to test recycling, and it holds one connection checked out for the whole run, to show the held-client limit.events.jsonlandsummary.json, and exits 0 only if every check passes:application_nameis on every connection;--claims-tablemints tokens with READ_ONLY claims for a UC table.--ttl-secondsmints shorter-lived claims tokens.--probe-tablenames the table to read.tools/.token-refresh.tsis unchanged, so the pool's token mint rate doesn't change.Testing
New tests in
connection-lifetime.test.ts, plus a pass-through block inpool-timeouts.test.tsthat follows that file's existing pattern. 11 of the 12 fail onmainand pass with the fix:main0is kept and warnsNaNor infinite value uses the default and warnsapplication_name,keepAlive,query_timeout,options,maxLifetimeSecondsreachpool.optionspnpm testpasses apart from onemock-workspace-clienttest that already fails onmain.pnpm build,pnpm docs:build,pnpm checkandpnpm -r typecheckpass.Live 260-minute soaks on a sandbox Lakebase Autoscaling project (1 CU), as a service principal whose only access to the probe table comes through Unity Catalog, with tokens that request READ_ONLY claims for it:
mainapplication_name42501from minute 240.5, on every connection42501from minute 240.542501from minute 240.5, as documentedThe lapse isn't tied to the token's expiry. With one-hour tokens, reads kept working for 15 minutes past expiry, and with 5-minute tokens for 29 minutes, so there's no shorter way to test it than a run of more than 4 hours.
Notes
query_timeoutandkeepAlive, now take effect where they were ignored before.maxLifetimeSeconds.@databricks/lakebaselogs only errors by default, so there they appear only when a logger withwarnis configured. Each pool warns once when it's created, so AppKit's per-user pools repeat the warning per user.getLakebaseOrmConfig()now includesmaxLifetimeSeconds. Whether TypeORM and Sequelize pass it to their own pools hasn't been checked.createLakebasePoolcan't request Unity Catalog claims today. This fix is a prerequisite for adding that, but the feature itself is separate.This pull request and its description were written by Isaac.