Merge pull request #71 from christianlouis/copilot/fix-seed-default-settings-error

Fix ProgrammingError at startup: asyncpg prepared statement cache invalidated by DDL
This commit is contained in:
Christian Krakau-Louis
2026-03-24 19:04:09 +01:00
committed by GitHub
4 changed files with 24 additions and 0 deletions
+2
View File
@@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
- Fixed `ProgrammingError` (`cached statement plan is invalid`) raised by the asyncpg dialect during startup: SQLAlchemy's asyncpg wrapper maintains an LRU prepared-statement cache per connection (default size 100). When `Base.metadata.create_all()` executes `CREATE TYPE … AS ENUM` DDL inside a transaction, PostgreSQL invalidates the cached plans for that connection. The next enum-type existence check then fails because the dialect tries to reuse the now-stale prepared statement. Fix: set `prepared_statement_cache_size=0` in `connect_args` on `create_async_engine` to disable the cache entirely, which is the documented SQLAlchemy recommendation for DDL-at-startup scenarios.
- Fixed `UndefinedTableError` on first boot: the lifespan startup event now calls `Base.metadata.create_all()` via the async engine before attempting to seed default settings, so all tables are created automatically when the database is empty (e.g., fresh PostgreSQL container with no Alembic migrations run yet).
- Fixed frontend API calls being hardcoded to `http://localhost:8000` in production: `NEXT_PUBLIC_API_URL` is baked into the JavaScript bundle at Next.js build time, so it can never be overridden at container runtime. Replaced the `NEXT_PUBLIC_API_URL` mechanism with a Next.js Route Handler proxy at `/api/v1/[...path]` that reads `process.env.BACKEND_URL` at server startup and proxies all `/api/v1/*` requests to the real backend. The frontend Axios client now uses a relative base URL (`/api/v1`), which also eliminates the CORS issue since the browser only ever talks to the same-origin Next.js server. Update `BACKEND_URL=http://backend:8000` in `docker-compose.new.yml` (or your deployment env) to point the proxy at your backend.
- Fixed infinite spinning wheel on the home page: `authStore` no longer initialises `isLoading` as `true` unconditionally — it is now `false` when no access token exists in `localStorage`, so unauthenticated users see the landing page immediately instead of an endless spinner
- Home page now performs an auth check when a token is present in `localStorage`, redirecting authenticated users to the dashboard and clearing stale tokens on failure
+5
View File
@@ -9,12 +9,17 @@ from sqlalchemy.orm import declarative_base
from app.core.config import settings
# Create async engine
# prepared_statement_cache_size=0 disables SQLAlchemy's asyncpg prepared-statement
# LRU cache. This prevents ProgrammingError("cached statement plan is invalid") when
# CREATE TYPE / CREATE TABLE DDL (run via create_all at startup) invalidates previously
# cached statement plans on the same connection.
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DEBUG,
pool_size=settings.DATABASE_POOL_SIZE,
max_overflow=settings.DATABASE_MAX_OVERFLOW,
pool_pre_ping=True,
connect_args={"prepared_statement_cache_size": 0},
)
# Create async session factory
+15
View File
@@ -29,6 +29,21 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
logger.info(f"Debug mode: {settings.DEBUG}")
logger.info("API documentation: /api/docs")
# Ensure all database tables exist (idempotent; safe to run on every startup)
try:
from app.core.database import engine, Base
import app.models.database_models # noqa: F401 - register all ORM models
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
logger.info("Database tables verified/created")
except Exception as exc:
logger.error(
"Could not create database tables: %s — API requests requiring DB will fail",
exc,
exc_info=True,
)
# Seed default database-backed settings (no-op if they already exist)
try:
from app.core.database import async_session_maker
+2
View File
@@ -100,6 +100,8 @@ Comprehensive task breakdown for repository improvements and production readines
- [x] Fix Docker build failure: wrap `useSearchParams()` in Suspense boundary in `/auth/callback` page
- [x] Fix frontend API URL hardcoded to `localhost:8000` in production: replaced build-time `NEXT_PUBLIC_API_URL` with a runtime Next.js Route Handler proxy (`/api/v1/[...path]`) reading `BACKEND_URL` at server startup
- [x] Log `BACKEND_URL` at frontend server startup and include target URL in per-request proxy error messages
- [x] Fix `UndefinedTableError` on first boot: lifespan event now runs `Base.metadata.create_all()` so tables are created automatically when no migrations have been applied
- [x] Fix `ProgrammingError` (cached statement plan is invalid) during startup: set `prepared_statement_cache_size=0` on the asyncpg engine to prevent plan invalidation when `CREATE TYPE` DDL runs at startup
### In Progress 🔨
- [ ] Configure branch protection rules