Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions openviking/observability/usage_audit/sqlite_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import asyncio
import json
import logging
import sqlite3
from datetime import date, datetime, time, timedelta, timezone, tzinfo
from pathlib import Path
Expand All @@ -21,9 +22,35 @@
from .projection import UsageAuditProjection, project_events, safe_int
from .schema import RESET_ON_SCHEMA_UPGRADE_TABLES, SCHEMA_VERSION, SQLITE_SCHEMA

logger = logging.getLogger(__name__)

UTC = timezone.utc


def _rollback_safely(conn: sqlite3.Connection, *, context: str) -> None:
"""Roll back the active transaction without masking the original error.

SQLite auto-rolls-back a transaction after certain fatal errors (e.g.
SQLITE_FULL / SQLITE_IOERR). By the time the ``except`` block runs there
is no transaction left, so a bare ``conn.execute("ROLLBACK")`` raises
``OperationalError: cannot rollback - no transaction is active`` and
replaces the underlying failure with a misleading secondary error.
Skip the rollback when nothing is active and never let rollback failures
shadow the exception being handled.
"""
if not conn.in_transaction:
logger.debug(
"Usage/Audit %s: transaction already auto-rolled-back by SQLite; "
"skipping explicit ROLLBACK",
context,
)
return
try:
conn.execute("ROLLBACK")
except sqlite3.Error as exc:
logger.warning("Usage/Audit %s: ROLLBACK failed: %s", context, exc)


def _date_range(start_date: str, end_date: str) -> Iterable[str]:
start = date.fromisoformat(start_date)
end = date.fromisoformat(end_date)
Expand Down Expand Up @@ -123,7 +150,7 @@ def _migrate_v4_to_v5_sync(conn: sqlite3.Connection) -> None:
conn.execute(f"ALTER TABLE request_audit ADD COLUMN {name} TEXT")
conn.execute("COMMIT")
except Exception:
conn.execute("ROLLBACK")
_rollback_safely(conn, context="v4->v5 migration")
raise

async def close(self) -> None:
Expand Down Expand Up @@ -158,7 +185,7 @@ def _delete_user_data_sync(self, account_id: str, user_id: str) -> dict[str, int
}
self._conn.execute("COMMIT")
except Exception:
self._conn.execute("ROLLBACK")
_rollback_safely(self._conn, context="delete_user_data")
raise
return deleted

Expand All @@ -183,7 +210,7 @@ def _record_projection_sync(self, projection: UsageAuditProjection) -> None:
self._trim_audit_rows(conn, projection.touched_audit_accounts)
conn.execute("COMMIT")
except Exception:
conn.execute("ROLLBACK")
_rollback_safely(conn, context="record_batch")
raise

@staticmethod
Expand Down
8 changes: 6 additions & 2 deletions openviking/observability/usage_audit/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,14 @@ async def _flush(self, batch: list[ObservabilityEvent]) -> None:
try:
await self._store.record_batch(batch)
except Exception as exc: # noqa: BLE001
# Always include the traceback: flush failures are rare and usually
# indicate storage-level faults whose root cause must survive in
# the logs for post-mortems (a bare message loses the origin).
logger.warning(
"Usage/Audit batch flush failed: %s",
"Usage/Audit batch flush failed (%d events): %s",
len(batch),
exc,
exc_info=logger.isEnabledFor(logging.DEBUG),
exc_info=True,
)

async def flush(self) -> None:
Expand Down
127 changes: 127 additions & 0 deletions tests/observability/test_usage_audit_rollback_resilience.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co. Ltd.
# SPDX-License-Identifier: AGPL-3.0
"""Rollback-resilience tests for the Usage/Audit SQLite store.

SQLite auto-rolls-back a transaction after certain fatal errors (SQLITE_FULL,
SQLITE_IOERR). The store's error paths used to issue a bare
``conn.execute("ROLLBACK")`` which then raised
``OperationalError: cannot rollback - no transaction is active`` and replaced
the underlying storage failure with a misleading secondary error (seen in
production as issue #4303). These tests pin the fixed behaviour: the original
exception must survive, and a still-active transaction must still be rolled
back.
"""

