diff --git a/server/deploy/poorbird.env.example b/server/deploy/poorbird.env.example index cbcb244..5192d0b 100644 --- a/server/deploy/poorbird.env.example +++ b/server/deploy/poorbird.env.example @@ -13,6 +13,14 @@ # The literal CHANGE_ME below is rejected at startup, so you cannot copy this # file and forget to edit it. POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird +# +# Connection pool. The API and the worker are separate processes and each gets +# its own pool, so the most either can open is POOL_SIZE + MAX_OVERFLOW and the +# most both together can open is twice that -- keep it under PostgreSQL's +# max_connections (100 by default). The worker opens connections lazily and +# needs about three, so the size below is really sizing the API. +POORBIRD_DB_POOL_SIZE=15 +POORBIRD_DB_MAX_OVERFLOW=10 # --- http ------------------------------------------------------------------- # Bind to loopback only; Caddy is the only thing that talks to it. @@ -44,7 +52,9 @@ POORBIRD_ENROLL_SECRET= POORBIRD_RATE_LIMIT_ENABLED=true # --- worker ----------------------------------------------------------------- -POORBIRD_WORKER_POLL_INTERVAL_S=2 +# How long to wait after finding the queue empty. Does not delay a queue that +# already has work: the worker drains that without pausing. +POORBIRD_WORKER_POLL_INTERVAL_S=5 POORBIRD_JOB_MAX_ATTEMPTS=3 # --- logging ---------------------------------------------------------------- diff --git a/server/src/poorbird/config.py b/server/src/poorbird/config.py index ea17749..22bc18c 100644 --- a/server/src/poorbird/config.py +++ b/server/src/poorbird/config.py @@ -37,7 +37,14 @@ class Settings(BaseSettings): # reported by ``poorbird check`` and raised with a readable message by db.py, # rather than silently connecting to whatever happens to be on localhost. database_url: str = "" - db_pool_size: int = 5 + # FastAPI runs this app's ``def`` handlers in anyio's threadpool (40 threads + # by default), and each one holds a session for the whole request. A pool of + # 5 meant the 6th concurrent request waited on ``pool_timeout`` before it + # even reached the database (REVIEW ยง7). The real ceiling is + # pool_size + db_max_overflow, so both are named here rather than left to + # SQLAlchemy's invisible default of 10. + db_pool_size: int = 15 + db_max_overflow: int = 10 db_echo: bool = False # --- http ------------------------------------------------------------- @@ -72,8 +79,11 @@ class Settings(BaseSettings): rate_limit_enabled: bool = True # --- worker ----------------------------------------------------------- - worker_poll_interval_s: float = 2.0 - worker_batch_size: int = 1 + # Idle polling only: the loop drains a non-empty queue back to back without + # sleeping, so this is the delay before a *newly* enqueued job is noticed, + # not a per-job cost. 5s trades latency nobody can perceive on a bird camera + # for 12 idle queries a minute instead of 30. + worker_poll_interval_s: float = 5.0 job_max_attempts: int = 3 # --- logging ---------------------------------------------------------- diff --git a/server/src/poorbird/db.py b/server/src/poorbird/db.py index b1bb7a7..5b0cdaf 100644 --- a/server/src/poorbird/db.py +++ b/server/src/poorbird/db.py @@ -31,6 +31,11 @@ if not _settings.database_url_is_set: engine = create_engine( _settings.database_url, pool_size=_settings.db_pool_size, + max_overflow=_settings.db_max_overflow, + # Past pool_size + max_overflow a caller waits rather than failing. It has + # to be finite: without a timeout a pool leak presents as requests hanging + # forever instead of as an error naming the pool. + pool_timeout=30, pool_pre_ping=True, echo=_settings.db_echo, future=True, diff --git a/server/src/poorbird/worker/main.py b/server/src/poorbird/worker/main.py index 0a68662..2c1907e 100644 --- a/server/src/poorbird/worker/main.py +++ b/server/src/poorbird/worker/main.py @@ -101,6 +101,13 @@ def run() -> int: ) try: + # One job per claim, deliberately. The review suggested claiming in + # batches of 5, but this loop already runs jobs back to back without + # sleeping while the queue has work, so a batch would only save claim + # round-trips -- and it would cost crash safety. Claiming 5 marks all 5 + # 'running'; dying after the first leaves four locked by a process that + # no longer exists, invisible until requeue_stale gets to them up to 15 + # minutes later. Single claims keep exactly one job at risk. while not _stop.is_set(): try: with SessionLocal() as session: diff --git a/server/tests/test_config.py b/server/tests/test_config.py index 113a0cc..005abf4 100644 --- a/server/tests/test_config.py +++ b/server/tests/test_config.py @@ -1,6 +1,7 @@ from __future__ import annotations import pytest +from conftest import needs_db from pydantic import ValidationError from poorbird.config import Settings @@ -81,3 +82,49 @@ def test_placeholder_enroll_secret_is_rejected(monkeypatch): monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "CHANGE_ME") with pytest.raises(ValidationError, match="placeholder"): Settings(_env_file=None) + + +# --- REVIEW section 7: pool sizing ----------------------------------------- + + +@needs_db +def test_pool_settings_reach_the_engine(monkeypatch): + """A setting nothing reads is worse than no setting at all. + + worker_batch_size sat in Settings for a whole phase looking like it tuned + something while the worker claimed one job at a time regardless. So this + asserts against the pool an engine really built, rather than comparing a + literal with itself. + + The values have to differ from SQLAlchemy's own defaults (pool_size 5, + max_overflow 10) or the test cannot tell a wired setting from an ignored + one -- which is the entire failure it is here to catch. Hence 17 and 7, + and hence re-importing db.py rather than reading the module-level engine, + whose numbers happen to coincide with the library's. + """ + import importlib + import sys + + from poorbird.config import get_settings + + monkeypatch.setattr( + "poorbird.config.get_settings", + lambda: Settings( + _env_file=None, + database_url=get_settings().database_url, + db_pool_size=17, + db_max_overflow=7, + ), + ) + + sys.modules.pop("poorbird.db", None) + try: + db = importlib.import_module("poorbird.db") + assert db.engine.pool.size() == 17 + # No public accessor for this one, and leaving half the connection + # ceiling unverified is the worse trade. + assert db.engine.pool._max_overflow == 7 + finally: + # Drop the throwaway engine and let the next importer rebuild the real + # one. It never opened a connection: the pool fills lazily. + sys.modules.pop("poorbird.db", None)