Skip to content

fix(db,firewall): validate pooled connections + raise IP cache TTL - #679

Merged
Soju06 merged 1 commit into
mainfrom
fix/db-pool-pre-ping-firewall-cache-ttl
May 17, 2026
Merged

Soju06 merged 1 commit into
mainfrom
fix/db-pool-pre-ping-firewall-cache-ttl

Conversation

@Soju06

@Soju06 Soju06 commented May 17, 2026

Copy link
Copy Markdown
Owner

Why

After the 1.18.0 production deploy a steady stream of HTTP 500s appeared on /v1/chat/completions roughly 17 minutes after container restart (~4.4% of traffic in a 25-minute window). The underlying error:

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 bug: SQLAlchemy QueuePool exhaustion in codex-lb #672 reports.

What Changes

  • app/db/session.py::_postgres_async_engine_kwargs now sets pool_pre_ping=True and pool_recycle=settings.database_pool_recycle_seconds (default 1800 seconds) 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 the existing configure-background-db-pool change.
  • SessionLocal() non-async-with pattern in _ensure_bridge_durable_schema_ready (app/main.py:410) — the existing try/finally already closes the session and the call is startup-only.
  • Default pool size / max-overflow tuning. Defaults remain 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 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).
  • uvx ruff check . clean
  • uvx ruff format --check . clean
  • uv run ty check clean

Fixes #672

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
@Soju06

Soju06 commented May 17, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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
Soju06 merged commit f46a5de into main May 17, 2026
18 checks passed
@Soju06
Soju06 deleted the fix/db-pool-pre-ping-firewall-cache-ttl branch May 17, 2026 11:37
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]>
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]>
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.

bug: SQLAlchemy QueuePool exhaustion in codex-lb

1 participant