Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(qa): restore hosted demo — Postgres pool + waitlist funnel (#494)

Beenu Arorab770c118e23b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 23ded556c..6364d311e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -269,6 +269,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+
+- **Hosted demo API 500s from stale Postgres pool + broken waitlist funnel (QA 2026-07-19).**
+ Live `/health` showed `demo_bootstrap.last_error_type=create_seed:ConnectionDoesNotExistError`
+ after 22 attempts — Fly Postgres autostop closed pooled sockets and every
+ subsequent checkout 500ed (`/api/v1/auth/login`, `/metrics/*`, `/alerts/*`,
+ `/cases` → 503). Fixes: (1) `pool_pre_ping=True` + `pool_recycle=300` on the
+ SQLAlchemy engine; (2) demo self-heal bootstrap now disposes the pool after
+ every disconnect, splits create_all / SQL migrations / seed into separate
+ steps, and surfaces stage-tagged errors on `/health`; (3) demo-mode middleware
+ allowlists `POST /api/v1/waitlist/signup` so the managed-instance conversion
+ funnel on tryaisoc.com is no longer 403ed for every visitor.
+
+
- **Out-of-the-box 500 from schema drift on migration-bootstrapped installs (#492).**
`docker-compose.yml` mounts `services/api/migrations` into
`/docker-entrypoint-initdb.d`, so a fresh compose stack builds Postgres from
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index ccb067e80..59d913b35 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -268,6 +268,11 @@ class Settings(BaseSettings):
DATABASE_URL: PostgresDsn = "postgresql+asyncpg://aisoc:aisoc_dev_secret@localhost:5432/aisoc" # type: ignore[assignment]
DATABASE_POOL_SIZE: int = 20
DATABASE_MAX_OVERFLOW: int = 10
+ # Recycle pooled connections before managed Postgres idle-closes them.
+ # Fly Postgres autostop + idle TCP teardown made stale pool entries the
+ # dominant source of ``ConnectionDoesNotExistError`` 500s on the hosted
+ # demo; 300s is well under typical idle timeouts while keeping churn low.
+ DATABASE_POOL_RECYCLE_SECONDS: int = 300
# Redis
REDIS_URL: RedisDsn = "redis://localhost:6379/0" # type: ignore[assignment]
diff --git a/services/api/app/db/database.py b/services/api/app/db/database.py
index 87889059b..ea0c080ab 100644
--- a/services/api/app/db/database.py
+++ b/services/api/app/db/database.py
@@ -68,10 +68,18 @@ def _normalize_async_pg_url(url: str) -> tuple[str, dict[str, Any]]:
_normalized_url, _connect_args = _normalize_async_pg_url(str(settings.DATABASE_URL))
+# pool_pre_ping + pool_recycle are required for Fly Postgres (and any
+# managed Postgres that autostops / idle-closes). Without pre_ping the
+# pool hands out sockets that the server already closed, and asyncpg
+# surfaces that as ``ConnectionDoesNotExistError`` on the next query —
+# which is exactly what was 500ing every demo endpoint on tryaisoc.com
+# (auth/login, metrics/*, alerts/*, …) while /health still looked fine.
engine = create_async_engine(
_normalized_url,
pool_size=settings.DATABASE_POOL_SIZE,
max_overflow=settings.DATABASE_MAX_OVERFLOW,
+ pool_pre_ping=True,
+ pool_recycle=settings.DATABASE_POOL_RECYCLE_SECONDS,
echo=settings.DEBUG,
future=True,
connect_args=_connect_args,
diff --git a/services/api/app/main.py b/services/api/app/main.py
index 1bf9d0baa..f14e27c9a 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -82,6 +82,26 @@ _DEMO_BOOTSTRAP_STATUS: dict[str, object] = {
}
+async def _invalidate_stale_db_pool(reason: str) -> None:
+ """Drop every pooled connection after a mid-flight disconnect.
+
+ Fly Postgres autostop (and idle TCP teardown) closes the server side of a
+ pooled socket without the client noticing. The next checkout then raises
+ ``ConnectionDoesNotExistError``. Disposing the pool forces fresh connects
+ on the next attempt — critical for the hosted demo where this was the
+ dominant cause of out-of-the-box 500s.
+ """
+ try:
+ await engine.dispose()
+ logger.info("demo bootstrap: disposed DB pool after %s", reason)
+ except Exception as dispose_exc: # noqa: BLE001 — best-effort; next attempt still retries
+ logger.warning(
+ "demo bootstrap: engine.dispose failed after %s: %s",
+ reason,
+ type(dispose_exc).__name__,
+ )
+
+
async def _demo_self_heal_bootstrap() -> None:
"""Best-effort schema + seed bootstrap for the hosted demo, run in the background.
@@ -93,10 +113,13 @@ async def _demo_self_heal_bootstrap() -> None:
bare ``asyncpg`` connect (what ``run_migrations`` uses) is unreliable here,
which is why the release_command never applied 045. So we do everything
through the engine: periodically create any missing ORM tables (``checkfirst``
- skips existing ones) and, when the canonical replay is absent, run the
- idempotent demo seed — retrying for a while so it lands whenever Postgres
- becomes reachable. Detached from boot so it never blocks readiness; every
- failure is logged and swallowed.
+ skips existing ones), apply pending SQL migrations, and, when the canonical
+ replay is absent, run the idempotent demo seed — retrying for a while so it
+ lands whenever Postgres becomes reachable. Detached from boot so it never
+ blocks readiness; every failure is logged and swallowed.
+
+ Each failed attempt disposes the SQLAlchemy pool so the next tick does not
+ reuse a socket the server already closed (``ConnectionDoesNotExistError``).
"""
from sqlalchemy import select, text # noqa: PLC0415
@@ -132,23 +155,54 @@ async def _demo_self_heal_bootstrap() -> None:
except Exception as exc: # noqa: BLE001 — table-missing or DB-unreachable; create below
_DEMO_BOOTSTRAP_STATUS["last_error_type"] = f"probe:{type(exc).__name__}"
logger.info("demo bootstrap: schema not ready (attempt %d/40): %s", attempt, type(exc).__name__)
+ await _invalidate_stale_db_pool(f"probe:{type(exc).__name__}")
+ # ── Step A: create missing ORM tables via the engine ─────────────────
try:
- # Create any missing ORM tables (incl. published_replays) via the
- # ENGINE — the path that reliably reaches the demo's Fly Postgres.
- # checkfirst (create_all default) skips existing tables, so this only
- # fills the gap the soft-failed migration left. Then seed the
- # canonical replay + demo data through the same engine-backed session.
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
_DEMO_BOOTSTRAP_STATUS["table_present"] = True
+ except Exception as exc: # noqa: BLE001 — Postgres likely still waking
+ _DEMO_BOOTSTRAP_STATUS["last_error_type"] = f"create_all:{type(exc).__name__}"
+ logger.info(
+ "demo bootstrap: create_all deferred (attempt %d/40): %s",
+ attempt,
+ type(exc).__name__,
+ )
+ await _invalidate_stale_db_pool(f"create_all:{type(exc).__name__}")
+ await asyncio.sleep(45)
+ continue
+
+ # ── Step B: apply pending SQL migrations (fills columns create_all
+ # cannot add to existing tables — e.g. 046 detection_rules drift).
+ try:
+ from app.scripts.run_migrations import main as run_sql_migrations # noqa: PLC0415
+
+ await run_sql_migrations()
+ except Exception as exc: # noqa: BLE001 — soft-fail; seed may still work via ORM
+ _DEMO_BOOTSTRAP_STATUS["last_error_type"] = f"migrate:{type(exc).__name__}"
+ logger.info(
+ "demo bootstrap: SQL migrations deferred (attempt %d/40): %s",
+ attempt,
+ type(exc).__name__,
+ )
+ await _invalidate_stale_db_pool(f"migrate:{type(exc).__name__}")
+ # Don't continue — still try the seed; create_all may be enough.
+
+ # ── Step C: idempotent full seed ─────────────────────────────────────
+ try:
await _run_full_seed()
_DEMO_BOOTSTRAP_STATUS.update(seeded=True, done=True, last_error_type=None)
logger.info("demo bootstrap: create_all + seed pass complete (attempt %d)", attempt)
return
except Exception as exc: # noqa: BLE001 — Postgres likely still waking; retry next tick
- _DEMO_BOOTSTRAP_STATUS["last_error_type"] = f"create_seed:{type(exc).__name__}"
- logger.info("demo bootstrap: create_all+seed deferred (attempt %d/40): %s", attempt, type(exc).__name__)
+ _DEMO_BOOTSTRAP_STATUS["last_error_type"] = f"seed:{type(exc).__name__}"
+ logger.info(
+ "demo bootstrap: seed deferred (attempt %d/40): %s",
+ attempt,
+ type(exc).__name__,
+ )
+ await _invalidate_stale_db_pool(f"seed:{type(exc).__name__}")
await asyncio.sleep(45)
diff --git a/services/api/app/middleware/demo_mode.py b/services/api/app/middleware/demo_mode.py
index 0e6803e47..a521e58af 100644
--- a/services/api/app/middleware/demo_mode.py
+++ b/services/api/app/middleware/demo_mode.py
@@ -42,6 +42,11 @@ _ALWAYS_ALLOWED_PREFIXES: tuple[str, ...] = (
"/api/openapi.json",
"/api/v1/auth/",
"/api/v1/dev-auth",
+ # Managed-instance waitlist lives on tryaisoc.com itself — blocking the
+ # POST under demo mode made the public conversion funnel 403 for every
+ # visitor (QA 2026-07-19). Waitlist rows are a separate table from the
+ # demo SOC dataset, so writes here do not corrupt the shared demo.
+ "/api/v1/waitlist/",
"/saml/",
"/oidc/",
)
diff --git a/services/api/tests/test_database_pool.py b/services/api/tests/test_database_pool.py
new file mode 100644
index 000000000..439e3de13
--- /dev/null
+++ b/services/api/tests/test_database_pool.py
@@ -0,0 +1,61 @@
+"""Pin the SQLAlchemy pool settings that keep Fly Postgres usable.
+
+Without ``pool_pre_ping`` the pool hands out sockets the managed Postgres
+already closed (autostop / idle teardown). The next query then raises
+``asyncpg.exceptions.ConnectionDoesNotExistError``, which is what was
+500ing every demo endpoint on tryaisoc.com while ``/health`` still looked
+fine. These tests are import-free (parse the source) so they run in the
+same lightweight CI job as the schema-drift guards — no full API dep set
+required.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+_API_ROOT = Path(__file__).resolve().parents[1]
+_DATABASE_PY = _API_ROOT / "app" / "db" / "database.py"
+_CONFIG_PY = _API_ROOT / "app" / "core" / "config.py"
+_MAIN_PY = _API_ROOT / "app" / "main.py"
+
+
+def test_engine_enables_pool_pre_ping():
+ src = _DATABASE_PY.read_text(encoding="utf-8")
+ assert "pool_pre_ping=True" in src, (
+ "create_async_engine must set pool_pre_ping=True — without it Fly "
+ "Postgres autostop produces ConnectionDoesNotExistError 500s on every "
+ "demo endpoint"
+ )
+
+
+def test_engine_recycles_pooled_connections():
+ src = _DATABASE_PY.read_text(encoding="utf-8")
+ assert "pool_recycle=" in src, "create_async_engine must set pool_recycle"
+ assert "DATABASE_POOL_RECYCLE_SECONDS" in src
+
+
+def test_pool_recycle_setting_defaults_to_five_minutes():
+ src = _CONFIG_PY.read_text(encoding="utf-8")
+ match = re.search(
+ r"DATABASE_POOL_RECYCLE_SECONDS:\s*int\s*=\s*(\d+)",
+ src,
+ )
+ assert match, "DATABASE_POOL_RECYCLE_SECONDS must be declared on Settings"
+ assert int(match.group(1)) == 300
+
+
+def test_demo_bootstrap_disposes_pool_on_connection_errors():
+ """The self-heal loop must invalidate the pool after a disconnect.
+
+ Otherwise every retry reuses the same dead socket and the hosted demo
+ stays 500ing for the full ~30 min budget (what /health.demo_bootstrap
+ showed on 2026-07-19: 22 attempts, all ConnectionDoesNotExistError).
+ """
+ src = _MAIN_PY.read_text(encoding="utf-8")
+ assert "async def _invalidate_stale_db_pool" in src
+ assert "await engine.dispose()" in src
+ # Every failure path in the bootstrap must call the invalidator.
+ for stage in ("probe:", "create_all:", "migrate:", "seed:"):
+ assert stage in src, f"bootstrap must tag failures as {stage!r}"
+ assert src.count("await _invalidate_stale_db_pool(") >= 3
diff --git a/services/api/tests/test_demo_mode.py b/services/api/tests/test_demo_mode.py
index 8e1d99f16..82fecd9bd 100644
--- a/services/api/tests/test_demo_mode.py
+++ b/services/api/tests/test_demo_mode.py
@@ -62,6 +62,10 @@ def app(monkeypatch: pytest.MonkeyPatch) -> FastAPI:
def login() -> dict[str, Any]:
return {"token": "fake"}
+ @app.post("/api/v1/waitlist/signup")
+ def waitlist_signup() -> dict[str, Any]:
+ return {"ok": True}
+
return app
@@ -170,6 +174,30 @@ def test_auth_login_is_allowed(app: FastAPI) -> None:
assert r.json() == {"token": "fake"}
+def test_waitlist_signup_is_allowed(app: FastAPI) -> None:
+ """Managed-instance waitlist must accept signups on the public demo host.
+
+ ``/waitlist`` is the conversion funnel for tryaisoc.com. Demo-mode must
+ not 403 the POST — waitlist rows are not part of the shared demo SOC
+ dataset, so allowing the write does not let visitors mutate the canned
+ alerts/cases every other visitor sees.
+ """
+ client = TestClient(app)
+ r = client.post(
+ "/api/v1/waitlist/signup",
+ json={
+ "email": "[email protected]",
+ "company": "Acme",
+ "role": "SOC Manager",
+ "soc_stack": ["Splunk"],
+ "motivation": "Alert volume is drowning the team.",
+ },
+ )
+ assert r.status_code == 200
+ assert r.json() == {"ok": True}
+ assert r.headers["X-AiSOC-Demo"] == "true"
+
+
def test_options_preflight_is_allowed(app: FastAPI) -> None:
"""CORS preflight (OPTIONS) is a safe method; gate must let it through."""
client = TestClient(app)