Repository navigation
fix(db,firewall): validate pooled connections + raise IP cache TTL - #679
Merged
Merged
Conversation
After the 1.18.0 production deploy a steady stream of HTTP 500s appeared
on /v1/chat/completions roughly 17 minutes after container restart:
sqlalchemy.dialects.postgresql.asyncpg.InterfaceError:
<class 'asyncpg.exceptions._base.InterfaceError'>: connection is closed
[SQL: SELECT sticky_sessions.key, sticky_sessions.kind, ...
FROM sticky_sessions WHERE sticky_sessions.key = $1 AND ...]
This is the same class of pool-health issue documented in #672. Two
independent contributors:
1. The async engines did not configure pool_pre_ping or pool_recycle, so
the pool happily handed out connections that the PostgreSQL server had
already silently dropped (idle timeout, restart, network reset). The
first real query on such a connection raises InterfaceError. Container
restart freshens the whole pool together, which is exactly when the
stale-connection race surfaces most visibly.
2. FirewallIPCache(ttl_seconds=2) was effectively no cache at all — every
request to /v1/* and /backend-api/codex/* re-opened a DB session to
re-check the firewall allowlist. That request-rate multiplier is the
dominant source of the QueuePool churn that #672 reports.
Changes
-------
- app/db/session.py::_postgres_async_engine_kwargs now sets
pool_pre_ping=True
pool_recycle=settings.database_pool_recycle_seconds (default 1800s)
on both the main and background engines. SQLite paths and the
CODEX_LB_TEST_DATABASE_URL NullPool path are untouched.
- app/core/middleware/firewall_cache.py raises the default TTL from
2 seconds to 30 seconds, and resolves the value lazily from
settings.firewall_ip_cache_ttl_seconds on first cache construction.
Explicit invalidation hooks (POST/DELETE /api/firewall/ips,
cache_poller invalidation channel) are unchanged.
- app/core/config/settings.py adds two new knobs:
database_pool_recycle_seconds (default 1800, env
CODEX_LB_DATABASE_POOL_RECYCLE_SECONDS)
firewall_ip_cache_ttl_seconds (default 30, env
CODEX_LB_FIREWALL_IP_CACHE_TTL_SECONDS)
Out of scope
------------
- Background pool sizing — handled by configure-background-db-pool.
- SessionLocal() non-async-with in _ensure_bridge_durable_schema_ready —
the existing try/finally already closes the session and the call is
startup-only.
OpenSpec
--------
Adds change folder
openspec/changes/hotfix-db-pool-pre-ping-and-firewall-cache-ttl/ with
proposal, tasks, and delta requirements under database-backends and
api-firewall. `openspec validate` passes.
Tests
-----
- tests/unit/test_db_session.py adds three regression tests covering the
kwargs invariant on PostgreSQL URLs (with default + custom recycle) and
the CODEX_LB_TEST_DATABASE_URL NullPool escape hatch.
- tests/unit/test_firewall_cache_ttl.py asserts the new default,
settings-driven overrides, and the validation that ttl_seconds > 0.
- Broader sweep: tests/unit/ + tests/integration/test_proxy_chat_completions.py
+ tests/integration/test_proxy_responses.py + tests/integration/test_migrations.py
→ 1697 passed, 6 skipped (PG-only / T21-obsolete).
Fixes #672
Owner
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Soju06
added a commit
that referenced
this pull request
May 17, 2026
Archive changes shipped in v1.18.0 and v1.18.1 per AGENTS.md "release 이후 archive" workflow. All 12 changes verified shipped in production at 10.0.0.113 (image 1.18.1, sha256:0431a474432d). 1.18.0 (9 changes): - deactivate-on-token-expired (#600) - drop-unknown-message-fields (#637) - mask-single-http-previous-response-miss (#516) - normalize-v1-responses-openai-sdk-stream (#639) - start-device-oauth-polling (#635) [delta header fixed: MODIFIED -> ADDED] - support-prolite-plan-capacity (#558) [delta header fixed: MODIFIED -> ADDED] - treat-upstream-overloaded-as-retryable (#601) - validate-password-length (#598) - validate-strict-function-tool-schema (#658) 1.18.1 (3 changes): - harden-long-codex-websocket-turns (#586) - suppress-duplicate-side-effect-tool-calls (#586) - hotfix-db-pool-pre-ping-and-firewall-cache-ttl (#679) Specs updated: 9 capabilities (admin-auth, api-firewall, chat-completions-compat, chat-completions-extensions, database-backends, frontend-architecture, responses-api-compat, usage-refresh-policy). openspec validate --specs: 19/19 passed. Co-authored-by: Hermes Agent <[email protected]>
6 tasks
vitalNohj
pushed a commit
to vitalNohj/codex-lb
that referenced
this pull request
Jul 17, 2026
…oju06#679) fix(db,firewall): validate pooled connections + raise IP cache TTL (Soju06#679) After the 1.18.0 production deploy a steady stream of HTTP 500s appeared on `/v1/chat/completions` ~17 minutes after container restart (~4.4% of traffic in a 25-minute window), all with: asyncpg.InterfaceError: connection is closed [SQL: SELECT sticky_sessions.key, ... FROM sticky_sessions WHERE ...] Two independent contributors, same class as Soju06#672: 1. PostgreSQL engines lacked pool_pre_ping / pool_recycle, so the pool handed out connections the server had silently dropped. Container restart freshens the whole pool together, which is exactly when the stale-connection race surfaces most visibly. 2. FirewallIPCache(ttl_seconds=2) was effectively no cache, multiplying pool churn under load and amplifying Soju06#672's QueuePool exhaustion. Changes: - _postgres_async_engine_kwargs sets pool_pre_ping=True and pool_recycle=database_pool_recycle_seconds (default 1800s) on main + background engines. SQLite/NullPool paths unchanged. - FirewallIPCache default TTL raised 2s → 30s, lazily resolved from firewall_ip_cache_ttl_seconds. Explicit invalidation hooks unchanged. - Settings: database_pool_recycle_seconds, firewall_ip_cache_ttl_seconds. OpenSpec change folder added under hotfix-db-pool-pre-ping-and-firewall-cache-ttl (proposal, tasks, delta requirements on database-backends and api-firewall). openspec validate passes. Tests: - tests/unit/test_db_session.py: 3 regression tests (PG kwargs invariant with default + custom recycle, NullPool escape hatch via CODEX_LB_TEST_DATABASE_URL). - tests/unit/test_firewall_cache_ttl.py: default TTL, settings override, invalid TTL rejection. - Broader sweep tests/unit + integration: 1697 passed, 6 PG-only/T21 skip. - ruff check + ruff format --check + uv run ty check: clean. - CI 18/18, mergeStateStatus CLEAN. Fixes Soju06#672
vitalNohj
pushed a commit
to vitalNohj/codex-lb
that referenced
this pull request
Jul 17, 2026
…u06#682) Archive changes shipped in v1.18.0 and v1.18.1 per AGENTS.md "release 이후 archive" workflow. All 12 changes verified shipped in production at 10.0.0.113 (image 1.18.1, sha256:0431a474432d). 1.18.0 (9 changes): - deactivate-on-token-expired (Soju06#600) - drop-unknown-message-fields (Soju06#637) - mask-single-http-previous-response-miss (Soju06#516) - normalize-v1-responses-openai-sdk-stream (Soju06#639) - start-device-oauth-polling (Soju06#635) [delta header fixed: MODIFIED -> ADDED] - support-prolite-plan-capacity (Soju06#558) [delta header fixed: MODIFIED -> ADDED] - treat-upstream-overloaded-as-retryable (Soju06#601) - validate-password-length (Soju06#598) - validate-strict-function-tool-schema (Soju06#658) 1.18.1 (3 changes): - harden-long-codex-websocket-turns (Soju06#586) - suppress-duplicate-side-effect-tool-calls (Soju06#586) - hotfix-db-pool-pre-ping-and-firewall-cache-ttl (Soju06#679) Specs updated: 9 capabilities (admin-auth, api-firewall, chat-completions-compat, chat-completions-extensions, database-backends, frontend-architecture, responses-api-compat, usage-refresh-policy). openspec validate --specs: 19/19 passed. Co-authored-by: Hermes Agent <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
After the 1.18.0 production deploy a steady stream of HTTP 500s appeared on
/v1/chat/completionsroughly 17 minutes after container restart (~4.4% of traffic in a 25-minute window). The underlying error:This is the same class of pool-health issue documented in #672. Two independent contributors:
The async engines did not configure
pool_pre_pingorpool_recycle, so the pool happily handed out connections that the PostgreSQL server had already silently dropped (idle timeout, restart, network reset). The first real query on such a connection raisesInterfaceError. Container restart freshens the whole pool together, which is exactly when the stale-connection race surfaces most visibly.FirewallIPCache(ttl_seconds=2)was effectively no cache at all — every request to/v1/*and/backend-api/codex/*re-opened a DB session to re-check the firewall allowlist. That request-rate multiplier is the dominant source of the QueuePool churn that bug: SQLAlchemy QueuePool exhaustion in codex-lb #672 reports.What Changes
app/db/session.py::_postgres_async_engine_kwargsnow setspool_pre_ping=Trueandpool_recycle=settings.database_pool_recycle_seconds(default1800seconds) on both the main and background engines. SQLite paths and theCODEX_LB_TEST_DATABASE_URLNullPool path are untouched.app/core/middleware/firewall_cache.pyraises the default TTL from 2 seconds to 30 seconds, and resolves the value lazily fromsettings.firewall_ip_cache_ttl_secondson first cache construction. Explicit invalidation hooks (POST/DELETE /api/firewall/ips,cache_pollerinvalidation channel) are unchanged.app/core/config/settings.pyadds two new knobs:database_pool_recycle_seconds(default1800, envCODEX_LB_DATABASE_POOL_RECYCLE_SECONDS)firewall_ip_cache_ttl_seconds(default30, envCODEX_LB_FIREWALL_IP_CACHE_TTL_SECONDS)Out of scope
configure-background-db-poolchange.SessionLocal()non-async-with pattern in_ensure_bridge_durable_schema_ready(app/main.py:410) — the existingtry/finallyalready closes the session and the call is startup-only.15/10; pre-ping + cache TTL is expected to remove the dominant source of pool churn we observed, after which existing burst capacity is enough.OpenSpec
Adds change folder
openspec/changes/hotfix-db-pool-pre-ping-and-firewall-cache-ttl/with proposal, tasks, and delta requirements underdatabase-backendsandapi-firewall.openspec validatepasses.Tests
tests/unit/test_db_session.pyadds three regression tests covering the kwargs invariant on PostgreSQL URLs (with default + custom recycle) and theCODEX_LB_TEST_DATABASE_URLNullPool escape hatch.tests/unit/test_firewall_cache_ttl.pyasserts the new default, settings-driven overrides, and the validation thatttl_seconds > 0.tests/unit/+tests/integration/test_proxy_chat_completions.py+tests/integration/test_proxy_responses.py+tests/integration/test_migrations.py→ 1697 passed, 6 skipped (PG-only / T21-obsolete).uvx ruff check .cleanuvx ruff format --check .cleanuv run ty checkcleanFixes #672