The three performance settings the review flagged, one of which turned out not to exist in any meaningful sense. db_pool_size 5 -> 15, and max_overflow named explicitly. FastAPI runs this app's def handlers in anyio's threadpool - 40 threads by default - and each holds a session for the whole request, so a pool of 5 put the sixth concurrent request on pool_timeout before it reached the database. The real ceiling was never 5 either: it was 15, because SQLAlchemy quietly adds max_overflow=10. Leaving that invisible is the actual hazard, since an operator raising pool_size has no way to see what they are raising it from, so both halves are settings now and the arithmetic is written down next to PostgreSQL's max_connections in the env example. pool_timeout is pinned at 30s rather than inherited: it has to stay finite, or a pool leak presents as requests hanging forever instead of an error that names the pool. worker_poll_interval_s 2.0 -> 5.0. This only ever delays noticing a job enqueued into an empty queue - the loop drains a queue that has work back to back without sleeping - so it costs latency nobody can perceive on a bird camera and halves the idle queries, 30 a minute down to 12. worker_batch_size is removed rather than raised to 5. Nothing read it. It has sat in Settings since Phase 1 looking like it tuned something while the worker claimed one job at a time regardless, which is worse than no setting at all. Implementing it would also be a mistake here: claiming five jobs marks all five 'running', so dying after the first leaves four locked by a process that no longer exists and invisible until requeue_stale reaches them up to fifteen minutes later. Single claims keep exactly one job at risk, and batching would only have saved claim round-trips on a loopback connection that no thumbnail decode would notice. The reasoning is at the claim loop, where the next person will ask. The test asserts against a pool an engine really built, because comparing Settings to itself would pass no matter what db.py does. It has to use values that differ from SQLAlchemy's own defaults - hence 17 and 7 - which is the point mutation testing earned: with max_overflow unwired the first version of this test still passed, because the default it fell back to was 10 and the setting also said 10. Tests: 193 -> 194. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
131 lines
4.7 KiB
Python
131 lines
4.7 KiB
Python
from __future__ import annotations
|
|
|
|
import pytest
|
|
from conftest import needs_db
|
|
from pydantic import ValidationError
|
|
|
|
from poorbird.config import Settings
|
|
|
|
|
|
def test_every_setting_reads_from_the_environment(monkeypatch):
|
|
"""Phase 1.2: no path, host or secret may be baked into code."""
|
|
monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@10.0.0.5:5432/db")
|
|
monkeypatch.setenv("POORBIRD_IMAGE_ROOT", "/mnt/elsewhere/images")
|
|
monkeypatch.setenv("POORBIRD_API_PORT", "9999")
|
|
monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "deadbeef")
|
|
|
|
s = Settings(_env_file=None)
|
|
|
|
assert s.database_url.endswith("@10.0.0.5:5432/db")
|
|
assert str(s.image_root).endswith("images")
|
|
assert s.api_port == 9999
|
|
assert s.enroll_secret_is_set
|
|
|
|
|
|
def test_database_url_is_tcp_not_a_unix_socket(monkeypatch):
|
|
"""A Unix socket is the one genuinely container-hostile choice."""
|
|
monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@127.0.0.1:5432/poorbird")
|
|
s = Settings(_env_file=None)
|
|
assert "@" in s.database_url and ":" in s.database_url.rpartition("@")[2]
|
|
assert "/var/run/postgresql" not in s.database_url
|
|
|
|
|
|
def test_enroll_secret_is_not_leaked_by_repr():
|
|
s = Settings(_env_file=None, enroll_secret="hunter2")
|
|
assert "hunter2" not in repr(s)
|
|
|
|
|
|
# --- SEC-006: no credentials baked into code --------------------------------
|
|
|
|
|
|
def test_no_database_credentials_are_baked_in(monkeypatch):
|
|
"""A default URL in code is a password in code, however harmless it looks."""
|
|
monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False)
|
|
s = Settings(_env_file=None)
|
|
assert s.database_url == ""
|
|
assert not s.database_url_is_set
|
|
|
|
|
|
def test_unset_database_url_fails_with_a_readable_message(monkeypatch):
|
|
"""Graceful, not a SQLAlchemy URL parse error from three frames down."""
|
|
monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False)
|
|
monkeypatch.setattr("poorbird.config.get_settings", lambda: Settings(_env_file=None))
|
|
|
|
import importlib
|
|
import sys
|
|
|
|
sys.modules.pop("poorbird.db", None)
|
|
with pytest.raises(RuntimeError, match="POORBIRD_DATABASE_URL is not set"):
|
|
importlib.import_module("poorbird.db")
|
|
sys.modules.pop("poorbird.db", None)
|
|
|
|
|
|
def test_placeholder_database_url_is_rejected(monkeypatch):
|
|
monkeypatch.setenv(
|
|
"POORBIRD_DATABASE_URL", "postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird"
|
|
)
|
|
with pytest.raises(ValidationError, match="placeholder"):
|
|
Settings(_env_file=None)
|
|
|
|
|
|
# --- SEC-001: enroll secret comes from the environment only -----------------
|
|
|
|
|
|
def test_enroll_secret_has_no_value_baked_in(monkeypatch):
|
|
monkeypatch.delenv("POORBIRD_ENROLL_SECRET", raising=False)
|
|
s = Settings(_env_file=None)
|
|
assert s.enroll_secret.get_secret_value() == ""
|
|
assert not s.enroll_secret_is_set
|
|
|
|
|
|
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)
|