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): await execution_options in demo bootstrap create_all (#496)

Beenu Arora960512195dd8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6364d311e..8d0c4a00a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -280,6 +280,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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.
+- **Demo bootstrap `create_all` AttributeError (QA follow-up).** After Fly Postgres
+ was restarted, `/health` still reported `create_all:AttributeError` because
+ `AsyncConnection.execution_options(...)` is a coroutine and was chained into
+ `.run_sync` without `await`. Await the options object first; pin in
+ `test_database_pool.py`. Unblocks `published_replays` create + `/r/demo-lockbit`.
+- **Canonical `/r/demo-lockbit` missing after re-seed short-circuit.** When
+ INC-RT-* cases already exist, `_seed_in_flight_investigation` returned early
+ and never created `published_replays`. Now that path still ensures the
+ canonical replay; bootstrap only marks `done` after verifying the slug.
- **Out-of-the-box 500 from schema drift on migration-bootstrapped installs (#492).**
diff --git a/services/api/app/main.py b/services/api/app/main.py
index d8160b753..619546a10 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -193,17 +193,22 @@ async def _demo_self_heal_bootstrap() -> None:
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 (AUTOCOMMIT — not one giant txn)
+ # ── Step A: create missing ORM tables (AUTOCOMMIT — not one giant txn).
+ # SQLAlchemy's AsyncConnection.execution_options is a coroutine; it must
+ # be awaited before calling run_sync (chaining without await raises
+ # AttributeError: 'coroutine' object has no attribute 'run_sync').
try:
async with engine.connect() as conn:
- await conn.execution_options(isolation_level="AUTOCOMMIT").run_sync(Base.metadata.create_all)
+ conn = await conn.execution_options(isolation_level="AUTOCOMMIT")
+ 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",
+ "demo bootstrap: create_all deferred (attempt %d/40): %s (%s)",
attempt,
type(exc).__name__,
+ str(exc)[:200],
)
await _invalidate_stale_db_pool(f"create_all:{type(exc).__name__}")
await asyncio.sleep(15)
@@ -226,9 +231,6 @@ async def _demo_self_heal_bootstrap() -> None:
# ── 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"seed:{type(exc).__name__}"
logger.info(
@@ -237,6 +239,27 @@ async def _demo_self_heal_bootstrap() -> None:
type(exc).__name__,
)
await _invalidate_stale_db_pool(f"seed:{type(exc).__name__}")
+ await asyncio.sleep(30)
+ continue
+
+ # Seed may short-circuit on existing cases without creating the
+ # canonical replay — only mark done when the slug is actually present.
+ try:
+ async with AsyncSessionLocal() as session:
+ seeded = await session.scalar(select(PublishedReplay.id).where(PublishedReplay.slug == CANONICAL_REPLAY_SLUG))
+ if seeded:
+ _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
+ _DEMO_BOOTSTRAP_STATUS["last_error_type"] = "seed:canonical_replay_missing"
+ logger.info(
+ "demo bootstrap: seed ran but %s still missing (attempt %d/40)",
+ CANONICAL_REPLAY_SLUG,
+ attempt,
+ )
+ except Exception as exc: # noqa: BLE001
+ _DEMO_BOOTSTRAP_STATUS["last_error_type"] = f"seed-verify:{type(exc).__name__}"
+ await _invalidate_stale_db_pool(f"seed-verify:{type(exc).__name__}")
await asyncio.sleep(30)
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index 084c54b18..ed7e92ac1 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -2075,7 +2075,21 @@ async def _seed_in_flight_investigation(session, tenant: Tenant) -> int:
existing = await session.execute(
select(InvestigationRun).where(InvestigationRun.tenant_id == tenant.id).where(InvestigationRun.case_id == incident["key"]).limit(1)
)
- if existing.scalar_one_or_none() is not None:
+ existing_run = existing.scalar_one_or_none()
+ if existing_run is not None:
+ # Cases/runs may already exist from a prior seed while published_replays
+ # was never created (table missing during an earlier Postgres outage).
+ # Still ensure the canonical /r/demo-lockbit row lands.
+ events = (
+ (
+ await session.execute(
+ select(InvestigationEvent).where(InvestigationEvent.run_id == existing_run.id).order_by(InvestigationEvent.seq.asc())
+ )
+ )
+ .scalars()
+ .all()
+ )
+ await _seed_published_replay(session, tenant, existing_run, list(events))
return 0
started = datetime.now(UTC) - timedelta(minutes=6)
diff --git a/services/api/tests/test_database_pool.py b/services/api/tests/test_database_pool.py
index c857d5d3c..ca9317a21 100644
--- a/services/api/tests/test_database_pool.py
+++ b/services/api/tests/test_database_pool.py
@@ -57,6 +57,10 @@ def test_demo_bootstrap_disposes_pool_on_connection_errors():
assert "await engine.dispose()" in src
assert "async def _wake_demo_postgres" in src
assert 'isolation_level="AUTOCOMMIT"' in src
+ # AsyncConnection.execution_options is a coroutine — must await before
+ # run_sync (chaining without await → AttributeError on 'coroutine').
+ assert "await conn.execution_options(" in src
+ assert "await conn.run_sync(Base.metadata.create_all)" in src
# Every failure path in the bootstrap must call the invalidator.
for stage in ("probe:", "create_all:", "migrate:", "seed:", "wake:"):
assert stage in src, f"bootstrap must tag failures as {stage!r}"