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(audit): stop a failed cost write from deleting the audit row it precedes (#975)

Beenu Arora7a62c6ec9199
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index ec37cb05e..7060b31e1 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -648,6 +648,27 @@ jobs:
POSTGRES_RLS_ISOLATION_REQUIRED: '1'
run: python -m pytest tests/isolation/test_postgres_rls.py -v --tb=short
+ # `POST /alerts/{id}/explain` logged `audit: failed to compute hash chain`
+ # on every call against a default install, and the audit row was not
+ # merely unchained — it was never written. A best-effort cost INSERT
+ # failed, the caller caught the Python exception, and PostgreSQL had
+ # already aborted the transaction, so every later statement including
+ # the audit INSERT failed too.
+ #
+ # The abort is a PostgreSQL behaviour. SQLite does not have it, so the
+ # unit suite exercises the savepoint mechanics and cannot reproduce the
+ # defect; this runs the reproduction against a real database.
+ # POSTGRES_ABORT_SEMANTICS_REQUIRED turns an unreachable database into a
+ # failure rather than a skip, for the same reason as the job above.
+ - name: A failed optional write does not delete the audit row (live)
+ env:
+ POSTGRES_ABORT_SEMANTICS_REQUIRED: '1'
+ # The suite imports `app.db.best_effort`, and this job runs from the
+ # repository root where `app` is not importable — the API service is
+ # not pip-installed here. Same answer the alembic steps below use.
+ PYTHONPATH: services/api
+ run: python -m pytest services/api/tests/test_audit_chain_survives_a_failed_write.py -v --tb=short
+
# Gap-closure Phase 2.3's "Done when", run rather than reasoned about: a
# test tenant with 20 shadow decisions cannot enable auto-close, can
# once the thresholds are met, and is demoted when injected
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 43c82b5bc..3361d9148 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -7606,6 +7606,58 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/health/audit-chain:
+ get:
+ tags:
+ - health
+ summary: Get Audit Chain Health
+ description: 'Whether the audit log''s tamper-evidence actually covers this
+ tenant.
+
+
+ `apps/docs/docs/operations/security.md` states that every state-changing
+
+ action is appended to an immutable, hash-chained log. That claim is only
+
+ true of rows that carry a hash, and the one signal that a row did not was
+
+ a `logger.warning` — which fired on every `alerts.explain` against a
+
+ default install for as long as a best-effort cost write could abort the
+
+ transaction underneath it. Nobody noticed, because an append-only log
+
+ going quiet looks exactly like an idle one.
+
+
+ So the question gets a surface. `unchained` counts rows this tenant holds
+
+ with no `entry_hash`, split into the ones written before migration 043
+
+ (which never had one and are not a defect) and the ones written after it
+
+ (which are). A reviewer asking "is the chain intact?" gets a number rather
+
+ than a grep.
+
+
+ `verified` replays the chain with `verify_chain` over the most recent
+
+ window, so a row that was rewritten in place is found rather than assumed
+
+ absent.'
+ operationId: get_audit_chain_health_api_v1_health_audit_chain_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ additionalProperties: true
+ type: object
+ title: Response Get Audit Chain Health Api V1 Health Audit Chain Get
+ security:
+ - HTTPBearer: []
/api/v1/health/shadow-reconciliation:
get:
tags:
diff --git a/services/api/app/api/v1/endpoints/health.py b/services/api/app/api/v1/endpoints/health.py
index 9490548e3..73e1cf24b 100644
--- a/services/api/app/api/v1/endpoints/health.py
+++ b/services/api/app/api/v1/endpoints/health.py
@@ -85,6 +85,7 @@ from app.api.v1.endpoints.metrics import PipelineHealth, PipelineStage
from app.core.config import settings
from app.models.alert import Alert
from app.models.connector import Connector
+from app.services.audit_hash import verify_chain
from app.services.connector_freshness import compute_freshness
from app.services.fleet_health import assess_fleet
from app.services.replay_evaluation.vendors import replayable_connector_ids
@@ -621,6 +622,112 @@ async def get_dead_letters(
}
[email protected]("/audit-chain")
+async def get_audit_chain_health(
+ user: AuthUser,
+ db: DBSession,
+) -> dict[str, Any]:
+ """Whether the audit log's tamper-evidence actually covers this tenant.
+
+ `apps/docs/docs/operations/security.md` states that every state-changing
+ action is appended to an immutable, hash-chained log. That claim is only
+ true of rows that carry a hash, and the one signal that a row did not was
+ a `logger.warning` — which fired on every `alerts.explain` against a
+ default install for as long as a best-effort cost write could abort the
+ transaction underneath it. Nobody noticed, because an append-only log
+ going quiet looks exactly like an idle one.
+
+ So the question gets a surface. `unchained` counts rows this tenant holds
+ with no `entry_hash`, split into the ones written before migration 043
+ (which never had one and are not a defect) and the ones written after it
+ (which are). A reviewer asking "is the chain intact?" gets a number rather
+ than a grep.
+
+ `verified` replays the chain with `verify_chain` over the most recent
+ window, so a row that was rewritten in place is found rather than assumed
+ absent.
+ """
+ window = 500
+
+ counts = (
+ (
+ await db.execute(
+ text(
+ """
+ SELECT
+ count(*) FILTER (WHERE entry_hash IS NULL) AS unchained,
+ count(*) FILTER (WHERE entry_hash IS NOT NULL) AS chained,
+ count(*) AS total,
+ min(created_at) FILTER (WHERE entry_hash IS NULL) AS oldest_unchained,
+ max(created_at) FILTER (WHERE entry_hash IS NULL) AS newest_unchained
+ FROM audit_log
+ WHERE tenant_id = :tid
+ """
+ ),
+ {"tid": user.tenant_id},
+ )
+ )
+ .mappings()
+ .one()
+ )
+
+ rows = (
+ (
+ await db.execute(
+ text(
+ """
+ SELECT id, tenant_id, actor_id, actor_email, actor_ip,
+ action, resource, resource_id, changes, metadata, created_at,
+ prev_hash, entry_hash
+ FROM audit_log
+ WHERE tenant_id = :tid
+ ORDER BY created_at DESC, id DESC
+ LIMIT :lim
+ """
+ ),
+ {"tid": user.tenant_id, "lim": window},
+ )
+ )
+ .mappings()
+ .all()
+ )
+ replay = [dict(r) for r in reversed(rows)]
+ intact, bad_index, reason = verify_chain(replay)
+
+ unchained = int(counts["unchained"] or 0)
+ return {
+ # Two facts, reported separately, because they have different causes
+ # and a single boolean would hide that. `chain_complete` is about rows
+ # written with no hash at all — what a failed chain computation
+ # produces, and what `aisoc_audit_chain_failures_total` counts.
+ # `replay_intact` is about the links between rows that do have one.
+ "chain_complete": unchained == 0,
+ "total_rows": int(counts["total"] or 0),
+ "chained_rows": int(counts["chained"] or 0),
+ # Every row here is one the tamper-evidence claim does not cover.
+ # Migration 043 made the columns nullable so existing deployments
+ # could adopt the chain without a flag day, so a non-zero count on an
+ # old tenant may be legacy — the timestamps say which.
+ "unchained_rows": unchained,
+ "oldest_unchained_at": counts["oldest_unchained"].isoformat() if counts["oldest_unchained"] else None,
+ "newest_unchained_at": counts["newest_unchained"].isoformat() if counts["newest_unchained"] else None,
+ "replay_window": len(replay),
+ # A replay break is not always tampering. Two audit writers in one
+ # request — a handler calling `emit_audit` and `audit_middleware`
+ # writing its own row on a separate session — can resolve the same
+ # head and fork the chain, and a fork is indistinguishable from a
+ # removed row. That is a real, open defect in the writer, documented
+ # on `app.services.audit._resolve_prev_hash`; it is reported here
+ # rather than hidden, because hiding it is what made the chain's
+ # failure invisible in the first place.
+ "replay_intact": intact,
+ "replay_broken_at_index": bad_index,
+ "replay_reason": reason,
+ # The counter is the alertable half; this is the on-demand half.
+ "metric": "aisoc_audit_chain_failures_total",
+ }
+
+
@router.get("/shadow-reconciliation")
async def get_shadow_reconciliation_health(
user: AuthUser,
diff --git a/services/api/app/db/best_effort.py b/services/api/app/db/best_effort.py
new file mode 100644
index 000000000..f0079353d
--- /dev/null
+++ b/services/api/app/db/best_effort.py
@@ -0,0 +1,87 @@
+"""Run optional database work without taking the caller's transaction with it.
+
+The defect this exists for
+--------------------------
+``POST /alerts/{id}/explain`` emitted this on every call against a default
+install::
+
+ WARNING explain.cost_track_failed … NotNullViolationError: null value in
+ column "total_cost_usd" of relation "aisoc_run_costs"
+ WARNING audit: failed to compute hash chain for tenant=… action=alerts.explain
+
+Two log lines, and only the first names a cause. The second is a consequence:
+PostgreSQL aborts the whole transaction on any statement error, and every
+later statement on that connection then raises ``InFailedSqlTransaction``
+until a rollback. The cost insert was wrapped in ``try/except`` so it "could
+not break the response" — but catching the Python exception does not undo the
+abort, so the *next* piece of work on the same session failed too. That next
+piece of work was the audit log.
+
+The audit row was then not merely unchained. Its own ``INSERT`` was issued on
+the same aborted transaction and failed as well, so the ``alerts.explain``
+event was **never written**. An append-only hash-chained audit log that
+silently drops events is a compliance claim that is false, and nothing above
+the warning line said so.
+
+The rule
+--------
+Optional database work runs inside a SAVEPOINT. A failure rolls back to the
+savepoint, the outer transaction survives, and the caller's later work — the
+audit row above all — still commits. Catching the exception without the
+savepoint is the shape that looks correct and is not.
+
+This is deliberately not "retry" or "ignore". It is scoped rollback: the
+caller still gets the exception, still decides whether to degrade, and still
+logs. What changes is that the decision is theirs rather than PostgreSQL's.
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator, Awaitable, Callable
+from contextlib import asynccontextmanager
+from typing import TypeVar
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+T = TypeVar("T")
+
+
+@asynccontextmanager
+async def savepoint(db: AsyncSession) -> AsyncIterator[None]:
+ """Scope a block's database errors to a SAVEPOINT.
+
+ The exception still propagates — the caller decides what a failure means.
+ What the savepoint guarantees is that the outer transaction is usable
+ afterwards either way.
+
+ ``AsyncSession.begin_nested`` emits ``SAVEPOINT`` and, on exit, either
+ ``RELEASE SAVEPOINT`` or ``ROLLBACK TO SAVEPOINT``. On a session with no
+ transaction open yet SQLAlchemy begins one first, so this is safe to use
+ before the caller has issued any statement.
+ """
+ nested = await db.begin_nested()
+ try:
+ yield
+ except BaseException:
+ if nested.is_active:
+ await nested.rollback()
+ raise
+ else:
+ if nested.is_active:
+ await nested.commit()
+
+
+async def attempt(db: AsyncSession, operation: Callable[[], Awaitable[T]]) -> tuple[T | None, Exception | None]:
+ """Run ``operation`` in a savepoint; return ``(result, error)``.
+
+ For the common shape where a caller wants to degrade rather than raise.
+ Returning the exception instead of swallowing it keeps the caller's log
+ line specific — ``explain.cost_track_failed … NotNullViolationError`` is
+ what identified the defect above, and a bare "cost tracking failed" would
+ not have.
+ """
+ try:
+ async with savepoint(db):
+ return await operation(), None
+ except Exception as exc: # noqa: BLE001 - the caller decides what it means
+ return None, exc
diff --git a/services/api/app/services/alert_explain.py b/services/api/app/services/alert_explain.py
index 9238e8493..1bfbbe554 100644
--- a/services/api/app/services/alert_explain.py
+++ b/services/api/app/services/alert_explain.py
@@ -55,6 +55,7 @@ from sqlalchemy import and_, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.airgap import AirgapViolation, enforce_airgap_for_url
+from app.db.best_effort import attempt
from app.models.alert import Alert
from app.models.detection_rule import DetectionRule
from app.services.cost_dashboard import _impute_public_cost
@@ -386,9 +387,11 @@ async def _historical_fp_rate(
.limit(_FP_RATE_SAMPLE_CAP)
)
- try:
- row = (await db.execute(query)).one()
- except Exception as exc: # noqa: BLE001
+ # In a savepoint: this query is informational, but a failure here aborts
+ # the transaction for everything after it — which is how a failed analytics
+ # query used to take the audit row for the same request down with it.
+ row, exc = await attempt(db, lambda: db.execute(query))
+ if exc is not None:
# FP rate is informational; never fail the whole explain
# endpoint because the analytics query timed out.
logger.warning("explain.fp_rate_query_failed tenant=%s error=%s", tenant_id, exc)
@@ -401,8 +404,10 @@ async def _historical_fp_rate(
notes=f"Query failed: {exc}; treat with caution.",
)
- total = int(row.total or 0)
- fps = int(row.fps or 0)
+ assert row is not None # noqa: S101 - `attempt` returns one of the two
+ aggregate = row.one()
+ total = int(aggregate.total or 0)
+ fps = int(aggregate.fps or 0)
rate = (fps / total) if total else 0.0
return HistoricalFpRate(
fp_rate=round(rate, 4),
@@ -841,12 +846,29 @@ async def _record_llm_cost(
# operators still see them in the audit trail.
return
- cost_usd = _impute_public_cost(
+ # ``None`` means "this model has no published list price", which is the
+ # normal case for the local model CORE ships. It used to be passed
+ # straight into ``total_cost_usd``, a NOT NULL column, so every explain on
+ # a default install raised
+ #
+ # NotNullViolationError: null value in column "total_cost_usd" of
+ # relation "aisoc_run_costs" violates not-null constraint
+ #
+ # which the caller swallowed as `explain.cost_track_failed` — and which
+ # took the whole transaction down with it. See the savepoint in
+ # ``generate_alert_explanation``.
+ estimated = _impute_public_cost(
call.model,
call.prompt_tokens,
call.completion_tokens,
)
+ # Migration 063's vocabulary, which this writer predates. ``total_cost_usd``
+ # carries **measured** (gateway-reported) cost only, and this path has no
+ # gateway-reported figure — ``_LlmCallResult`` carries no cost header — so
+ # it is never written here. A list-price figure goes to the estimate
+ # columns and an unpriced call increments a counter, which is how a
+ # surface downstream can say "not measured" rather than "$0.00".
run_id = f"alert:{alert_id}"
# ``aisoc_run_costs`` PK is (run_id, tenant_id, model). We use an
@@ -864,7 +886,9 @@ async def _record_llm_cost(
"model": call.model,
"prompt_tokens": call.prompt_tokens,
"completion_tokens": call.completion_tokens,
- "cost_usd": cost_usd,
+ "estimated_cost_usd": estimated or 0.0,
+ "estimated_call_count": 1 if estimated is not None else 0,
+ "unpriced_call_count": 0 if estimated is not None else 1,
"latency_ms": call.latency_ms,
},
)
@@ -877,19 +901,25 @@ _UPSERT_RUN_COST = text(
INSERT INTO aisoc_run_costs (
run_id, tenant_id, model,
total_prompt_tokens, total_completion_tokens,
- total_cost_usd, total_latency_ms, call_count, recorded_at
+ total_cost_usd, total_latency_ms, call_count,
+ estimated_cost_usd, estimated_call_count, unpriced_call_count,
+ recorded_at
)
VALUES (
:run_id, :tenant_id, :model,
:prompt_tokens, :completion_tokens,
- :cost_usd, :latency_ms, 1, now()
+ 0, :latency_ms, 1,
+ :estimated_cost_usd, :estimated_call_count, :unpriced_call_count,
+ now()
)
ON CONFLICT (run_id, tenant_id, model) DO UPDATE SET
total_prompt_tokens = aisoc_run_costs.total_prompt_tokens + EXCLUDED.total_prompt_tokens,
total_completion_tokens = aisoc_run_costs.total_completion_tokens + EXCLUDED.total_completion_tokens,
- total_cost_usd = aisoc_run_costs.total_cost_usd + EXCLUDED.total_cost_usd,
total_latency_ms = aisoc_run_costs.total_latency_ms + EXCLUDED.total_latency_ms,
call_count = aisoc_run_costs.call_count + 1,
+ estimated_cost_usd = aisoc_run_costs.estimated_cost_usd + EXCLUDED.estimated_cost_usd,
+ estimated_call_count = aisoc_run_costs.estimated_call_count + EXCLUDED.estimated_call_count,
+ unpriced_call_count = aisoc_run_costs.unpriced_call_count + EXCLUDED.unpriced_call_count,
recorded_at = now()
"""
)
@@ -961,16 +991,17 @@ async def generate_alert_explanation(
# Always attempt to book the cost — _record_llm_cost no-ops on
# failed calls so we don't pollute the cost table with zero
# rows.
- try:
- await _record_llm_cost(
- db,
- tenant_id=alert.tenant_id,
- alert_id=alert.id,
- call=call,
- )
- except Exception as exc: # noqa: BLE001
- # Cost tracking failures must never break the explain
- # response. Log and move on.
+ # In a savepoint. "Must never break the explain response" was already
+ # the intent, and the `try/except` around it did not achieve it: a
+ # failed INSERT aborts the PostgreSQL transaction, so catching the
+ # Python exception left every later statement on this session failing
+ # too — including the audit row for this very request, which was
+ # therefore never written at all.
+ _, exc = await attempt(
+ db,
+ lambda: _record_llm_cost(db, tenant_id=alert.tenant_id, alert_id=alert.id, call=call),
+ )
+ if exc is not None:
logger.warning(
"explain.cost_track_failed tenant=%s alert=%s error=%s",
alert.tenant_id,
diff --git a/services/api/app/services/audit.py b/services/api/app/services/audit.py
index 2304372cf..b2091dde1 100644
--- a/services/api/app/services/audit.py
+++ b/services/api/app/services/audit.py
@@ -49,16 +49,31 @@ from datetime import UTC, datetime
from typing import Any
from fastapi import Request
+from prometheus_client import Counter
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.trusted_proxy import resolve_client_ip
+from app.db.best_effort import savepoint
from app.models.audit import AuditLog
from app.services.audit_hash import compute_entry_hash
from app.services.audit_redaction import redact_changes
logger = logging.getLogger("aisoc.audit")
+#: Rows written without a hash link, by the action that produced them.
+#:
+#: Defined here rather than in ``app.main`` so that importing the audit
+#: service is enough to register it: a counter declared beside the HTTP
+#: metrics would be missing from any process that emits audit events without
+#: serving requests, and a metric that exists on one replica and not another
+#: reads as zero.
+AUDIT_CHAIN_FAILURES = Counter(
+ "aisoc_audit_chain_failures_total",
+ "Audit rows written with no hash link, so tamper-evidence does not cover them.",
+ ["action"],
+)
+
# Hard caps on header-derived metadata that lands in the audit row.
# These exist independently of changes-payload redaction and protect
# the ``metadata`` JSONB column from arbitrary client growth.
@@ -78,6 +93,28 @@ async def _resolve_prev_hash(db: AsyncSession, tenant_id: uuid.UUID) -> str | No
tenant). Legacy rows that pre-date the hash chain — where
``entry_hash IS NULL`` — are skipped via the partial index from
migration 043; new chains begin from the first hashed row.
+
+ **Known limitation — concurrent writers fork the chain.** The read here
+ and the insert that follows are not atomic, and one request can have two
+ writers: this handler's session and `audit_middleware`'s own. Measured on
+ `POST /alerts/{id}/explain`, two milliseconds apart, both resolving the
+ same head:
+
+ alerts:create entry=dabf5207f866 prev=-
+ alerts.explain entry=66eed8144cee prev=dabf5207f866
+ alerts:create entry=ca30ed264f98 prev=dabf5207f866 <- fork
+
+ `verify_chain` calls that broken and is right to: a fork is
+ indistinguishable from a removed row. `GET /api/v1/health/audit-chain`
+ reports it rather than hiding it.
+
+ It is not fixed here, and a transaction-scoped advisory lock is not the
+ fix: the middleware runs before the request session's dependency
+ teardown, so the handler still holds the lock and the middleware's
+ acquisition times out — measured, and it dropped the middleware's row
+ entirely, which is worse than the fork. Closing it needs a commit-ordered
+ sequence or a single audit writer per request, which is a design change
+ and not this one.
"""
stmt = (
select(AuditLog.entry_hash)
@@ -182,8 +219,16 @@ async def emit_audit(
# write the row — falling back to an unchained entry is strictly
# better than failing the originating mutation, and the gap is
# detectable by the verifier.
+ #
+ # Inside a savepoint, because "we still write the row" was not true.
+ # PostgreSQL aborts the whole transaction on a statement error, so a
+ # failed SELECT here left the INSERT below failing too and the event was
+ # never written at all. Observed on `alerts.explain`, where the SELECT was
+ # not itself at fault — an earlier best-effort cost INSERT had already
+ # aborted the transaction, and this was simply the next statement to run.
try:
- prev = await _resolve_prev_hash(db, tenant_id)
+ async with savepoint(db):
+ prev = await _resolve_prev_hash(db, tenant_id)
event.prev_hash = prev
event.entry_hash = compute_entry_hash(
prev_hash=prev,
@@ -200,8 +245,22 @@ async def emit_audit(
created_at=event.created_at,
)
except Exception: # noqa: BLE001
- logger.warning(
- "audit: failed to compute hash chain for tenant=%s action=%s",
+ # `error`, a counter and a health surface — not a warning.
+ #
+ # This was `logger.warning` and nothing else, and it fired on every
+ # `alerts.explain` against a default install for as long as the cost
+ # writer could abort the transaction. Nobody noticed, because an
+ # append-only log going quiet looks exactly like an idle one. A
+ # compliance control whose only failure signal is a line in a stream
+ # nobody greps is a control in name only.
+ #
+ # `aisoc_audit_chain_failures_total` is scraped on /metrics, so this
+ # is alertable, and `GET /api/v1/health/audit-chain` answers the same
+ # question on demand for an auditor who is not watching a dashboard.
+ AUDIT_CHAIN_FAILURES.labels(action=action).inc()
+ logger.error(
+ "audit: failed to compute hash chain for tenant=%s action=%s — "
+ "this row is written UNCHAINED and the tamper-evidence claim does not hold for it",
tenant_id,
action,
exc_info=True,
diff --git a/services/api/tests/test_alert_explain.py b/services/api/tests/test_alert_explain.py
index ba6d319a3..bb9af3ce3 100644
--- a/services/api/tests/test_alert_explain.py
+++ b/services/api/tests/test_alert_explain.py
@@ -146,6 +146,25 @@ def _rule(
)
+def _fake_session() -> MagicMock:
+ """A stand-in `AsyncSession` that also understands savepoints.
+
+ The optional database work in this module — the FP-rate aggregate and the
+ cost write — now runs inside `db.begin_nested()`, because a failure
+ without one aborts the PostgreSQL transaction and takes the caller's
+ later statements down with it, which is how a cost-tracking bug deleted
+ an `alerts.explain` audit row. A bare `MagicMock` returns a non-awaitable
+ for `begin_nested`, so the fake has to grow the same shape.
+ """
+ nested = MagicMock()
+ nested.is_active = True
+ nested.commit = AsyncMock()
+ nested.rollback = AsyncMock()
+ db = MagicMock()
+ db.begin_nested = AsyncMock(return_value=nested)
+ return db
+
+
def _scalar_one_or_none_result(value: Any) -> MagicMock:
"""Mock an ``await session.execute(...)`` whose ``scalar_one_or_none()`` returns ``value``."""
result = MagicMock()
@@ -259,7 +278,7 @@ class TestResolveRuleLineage:
rule = _rule(rule_id=rid)
alert = _alert(raw_event={"rule_id": str(rid)})
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_scalar_one_or_none_result(rule))
result_rule, confidence, method = await _resolve_rule_lineage(db, alert)
@@ -279,7 +298,7 @@ class TestResolveRuleLineage:
mitre_techniques=["T1078"],
)
- db = MagicMock()
+ db = _fake_session()
# First call: explicit lookup → no row.
# Second call: candidate scan → one matching rule.
rule = _rule(mitre_techniques=["T1078"])
@@ -302,7 +321,7 @@ class TestResolveRuleLineage:
# without hitting the DB a second time.
alert = _alert(category=None, mitre_techniques=[])
- db = MagicMock()
+ db = _fake_session()
# No explicit signal in this alert, so no lookup at all.
# We assert we never call execute (early return).
db.execute = AsyncMock()
@@ -324,7 +343,7 @@ class TestResolveRuleLineage:
)
alert = _alert(mitre_techniques=["T1078", "T1110", "T1059"])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_scalars_all_result([rule]))
result_rule, confidence, method = await _resolve_rule_lineage(db, alert)
@@ -350,7 +369,7 @@ class TestResolveRuleLineage:
)
alert = _alert(category="identity", mitre_techniques=["T1059"])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_scalars_all_result([rule]))
result_rule, confidence, method = await _resolve_rule_lineage(db, alert)
@@ -365,7 +384,7 @@ class TestResolveRuleLineage:
# This is the "tenant disabled all rules" corner.
alert = _alert(category="identity", mitre_techniques=["T1078"])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_scalars_all_result([]))
result_rule, confidence, method = await _resolve_rule_lineage(db, alert)
@@ -393,7 +412,7 @@ class TestHistoricalFpRate:
rule = _rule(category="identity", mitre_techniques=["T1078"])
alert = _alert(tenant_id=tenant, category="identity", mitre_techniques=["T1078"])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_row_one_result(total=200, fps=20))
fp = await _historical_fp_rate(db, tenant_id=tenant, rule=rule, alert=alert)
@@ -412,7 +431,7 @@ class TestHistoricalFpRate:
tenant = uuid.uuid4()
alert = _alert(tenant_id=tenant, category="identity", mitre_techniques=["T1078"])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_row_one_result(total=50, fps=5))
fp = await _historical_fp_rate(db, tenant_id=tenant, rule=None, alert=alert)
@@ -425,7 +444,7 @@ class TestHistoricalFpRate:
tenant = uuid.uuid4()
alert = _alert(tenant_id=tenant, category="identity", mitre_techniques=[])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_row_one_result(total=10, fps=1))
fp = await _historical_fp_rate(db, tenant_id=tenant, rule=None, alert=alert)
@@ -439,7 +458,7 @@ class TestHistoricalFpRate:
tenant = uuid.uuid4()
alert = _alert(tenant_id=tenant, category=None, mitre_techniques=[])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_row_one_result(total=100, fps=10))
fp = await _historical_fp_rate(db, tenant_id=tenant, rule=None, alert=alert)
@@ -452,7 +471,7 @@ class TestHistoricalFpRate:
tenant = uuid.uuid4()
alert = _alert(tenant_id=tenant)
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(return_value=_row_one_result(total=0, fps=0))
fp = await _historical_fp_rate(db, tenant_id=tenant, rule=None, alert=alert)
@@ -468,7 +487,7 @@ class TestHistoricalFpRate:
tenant = uuid.uuid4()
alert = _alert(tenant_id=tenant)
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(side_effect=RuntimeError("connection reset"))
fp = await _historical_fp_rate(db, tenant_id=tenant, rule=None, alert=alert)
@@ -733,7 +752,7 @@ class TestGenerateAlertExplanation:
# The endpoint should NEVER fail-closed because the LLM is off.
alert = _alert(category="identity", mitre_techniques=["T1078"])
- db = MagicMock()
+ db = _fake_session()
# No explicit rule → falls through to candidate scan returning
# no candidates → no rule. FPR query returns zero sample.
db.execute = AsyncMock(
@@ -763,7 +782,7 @@ class TestGenerateAlertExplanation:
# Happy path: resolver allows, LLM returns text, cost is booked.
alert = _alert(category="identity", mitre_techniques=["T1078"])
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(
side_effect=[
_scalars_all_result([]), # no candidate rules
@@ -807,7 +826,7 @@ class TestGenerateAlertExplanation:
# the deterministic summary and surface the failure reason.
alert = _alert(category="identity")
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(
side_effect=[
_scalars_all_result([]),
@@ -849,7 +868,7 @@ class TestGenerateAlertExplanation:
# The dashboard will simply miss this row.
alert = _alert(category="identity")
- db = MagicMock()
+ db = _fake_session()
db.execute = AsyncMock(
side_effect=[
_scalars_all_result([]),
diff --git a/services/api/tests/test_audit_chain_survives_a_failed_write.py b/services/api/tests/test_audit_chain_survives_a_failed_write.py
new file mode 100644
index 000000000..96d5ff158
--- /dev/null
+++ b/services/api/tests/test_audit_chain_survives_a_failed_write.py
@@ -0,0 +1,212 @@
+"""A failed best-effort write must not take the audit row with it.
+
+What was observed
+-----------------
+Against a running CORE stack, `POST /api/v1/alerts/{id}/explain` answered 200
+and logged two lines:
+
+ WARNING explain.cost_track_failed … NotNullViolationError: null value in
+ column "total_cost_usd" of relation "aisoc_run_costs" violates
+ not-null constraint
+ WARNING audit: failed to compute hash chain for tenant=… action=alerts.explain
+
+Only the first names a cause. `_impute_public_cost` returns `None` for a model
+with no published list price — the normal case for the local model CORE ships
+— and that `None` went straight into a `NOT NULL` column. The caller caught
+the Python exception, which does not undo PostgreSQL aborting the
+transaction, so every later statement on the session failed too.
+
+The audit row was not merely written unchained. Its own `INSERT` ran on the
+same aborted transaction and failed as well, so `audit_log` held no
+`alerts.explain` row at all — confirmed against the database afterwards:
+
+ action | unchained | created_at
+ alerts:create | f | 2026-09-28 15:58:59.818406+00
+ (1 row)
+
+Why these assertions run rather than read
+-----------------------------------------
+Every one of these drives a real transaction against SQLite with
+`SAVEPOINT` semantics, because the property under test is a database
+behaviour and not a shape in the source. A test that asserted
+"`_record_llm_cost` is wrapped in try/except" would have passed throughout:
+it *was*.
+"""
+
+from __future__ import annotations
+
+import os
+import socket
+import uuid
+from urllib.parse import urlparse
+
+import pytest
+import pytest_asyncio
+from app.db.best_effort import attempt, savepoint
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+
+
+@pytest_asyncio.fixture
+async def session():
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
+ async with engine.begin() as conn:
+ await conn.execute(text("CREATE TABLE widget (id TEXT PRIMARY KEY, name TEXT NOT NULL)"))
+ maker = async_sessionmaker(engine, expire_on_commit=False)
+ async with maker() as db:
+ yield db
+ await engine.dispose()
+
+
+async def _insert(db: AsyncSession, name: str | None) -> None:
+ await db.execute(text("INSERT INTO widget (id, name) VALUES (:i, :n)"), {"i": str(uuid.uuid4()), "n": name})
+
+
+class TestAFailedOptionalWriteLeavesTheSessionUsable:
+ @pytest.mark.asyncio
+ async def test_a_savepoint_confines_the_failure(self, session: AsyncSession) -> None:
+ _, exc = await attempt(session, lambda: _insert(session, None))
+ assert exc is not None, "the failure must still reach the caller — silence is the other defect"
+
+ # The work that used to be collateral damage.
+ await _insert(session, "the audit row")
+ rows = (await session.execute(text("SELECT name FROM widget"))).scalars().all()
+ assert rows == ["the audit row"]
+
+ @pytest.mark.asyncio
+ async def test_a_successful_operation_still_commits(self, session: AsyncSession) -> None:
+ """The other direction. A savepoint that rolled back unconditionally
+ would pass the test above and silently discard every optional write."""
+ result, exc = await attempt(session, lambda: _insert(session, "kept"))
+ assert exc is None
+ assert result is None or result is not None # `_insert` returns None; the point is it ran
+ rows = (await session.execute(text("SELECT name FROM widget"))).scalars().all()
+ assert rows == ["kept"]
+
+ @pytest.mark.asyncio
+ async def test_the_context_manager_reraises(self, session: AsyncSession) -> None:
+ with pytest.raises(Exception): # noqa: B017, PT011 - driver-specific integrity error
+ async with savepoint(session):
+ await _insert(session, None)
+ await _insert(session, "still works")
+
+
+class TestTheExplainCostWriterCannotProduceNull:
+ """`total_cost_usd` is NOT NULL and the imputer returns None by design.
+
+ `_impute_public_cost` returning `None` is deliberate — "this model has no
+ published price" and "this model is free" are different facts. The defect
+ was the writer treating that as a number.
+ """
+
+ def test_an_unpriced_model_is_counted_not_costed(self) -> None:
+ from app.services.alert_explain import _UPSERT_RUN_COST
+
+ sql = str(_UPSERT_RUN_COST)
+ assert ":cost_usd" not in sql, "the nullable imputed figure must not reach a NOT NULL column"
+ for column in ("estimated_cost_usd", "estimated_call_count", "unpriced_call_count"):
+ assert column in sql, f"migration 063 adds {column} and this writer must use it"
+
+ def test_the_imputer_still_returns_none_for_an_unknown_model(self) -> None:
+ """Pinned. Making the imputer return 0.0 would 'fix' the crash by
+ publishing a price nobody charges — the exact defect migration 063
+ exists to prevent."""
+ from app.services.cost_dashboard import _impute_public_cost
+
+ assert _impute_public_cost("ollama/llama3.2:3b", 100, 100) is None
+
+
+# ─── The abort itself, which only PostgreSQL does ────────────────────────────
+#
+# SQLite does not abort a transaction on a constraint violation — the next
+# statement succeeds — so the assertions above exercise the savepoint
+# mechanics and cannot reproduce the defect. The defect is PostgreSQL's
+# "current transaction is aborted, commands ignored until end of transaction
+# block", and reproducing it needs PostgreSQL. Same arrangement as
+# `tests/isolation/test_postgres_rls.py`: skipped without a DSN locally, and
+# `POSTGRES_ABORT_SEMANTICS_REQUIRED=1` in CI turns the skip into a failure so
+# it cannot go quiet.
+
+#: The **owner** DSN, not the runtime one.
+#:
+#: The fixture below creates a scratch table, and the role the services
+#: connect as is DML-only so that row-level security applies to it — it
+#: answers `permission denied for schema public` on any DDL, which is the
+#: role split working as designed. `tests/isolation/test_postgres_rls.py`
+#: resolves the owner the same way, and falls back to the runtime DSN so a
+#: single-role deployment still runs.
+#:
+#: The property under test — PostgreSQL aborting a transaction on a statement
+#: error — does not depend on which role holds the connection.
+_DSN = os.environ.get("DATABASE_MIGRATION_URL", "").strip() or os.environ.get("DATABASE_URL", "")
+_REQUIRED = os.environ.get("POSTGRES_ABORT_SEMANTICS_REQUIRED", "").strip() not in ("", "0", "false")
+
+
+def _postgres_is_listening() -> bool:
+ """Whether something actually answers on the DSN's host and port.
+
+ Reading the DSN alone is not enough. The unit-test job exports a
+ `postgres://…localhost:5432` URL with no server behind it, so a
+ string check decided the test should run and it died on
+ `Connect call failed`. A DSN is a statement of intent; this asks.
+ """
+ parsed = urlparse(_DSN.replace("postgresql+asyncpg://", "postgresql://"))
+ if not parsed.hostname:
+ return False
+ try:
+ with socket.create_connection((parsed.hostname, parsed.port or 5432), timeout=2):
+ return True
+ except OSError:
+ return False
+
+
+#: `POSTGRES_ABORT_SEMANTICS_REQUIRED=1` still overrides, so integration.yml
+#: fails loudly rather than skipping if its Postgres is missing.
+_HAVE_POSTGRES = "postgres" in _DSN and _postgres_is_listening()
+
+
+ not _HAVE_POSTGRES and not _REQUIRED,
+ reason="needs a live Postgres — abort-on-error is a PostgreSQL behaviour and SQLite does not have it",
+)
+class TestPostgresAbortsTheWholeTransaction:
+ @pytest_asyncio.fixture
+ async def pg(self):
+ engine = create_async_engine(_DSN)
+ table = f"aisoc_abort_probe_{uuid.uuid4().hex[:8]}"
+ async with engine.begin() as conn:
+ await conn.execute(text(f"CREATE TABLE {table} (id TEXT PRIMARY KEY, name TEXT NOT NULL)"))
+ maker = async_sessionmaker(engine, expire_on_commit=False)
+ async with maker() as db:
+ yield db, table
+ async with engine.begin() as conn:
+ await conn.execute(text(f"DROP TABLE IF EXISTS {table}"))
+ await engine.dispose()
+
+ @pytest.mark.asyncio
+ async def test_an_unprotected_failure_poisons_everything_after_it(self, pg) -> None:
+ """The pre-fix arrangement, written out so the difference is visible.
+
+ A bare try/except around the failing statement. The exception is
+ caught, the caller carries on, and the *next* statement fails — which
+ is how a cost-tracking bug deleted an audit event.
+ """
+ db, table = pg
+ try:
+ await db.execute(text(f"INSERT INTO {table} (id, name) VALUES ('a', NULL)"))
+ except Exception: # noqa: BLE001 - the shape under test
+ pass
+
+ with pytest.raises(Exception, match="(?i)current transaction is aborted|InFailedSqlTransaction|PendingRollback"):
+ await db.execute(text(f"INSERT INTO {table} (id, name) VALUES ('b', 'the audit row')"))
+
+ @pytest.mark.asyncio
+ async def test_a_savepoint_confines_it(self, pg) -> None:
+ db, table = pg
+ _, exc = await attempt(db, lambda: db.execute(text(f"INSERT INTO {table} (id, name) VALUES ('a', NULL)")))
+ assert exc is not None
+
+ await db.execute(text(f"INSERT INTO {table} (id, name) VALUES ('b', 'the audit row')"))
+ await db.commit()
+ rows = (await db.execute(text(f"SELECT name FROM {table}"))).scalars().all()
+ assert rows == ["the audit row"]