from __future__ import annotations

import asyncio
import sqlite3
from pathlib import Path

import pytest

from openviking.observability.usage_audit.projection import UsageAuditProjection
from openviking.observability.usage_audit.sqlite_store import SQLiteUsageAuditStore


def _make_store(tmp_path: Path) -> SQLiteUsageAuditStore:
store = SQLiteUsageAuditStore(tmp_path / "usage_audit.sqlite3")
asyncio.run(store.initialize())
return store


def _projection_with_token_row() -> UsageAuditProjection:
projection = UsageAuditProjection()
projection.token_rows[
("acct-1", "user-1", "2026-05-12", 1, "vlm", "input", "prov", "model")
] = 5
return projection


class _AutoRollbackInsertFailure:
"""Simulate a fatal SQLite write error that auto-rolled-back the txn."""

def __init__(self, *, auto_rollback: bool) -> None:
self.auto_rollback = auto_rollback

def __call__(self, conn, rows, updated_at): # signature of _write_token_rows
if self.auto_rollback:
conn.execute("ROLLBACK")
raise sqlite3.OperationalError("disk I/O error")


def test_record_batch_preserves_original_error_when_sqlite_auto_rolled_back(
tmp_path, monkeypatch
):
store = _make_store(tmp_path)
monkeypatch.setattr(
SQLiteUsageAuditStore,
"_write_token_rows",
staticmethod(_AutoRollbackInsertFailure(auto_rollback=True)),
)

with pytest.raises(sqlite3.OperationalError, match="disk I/O error"):
store._record_projection_sync(_projection_with_token_row())


def test_record_batch_still_rolls_back_active_transaction(tmp_path, monkeypatch):
store = _make_store(tmp_path)
conn = store._conn
assert conn is not None
monkeypatch.setattr(
SQLiteUsageAuditStore,
"_write_token_rows",
staticmethod(_AutoRollbackInsertFailure(auto_rollback=False)),
)

with pytest.raises(sqlite3.OperationalError, match="disk I/O error"):
store._record_projection_sync(_projection_with_token_row())

assert conn.in_transaction is False


def test_record_batch_recovers_after_transient_failure(tmp_path, monkeypatch):
store = _make_store(tmp_path)
monkeypatch.setattr(
SQLiteUsageAuditStore,
"_write_token_rows",
staticmethod(_AutoRollbackInsertFailure(auto_rollback=True)),
)

with pytest.raises(sqlite3.OperationalError, match="disk I/O error"):
store._record_projection_sync(_projection_with_token_row())

# A later batch must succeed on the same connection once the transient
# storage fault is gone — the failed path must not wedge the store.
monkeypatch.undo()
store._record_projection_sync(_projection_with_token_row())


class _DeleteFailingConn:
"""Connection proxy whose first DELETE simulates an auto-rollback fault."""

def __init__(self, conn: sqlite3.Connection) -> None:
self._conn = conn
self._failed = False

def execute(self, sql, *args):
if not self._failed and sql.lstrip().upper().startswith("DELETE"):
self._failed = True
self._conn.execute("ROLLBACK")
raise sqlite3.OperationalError("disk I/O error")
return self._conn.execute(sql, *args)

def __getattr__(self, name):
return getattr(self._conn, name)


def test_delete_user_data_preserves_original_error_when_sqlite_auto_rolled_back(tmp_path):
store = _make_store(tmp_path)
conn = store._conn
assert conn is not None
store._conn = _DeleteFailingConn(conn) # type: ignore[assignment]

with pytest.raises(sqlite3.OperationalError, match="disk I/O error"):
store._delete_user_data_sync("acct-1", "user-1")

assert conn.in_transaction is False