콘텐츠로 이동

spakky-sqlalchemy

SQLAlchemy 통합 - ORM, Repository, Transaction, Outbox Contribution

spakky-sqlalchemy는 spakky-data의 Repository/Transaction 계약을 SQLAlchemy engine과 session으로 구현하는 플러그인입니다. 처음 사용하는 경우에는 데이터베이스 가이드에서 도메인 Aggregate, ORM table, Repository, @Transactional() UseCase를 한 흐름으로 확인하세요.

Outbox storage/table은 base plugin 본체가 아니라 spakky.contributions.spakky.outbox contribution으로 등록됩니다. load_plugins(include=...) 사용 시 spakky-outbox와 spakky-sqlalchemy가 모두 include set에 있어야 이 contribution이 로드됩니다. 설치 시에는 spakky-outbox를 별도로 추가하거나 spakky-sqlalchemy[outbox] extra를 사용하세요.

멱등 소비의 처리 기록 저장소는 spakky.contributions.spakky.event contribution으로 등록됩니다. spakky-event와 spakky-sqlalchemy[event]를 함께 설치하고 두 plugin을 모두 active 상태로 로드하면 ProcessedEventTable(spakky_event_inbox)과 SqlAlchemyProcessedEventStore, AsyncSqlAlchemyProcessedEventStore가 등록됩니다.

Agent state/signal/evidence persistence도 base plugin 본체가 아니라 spakky.contributions.spakky.agent contribution으로 등록됩니다. Durable @Agent execution을 운영에서 사용하려면 spakky-agent와 spakky-sqlalchemy[agent]를 함께 설치하고 두 plugin을 모두 active 상태로 로드해야 합니다. 이 contribution은 SqlAlchemyAgentStateRepository, SqlAlchemyAgentSignalRepository, SqlAlchemyAgentEvidenceRepository, SqlAlchemyAgentTaskStore(ITaskStore)와 AgentStateTable, AgentSignalTable, AgentEvidenceTable, AgentConversationTurnTable을 등록합니다. 운영용 in-memory fallback은 제공하지 않습니다.

메인

initialize(app)

Initialize the SQLAlchemy plugin.

Registers SQLAlchemy configuration, schema registry, session managers, and transaction handlers. Async Pods are only registered when DataConfig.support_async_mode is True.

Parameters:

Name Type Description Default
app SpakkyApplication

The Spakky application instance.

required
Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/main.py
def initialize(app: SpakkyApplication) -> None:
    """Initialize the SQLAlchemy plugin.

    Registers SQLAlchemy configuration, schema registry, session managers,
    and transaction handlers. Async Pods are only registered when
    DataConfig.support_async_mode is True.

    Args:
        app: The Spakky application instance.
    """
    config = DataConfig()

    app.add(SQLAlchemyConnectionConfig)
    app.add(SchemaRegistry)

    app.add(ConnectionManager)
    app.add(SessionManager)
    app.add(Transaction)

    if config.support_async_mode:
        app.add(AsyncConnectionManager)
        app.add(AsyncSessionManager)
        app.add(AsyncTransaction)

설정

SQLAlchemyConnectionConfig()

Bases: BaseSettings

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/common/config.py
def __init__(self) -> None:
    super().__init__()

connection_string instance-attribute

SQLAlchemy database connection URL (e.g. postgresql+psycopg://user:pass@host/db).

sync_connection_string = None class-attribute instance-attribute

Optional synchronous driver URL for databases requiring separate drivers.

For example sqlite+aiosqlite for async access and sqlite+pysqlite for sync. Omitted preserves the base connection_string for dual-mode drivers.

echo = False class-attribute instance-attribute

If True, the engine logs all SQL statements to the default logger.

echo_pool = False class-attribute instance-attribute

If True, the connection pool logs all checkout/checkin events.

DEFAULT_POOL_SIZE = 5 class-attribute

Default number of connections in the pool.

DEFAULT_POOL_MAX_OVERFLOW = 10 class-attribute

Default maximum overflow connections.

DEFAULT_POOL_TIMEOUT = 30.0 class-attribute

Default seconds to wait when pool is exhausted.

DEFAULT_POOL_RECYCLE = -1 class-attribute

Default connection recycle time (-1 = disabled).

DEFAULT_POOL_PRE_PING = False class-attribute

Default pre-ping setting.

pool_size = DEFAULT_POOL_SIZE class-attribute instance-attribute

Number of connections to maintain persistently in the pool.

pool_max_overflow = DEFAULT_POOL_MAX_OVERFLOW class-attribute instance-attribute

Maximum number of connections that can be opened beyond pool_size.

pool_timeout = DEFAULT_POOL_TIMEOUT class-attribute instance-attribute

Seconds to wait before raising an error when the pool is exhausted.

pool_recycle = DEFAULT_POOL_RECYCLE class-attribute instance-attribute

Recycle connections after this many seconds to prevent stale connections. Recommended when connecting through a proxy or firewall with idle timeouts.

pool_pre_ping = DEFAULT_POOL_PRE_PING class-attribute instance-attribute

If True, tests each connection for liveness before returning it from the pool. Prevents errors caused by connections dropped by the database server.

async_pool_mode = 'queue' class-attribute instance-attribute

Async pooling strategy. Use null when one engine serves multiple event loops.

NullPool never shares a connection or asyncio queue between loops. Queue capacity settings are ignored in this mode; database/server limits still apply. The synchronous connection manager retains its ordinary pool.

session_autoflush = True class-attribute instance-attribute

If True, the session automatically flushes pending changes before queries.

session_expire_on_commit = True class-attribute instance-attribute

If True, ORM objects are expired after each commit, forcing a reload on next access.

autocommit = True class-attribute instance-attribute

If True, transactions are automatically committed after with statements. If False, transactions must be manually committed or rolled back.

ORM

VERSION_COLUMN_NAME = 'version' module-attribute

Column name that carries AbstractAggregateRoot.version in a mapped table.

AbstractTable

Bases: DeclarativeBase, AsyncAttrs

Base table class for SQLAlchemy ORM integration with Spakky.

Use this class for infrastructure tables that don't map to domain models (e.g., outbox tables, audit logs). For tables that map to domain entities, use AbstractMappableTable instead.

AbstractMappableTable

Bases: AbstractTable

Table class with domain object mapping support.

Use this class for tables that map to domain entities. Subclasses must implement from_domain() and to_domain() methods for bidirectional mapping.

optimistic_lock_mapper_args() classmethod

Build the mapper arguments that enable optimistic locking.

When the mapped domain type is an AbstractAggregateRoot and the table has a UUID-typed version column, that column becomes the mapper's version_id_col. The aggregate generates its own version, so SQLAlchemy only compares the stored value (version_id_generator=False) and never generates one.

Tables of child entities reached through relationships are left unversioned: only the aggregate root passes through a repository, which is where the loaded version is supplied.

A subclass that defines its own __mapper_args__ replaces the default as usual in SQLAlchemy declarative mapping.

Returns:

Type Description
dict[str, Any]

Mapper keyword arguments, empty when optimistic locking does not apply.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/orm/table.py
@classmethod
def optimistic_lock_mapper_args(
    cls,
) -> dict[str, Any]:  # Any: SQLAlchemy mapper kwargs
    """Build the mapper arguments that enable optimistic locking.

    When the mapped domain type is an `AbstractAggregateRoot` and the table
    has a UUID-typed `version` column, that column becomes the mapper's
    `version_id_col`. The aggregate generates its own version, so
    SQLAlchemy only compares the stored value
    (`version_id_generator=False`) and never generates one.

    Tables of child entities reached through relationships are left
    unversioned: only the aggregate root passes through a repository,
    which is where the loaded version is supplied.

    A subclass that defines its own `__mapper_args__` replaces the default
    as usual in SQLAlchemy declarative mapping.

    Returns:
        Mapper keyword arguments, empty when optimistic locking does not apply.
    """
    mappable = next(
        (
            type_
            for type_ in generic_mro(cls)
            if get_origin(type_) is AbstractMappableTable
        ),
        None,
    )
    domain: object = next(iter(get_args(mappable)), None)
    if not isinstance(domain, type) or not issubclass(
        domain, AbstractAggregateRoot
    ):
        return {}
    version_column = cls.__table__.columns.get(VERSION_COLUMN_NAME)
    if version_column is None or not cls.stores_domain_version(version_column):
        return {}
    return {"version_id_col": version_column, "version_id_generator": False}

stores_domain_version(column) staticmethod

Tell whether a column can hold AbstractAggregateRoot.version as is.

Only a column whose Python value type is UUID takes the aggregate's version without the table's own from_domain() conversion. Any other column (a string copy of the version, an integer revision counter, ...) belongs to the table author and is never written by the framework.

Parameters:

Name Type Description Default
column ColumnElement[Any]

Candidate version column.

required

Returns:

Type Description
bool

True if the column's Python type is UUID.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/orm/table.py
@staticmethod
def stores_domain_version(
    column: ColumnElement[Any],  # Any: column value type is what is inspected
) -> bool:
    """Tell whether a column can hold `AbstractAggregateRoot.version` as is.

    Only a column whose Python value type is `UUID` takes the aggregate's
    version without the table's own `from_domain()` conversion. Any other
    column (a string copy of the version, an integer revision counter, ...)
    belongs to the table author and is never written by the framework.

    Args:
        column: Candidate version column.

    Returns:
        True if the column's Python type is `UUID`.
    """
    try:
        return column.type.python_type is UUID
    except NotImplementedError:
        # The type does not declare a Python type, so it is not a UUID column.
        return False

SchemaRegistry()

Bases: ITagRegistryAware

Registry that maps domain types to SQLAlchemy table schemas.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/orm/schema_registry.py
def __init__(self) -> None:
    self._metadata = MetaData()
    self._domain_to_table_map = {}
    self._table_to_domain_map = {}

metadata property

Return MetaData containing only tables registered via @Table tag.

This filters out tables that were defined but not scanned by the SpakkyApplication, ensuring only application-scoped tables are included.

Returns:

Type Description
MetaData

MetaData with only @Table-tagged tables.

get_type(domain_type)

Look up the table class registered for the given domain type.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/orm/schema_registry.py
def get_type[AggregateRootT: AbstractAggregateRoot[Any]](
    self, domain_type: type[AggregateRootT]
) -> type[AbstractMappableTable[AggregateRootT]]:
    """Look up the table class registered for the given domain type."""
    table = self._domain_to_table_map.get(domain_type)
    if table is None:
        raise NoSchemaFoundFromDomainError(domain_type)
    return cast(type[AbstractMappableTable[AggregateRootT]], table)

from_domain(aggregate)

Convert a domain object to its corresponding table instance.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/orm/schema_registry.py
def from_domain[AggregateRootT: AbstractAggregateRoot[Any]](
    self, aggregate: AggregateRootT
) -> AbstractMappableTable[AggregateRootT]:
    """Convert a domain object to its corresponding table instance."""
    table: type[AbstractMappableTable[AggregateRootT]] | None = (
        self._domain_to_table_map.get(type(aggregate))
    )
    if table is None:
        raise NoSchemaFoundFromDomainError(aggregate)
    return table.from_domain(aggregate)

AbstractSpakkySqlAlchemyORMError

Bases: AbstractSpakkySqlAlchemyError, ABC

Base exception for Spakky SQLAlchemy ORM errors.

영속성

POSTGRESQL_UNIQUE_VIOLATION_SQLSTATE = '23505' module-attribute

SQLSTATE PostgreSQL drivers report for a unique or primary key violation.

SQLITE_UNIQUE_VIOLATION_ERROR_NAMES = frozenset({'SQLITE_CONSTRAINT_UNIQUE', 'SQLITE_CONSTRAINT_PRIMARYKEY'}) module-attribute

SQLite extended result code names for a unique or primary key violation.

INSERT_STATEMENT_PREFIX = 'INSERT' module-attribute

Leading keyword of the SQL statements that create rows.

CannotDetermineAggregateTypeError

Bases: AbstractSpakkySqlAlchemyPersistencyError

Raised when aggregate type cannot be resolved from generic parameters.

AbstractGenericRepository(session_manager, schema_registry, aggregate_collector)

Bases: IGenericRepository[AggregateRootT, AggregateIdT], ABC

Generic repository implementation for SQLAlchemy.

This class provides basic CRUD operations using SQLAlchemy sessions. It serves as a base class for specific entity repositories.

Resolve aggregate type from generic parameters and store dependencies.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/repository.py
def __init__(
    self,
    session_manager: SessionManager,
    schema_registry: SchemaRegistry,
    aggregate_collector: AggregateCollector,
) -> None:
    """Resolve aggregate type from generic parameters and store dependencies."""
    parameterized_base = next(
        (
            type_
            for type_ in generic_mro(type(self))
            if get_origin(type_) is AbstractGenericRepository
        ),
        None,
    )
    if parameterized_base is None:
        raise CannotDetermineAggregateTypeError(type(self))
    self._aggregate_type = next(iter(get_args(parameterized_base)))
    self._session_manager = session_manager
    self._schema_registry = schema_registry
    self._aggregate_collector = aggregate_collector

AbstractAsyncGenericRepository(session_manager, schema_registry, aggregate_collector)

Bases: IAsyncGenericRepository[AggregateRootT, AggregateIdT], ABC

Async generic repository implementation for SQLAlchemy.

This class provides basic CRUD operations using SQLAlchemy's async sessions. It serves as a base class for specific entity repositories that require async support.

Resolve aggregate type from generic parameters and store dependencies.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/repository.py
def __init__(
    self,
    session_manager: AsyncSessionManager,
    schema_registry: SchemaRegistry,
    aggregate_collector: AggregateCollector,
) -> None:
    """Resolve aggregate type from generic parameters and store dependencies."""
    parameterized_base = next(
        (
            type_
            for type_ in generic_mro(type(self))
            if get_origin(type_) is AbstractAsyncGenericRepository
        ),
        None,
    )
    if parameterized_base is None:
        raise CannotDetermineAggregateTypeError(type(self))
    self._aggregate_type = next(iter(get_args(parameterized_base)))
    self._session_manager = session_manager
    self._schema_registry = schema_registry
    self._aggregate_collector = aggregate_collector

Transaction(config, session_manager)

Bases: AbstractTransaction

SQLAlchemy synchronous transaction implementation.

Initialize with autocommit config and session manager.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
def __init__(
    self,
    config: SQLAlchemyConnectionConfig,
    session_manager: SessionManager,
) -> None:
    """Initialize with autocommit config and session manager."""
    super().__init__(autocommit=config.autocommit)
    self._session_manager = session_manager

initialize()

Open a new session bound to the new physical transaction.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
def initialize(self) -> None:
    """Open a new session bound to the new physical transaction."""
    self._session_manager.open(self.current_frame.transaction)

join()

Use the session of the joined physical transaction.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
def join(self) -> None:
    """Use the session of the joined physical transaction."""
    self._session_manager.join(self.current_frame.transaction)

leave()

Stop using the session of the joined physical transaction.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
def leave(self) -> None:
    """Stop using the session of the joined physical transaction."""
    self._session_manager.leave()

dispose()

Close the top session and return to the one below.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
def dispose(self) -> None:
    """Close the top session and return to the one below."""
    self._session_manager.close()

commit()

Commit the current session.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
def commit(self) -> None:
    """Commit the current session."""
    self._session_manager.session.commit()

rollback()

Roll back the current session.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
def rollback(self) -> None:
    """Roll back the current session."""
    self._session_manager.session.rollback()

AsyncTransaction(config, session_manager)

Bases: AbstractAsyncTransaction

SQLAlchemy asynchronous transaction implementation.

Initialize with autocommit config and async session manager.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
def __init__(
    self,
    config: SQLAlchemyConnectionConfig,
    session_manager: AsyncSessionManager,
) -> None:
    """Initialize with autocommit config and async session manager."""
    super().__init__(autocommit=config.autocommit)
    self._session_manager = session_manager

initialize() async

Open a new async session bound to the new physical transaction.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
async def initialize(self) -> None:
    """Open a new async session bound to the new physical transaction."""
    await self._session_manager.open(self.current_frame.transaction)

join() async

Use the async session of the joined physical transaction.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
async def join(self) -> None:
    """Use the async session of the joined physical transaction."""
    await self._session_manager.join(self.current_frame.transaction)

leave() async

Stop using the async session of the joined physical transaction.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
async def leave(self) -> None:
    """Stop using the async session of the joined physical transaction."""
    await self._session_manager.leave()

dispose() async

Close the top async session and return to the one below.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
async def dispose(self) -> None:
    """Close the top async session and return to the one below."""
    await self._session_manager.close()

commit() async

Commit the current async session.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
async def commit(self) -> None:
    """Commit the current async session."""
    await self._session_manager.session.commit()

rollback() async

Roll back the current async session.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/transaction.py
@override
async def rollback(self) -> None:
    """Roll back the current async session."""
    await self._session_manager.session.rollback()

SessionNotInitializedError

Bases: AbstractSpakkySqlAlchemyPersistencyError

Raised when trying to access a session that has not been initialized.

SessionNotBoundError

Bases: AbstractSpakkySqlAlchemyPersistencyError

Raised when a joined transaction has no session in the current context.

Every physical transaction opened through open() keeps its session on the context's stack, and a context that joins it inherited that stack. A missing session means join() was called for a transaction this session manager never opened.

SessionSlot(session, transaction) dataclass

The session of one physical transaction.

The slot is bound to the physical transaction that owns the session. The transaction object is shared by every execution context that copied the session stack, so the moment it finishes is seen at once by child tasks and threads that still hold the slot.

session instance-attribute

The session of the physical transaction.

transaction instance-attribute

The physical transaction this session belongs to.

SessionManager(connection_manager)

Bases: IApplicationContextAware

Manages synchronous SQLAlchemy sessions per execution context.

Each execution context keeps a stack of session slots that mirrors its transaction scopes. open() pushes a new session bound to a new physical transaction (the outermost scope or Propagation.REQUIRES_NEW) and close() pops and closes it. join() pushes the slot of the transaction a Propagation.REQUIRED scope joined and leave() pops it. session is the session of the top slot, that is, of the physical transaction the current scope belongs to.

The stack is an immutable tuple held in a ContextVar. A child task or thread that copied the execution context starts from the parent's stack, so it sees the parent's session, but the sessions it opens and closes stay in its own context and never replace the session another task is using. Once the transaction of the top slot has finished, session raises TransactionAlreadyFinishedError instead of handing out the session below it: a write never lands in a transaction other than the one its scope belongs to.

Initialize with engine from connection manager.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
def __init__(self, connection_manager: ConnectionManager) -> None:
    """Initialize with engine from connection manager."""
    self._engine = connection_manager.connection
    self._session_factory = None
    self._sessions = ContextVar("spakky_sqlalchemy_sessions", default=())

session property

The session of the physical transaction the current scope belongs to.

Raises:

Type Description
SessionNotInitializedError

No session is open in this context.

TransactionAlreadyFinishedError

That transaction has already committed or rolled back.

open(transaction)

Open a new session for a new physical transaction.

Parameters:

Name Type Description Default
transaction PhysicalTransaction

The physical transaction the session belongs to.

required
Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
def open(self, transaction: PhysicalTransaction) -> None:
    """Open a new session for a new physical transaction.

    Args:
        transaction: The physical transaction the session belongs to.
    """
    if self._session_factory is None:
        raise SessionNotInitializedError()
    self._sessions.set(
        (*self._sessions.get(), SessionSlot(self._session_factory(), transaction))
    )

join(transaction)

Use the session of a transaction a scope joined in this context.

Parameters:

Name Type Description Default
transaction PhysicalTransaction

The physical transaction joined by the scope.

required

Raises:

Type Description
SessionNotBoundError

This context holds no session of it.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
def join(self, transaction: PhysicalTransaction) -> None:
    """Use the session of a transaction a scope joined in this context.

    Args:
        transaction: The physical transaction joined by the scope.

    Raises:
        SessionNotBoundError: This context holds no session of it.
    """
    stack = self._sessions.get()
    for slot in reversed(stack):
        if slot.transaction is transaction:
            self._sessions.set((*stack, slot))
            return
    raise SessionNotBoundError()

leave()

Stop using the session pushed by join().

Raises:

Type Description
SessionNotInitializedError

No session is open in this context.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
def leave(self) -> None:
    """Stop using the session pushed by ``join()``.

    Raises:
        SessionNotInitializedError: No session is open in this context.
    """
    stack = self._sessions.get()
    if not stack:
        raise SessionNotInitializedError()
    self._sessions.set(stack[:-1])

close()

Close the top session of the current context and return to the one below.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
def close(self) -> None:
    """Close the top session of the current context and return to the one below."""
    if self._session_factory is None:
        return
    stack = self._sessions.get()
    if not stack:
        return
    self._sessions.set(stack[:-1])
    stack[-1].session.close()

AsyncSessionManager(connection_manager)

Bases: IApplicationContextAware

Manages asynchronous SQLAlchemy sessions per execution context.

Each execution context keeps a stack of session slots that mirrors its transaction scopes. open() pushes a new session bound to a new physical transaction (the outermost scope or Propagation.REQUIRES_NEW) and close() pops and closes it. join() pushes the slot of the transaction a Propagation.REQUIRED scope joined and leave() pops it. session is the session of the top slot, that is, of the physical transaction the current scope belongs to.

The stack is an immutable tuple held in a ContextVar. A child task or thread that copied the execution context starts from the parent's stack, so it sees the parent's session, but the sessions it opens and closes stay in its own context and never replace the session another task is using. Once the transaction of the top slot has finished, session raises TransactionAlreadyFinishedError instead of handing out the session below it: a write never lands in a transaction other than the one its scope belongs to.

Initialize with engine from async connection manager.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
def __init__(self, connection_manager: AsyncConnectionManager) -> None:
    """Initialize with engine from async connection manager."""
    self._engine = connection_manager.connection
    self._session_factory = None
    self._sessions = ContextVar("spakky_sqlalchemy_async_sessions", default=())

session property

The session of the physical transaction the current scope belongs to.

Raises:

Type Description
SessionNotInitializedError

No session is open in this context.

TransactionAlreadyFinishedError

That transaction has already committed or rolled back.

open(transaction) async

Open a new async session for a new physical transaction.

Parameters:

Name Type Description Default
transaction PhysicalTransaction

The physical transaction the session belongs to.

required
Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
async def open(self, transaction: PhysicalTransaction) -> None:
    """Open a new async session for a new physical transaction.

    Args:
        transaction: The physical transaction the session belongs to.
    """
    if self._session_factory is None:
        raise SessionNotInitializedError()
    self._sessions.set(
        (*self._sessions.get(), SessionSlot(self._session_factory(), transaction))
    )

join(transaction) async

Use the session of a transaction a scope joined in this context.

Parameters:

Name Type Description Default
transaction PhysicalTransaction

The physical transaction joined by the scope.

required

Raises:

Type Description
SessionNotBoundError

This context holds no session of it.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
async def join(self, transaction: PhysicalTransaction) -> None:
    """Use the session of a transaction a scope joined in this context.

    Args:
        transaction: The physical transaction joined by the scope.

    Raises:
        SessionNotBoundError: This context holds no session of it.
    """
    stack = self._sessions.get()
    for slot in reversed(stack):
        if slot.transaction is transaction:
            self._sessions.set((*stack, slot))
            return
    raise SessionNotBoundError()

leave() async

Stop using the session pushed by join().

Raises:

Type Description
SessionNotInitializedError

No session is open in this context.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
async def leave(self) -> None:
    """Stop using the session pushed by ``join()``.

    Raises:
        SessionNotInitializedError: No session is open in this context.
    """
    stack = self._sessions.get()
    if not stack:
        raise SessionNotInitializedError()
    self._sessions.set(stack[:-1])

close() async

Close the top async session of the current context and return to the one below.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/session_manager.py
async def close(self) -> None:
    """Close the top async session of the current context and return to the one below."""
    if self._session_factory is None:
        return
    stack = self._sessions.get()
    if not stack:
        return
    self._sessions.set(stack[:-1])
    await stack[-1].session.close()

Connection managers for SQLAlchemy engines.

This module provides connection managers that handle SQLAlchemy engine lifecycle, including proper disposal on application shutdown.

ConnectionManager(config)

Manages synchronous SQLAlchemy engine lifecycle.

Create a synchronous SQLAlchemy engine from configuration.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/connection_manager.py
def __init__(self, config: SQLAlchemyConnectionConfig) -> None:
    """Create a synchronous SQLAlchemy engine from configuration."""
    self._connection = create_engine(
        url=config.sync_connection_string or config.connection_string,
        echo=config.echo,
        echo_pool=config.echo_pool,
        pool_size=config.pool_size,
        max_overflow=config.pool_max_overflow,
        pool_timeout=config.pool_timeout,
        pool_recycle=config.pool_recycle,
        pool_pre_ping=config.pool_pre_ping,
    )

connection property

Get the SQLAlchemy Engine instance.

dispose()

Dispose the engine connection pool.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/connection_manager.py
def dispose(self) -> None:
    """Dispose the engine connection pool."""
    self._connection.dispose()

AsyncConnectionManager(config)

Bases: IAsyncService

Manages asynchronous SQLAlchemy engine lifecycle.

NullPool mode initializes the dialect before ApplicationContext startup completes, so concurrent loops cannot race its first-connect asyncio lock. Queue mode retains caller-owned disposal on the loop that owns connections; its lifecycle hooks intentionally do not open or dispose connections.

Create an asynchronous SQLAlchemy engine from configuration.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/connection_manager.py
def __init__(self, config: SQLAlchemyConnectionConfig) -> None:
    """Create an asynchronous SQLAlchemy engine from configuration."""
    self._use_null_pool = config.async_pool_mode == "null"
    if self._use_null_pool:
        self._connection = create_async_engine(
            url=config.connection_string,
            echo=config.echo,
            echo_pool=config.echo_pool,
            poolclass=NullPool,
            pool_recycle=config.pool_recycle,
            pool_pre_ping=config.pool_pre_ping,
        )
        return
    self._connection = create_async_engine(
        url=config.connection_string,
        echo=config.echo,
        echo_pool=config.echo_pool,
        pool_size=config.pool_size,
        max_overflow=config.pool_max_overflow,
        pool_timeout=config.pool_timeout,
        pool_recycle=config.pool_recycle,
        pool_pre_ping=config.pool_pre_ping,
    )

connection property

Get the async SQLAlchemy Engine instance.

set_stop_event(stop_event)

No polling loop: lifecycle hooks handle connection initialization.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/connection_manager.py
@override
def set_stop_event(self, stop_event: locks.Event) -> None:
    """No polling loop: lifecycle hooks handle connection initialization."""

start_async() async

Initialize NullPool's dialect before multiple loops can use it.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/connection_manager.py
@override
async def start_async(self) -> None:
    """Initialize NullPool's dialect before multiple loops can use it."""
    if self._use_null_pool:
        async with self._connection.connect() as connection:
            await connection.execute(select(1))

stop_async() async

Dispose NullPool; QueuePool remains owned by its requesting loop.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/connection_manager.py
@override
async def stop_async(self) -> None:
    """Dispose NullPool; QueuePool remains owned by its requesting loop."""
    if self._use_null_pool:
        await self.dispose()

dispose() async

Dispose the engine connection pool.

Must be called from the same event loop where connections were used.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/persistency/connection_manager.py
async def dispose(self) -> None:
    """Dispose the engine connection pool.

    Must be called from the same event loop where connections were used.
    """
    await self._connection.dispose()

AbstractSpakkySqlAlchemyPersistencyError

Bases: AbstractSpakkySqlAlchemyError, ABC

Base exception for Spakky SQLAlchemy persistency errors.

Outbox

SQLAlchemy contribution for the spakky-outbox feature.

initialize(app)

Register SQLAlchemy-backed Outbox infrastructure.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/contributions/outbox.py
def initialize(app: SpakkyApplication) -> None:
    """Register SQLAlchemy-backed Outbox infrastructure."""
    config = DataConfig()

    app.add(OutboxMessageTable)
    app.add(SqlAlchemyOutboxStorage)

    if config.support_async_mode:
        app.add(AsyncSqlAlchemyOutboxStorage)

SQLAlchemy implementation of IOutboxStorage / IAsyncOutboxStorage.

SqlAlchemyOutboxStorage(session_manager, connection_manager, config=None)

Bases: IOutboxStorage

Synchronous SQLAlchemy-based Outbox storage implementation.

  • save(): uses the current transactional session (same TX as business data).
  • fetch_pending/mark_published/increment_retry/mark_abandoned/ release_claim/purge_published: use independent sessions.
Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
def __init__(
    self,
    session_manager: SessionManager,
    connection_manager: ConnectionManager,
    config: OutboxConfig | None = None,
) -> None:
    self._session_manager = session_manager
    self._session_factory = sessionmaker(
        bind=connection_manager.connection,
        expire_on_commit=False,
    )
    self._claim_timeout_seconds = (
        config.claim_timeout_seconds if config else _DEFAULT_CLAIM_TIMEOUT_SECONDS
    )

__claimable_ids(session, candidates) staticmethod

Drop candidates whose partition key is headed by another instance.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
@staticmethod
def __claimable_ids(
    session: Session,
    candidates: Sequence[OutboxMessageTable],
) -> list[UUID]:
    """Drop candidates whose partition key is headed by another instance."""
    partition_keys = {
        row.partition_key for row in candidates if row.partition_key is not None
    }
    if not partition_keys:
        return [row.id for row in candidates]

    heads = session.execute(
        _partition_key_head_ids().where(
            OutboxMessageTable.partition_key.in_(partition_keys)
        )
    ).all()
    headed_elsewhere = _keys_headed_elsewhere(heads, candidates)
    return [
        row.id for row in candidates if row.partition_key not in headed_elsewhere
    ]

release_claim(message)

Clear this relay's claim of an unpublished message in an independent session.

The row is updated only while claimed_at still equals the claim that fetch_pending returned, so a newer claim by another instance stays. A published or abandoned row keeps its claim; it is not pending any more.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
@override
def release_claim(self, message: OutboxMessage) -> None:
    """Clear this relay's claim of an unpublished message in an independent session.

    The row is updated only while `claimed_at` still equals the claim that
    `fetch_pending` returned, so a newer claim by another instance stays.
    A published or abandoned row keeps its claim; it is not pending any more.
    """
    with self._session_factory() as session:
        session.execute(
            update(OutboxMessageTable)
            .where(OutboxMessageTable.id == message.id)
            .where(OutboxMessageTable.claimed_at == message.claimed_at)
            .where(_awaiting_delivery(OutboxMessageTable))
            .values(claimed_at=None)
        )
        session.commit()

purge_published(older_than)

Delete published rows older than older_than in an independent session.

published_at is NULL for pending and abandoned rows, so they stay.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
@override
def purge_published(self, older_than: datetime) -> int:
    """Delete published rows older than `older_than` in an independent session.

    `published_at` is NULL for pending and abandoned rows, so they stay.
    """
    with self._session_factory() as session:
        result = session.execute(
            delete(OutboxMessageTable).where(
                OutboxMessageTable.published_at.is_not(None),
                OutboxMessageTable.published_at < older_than,
            )
        )
        session.commit()
        return self._deleted(result)

AsyncSqlAlchemyOutboxStorage(session_manager, connection_manager, config=None)

Bases: IAsyncOutboxStorage

Asynchronous SQLAlchemy-based Outbox storage implementation.

  • save(): uses the current transactional session (same TX as business data).
  • fetch_pending/mark_published/increment_retry/mark_abandoned/ release_claim/purge_published: use independent sessions.
Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
def __init__(
    self,
    session_manager: AsyncSessionManager,
    connection_manager: AsyncConnectionManager,
    config: OutboxConfig | None = None,
) -> None:
    self._session_manager = session_manager
    self._session_factory = async_sessionmaker(
        bind=connection_manager.connection,
        expire_on_commit=False,
    )
    self._claim_timeout_seconds = (
        config.claim_timeout_seconds if config else _DEFAULT_CLAIM_TIMEOUT_SECONDS
    )

__claimable_ids(session, candidates) async staticmethod

Drop candidates whose partition key is headed by another instance.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
@staticmethod
async def __claimable_ids(
    session: AsyncSession,
    candidates: Sequence[OutboxMessageTable],
) -> list[UUID]:
    """Drop candidates whose partition key is headed by another instance."""
    partition_keys = {
        row.partition_key for row in candidates if row.partition_key is not None
    }
    if not partition_keys:
        return [row.id for row in candidates]

    heads = (
        await session.execute(
            _partition_key_head_ids().where(
                OutboxMessageTable.partition_key.in_(partition_keys)
            )
        )
    ).all()
    headed_elsewhere = _keys_headed_elsewhere(heads, candidates)
    return [
        row.id for row in candidates if row.partition_key not in headed_elsewhere
    ]

release_claim(message) async

Clear this relay's claim of an unpublished message in an independent session.

The row is updated only while claimed_at still equals the claim that fetch_pending returned, so a newer claim by another instance stays. A published or abandoned row keeps its claim; it is not pending any more.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
@override
async def release_claim(self, message: OutboxMessage) -> None:
    """Clear this relay's claim of an unpublished message in an independent session.

    The row is updated only while `claimed_at` still equals the claim that
    `fetch_pending` returned, so a newer claim by another instance stays.
    A published or abandoned row keeps its claim; it is not pending any more.
    """
    async with self._session_factory() as session:
        await session.execute(
            update(OutboxMessageTable)
            .where(OutboxMessageTable.id == message.id)
            .where(OutboxMessageTable.claimed_at == message.claimed_at)
            .where(_awaiting_delivery(OutboxMessageTable))
            .values(claimed_at=None)
        )
        await session.commit()

purge_published(older_than) async

Delete published rows older than older_than in an independent session.

published_at is NULL for pending and abandoned rows, so they stay.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/outbox/storage.py
@override
async def purge_published(self, older_than: datetime) -> int:
    """Delete published rows older than `older_than` in an independent session.

    `published_at` is NULL for pending and abandoned rows, so they stay.
    """
    async with self._session_factory() as session:
        result = await session.execute(
            delete(OutboxMessageTable).where(
                OutboxMessageTable.published_at.is_not(None),
                OutboxMessageTable.published_at < older_than,
            )
        )
        await session.commit()
        return self._deleted(result)

SQLAlchemy table definition for the Outbox pattern.

OutboxMessageTable

Bases: AbstractTable

Outbox message table for transactional outbox pattern.

This is an infrastructure table that doesn't map to a domain model, so it inherits from AbstractTable (not AbstractMappableTable).

Agent Persistence

SQLAlchemy contribution for the spakky-agent feature.

initialize(app)

Register SQLAlchemy-backed agent persistence infrastructure.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/contributions/agent.py
def initialize(app: SpakkyApplication) -> None:
    """Register SQLAlchemy-backed agent persistence infrastructure."""
    app.add(AgentStateTable)
    app.add(AgentSignalTable)
    app.add(AgentEvidenceTable)
    app.add(AgentEvidenceOriginTable)
    app.add(AgentConversationTurnTable)
    app.add(SqlAlchemyAgentStateRepository)
    app.add(SqlAlchemyAgentSignalRepository)
    app.add(SqlAlchemyAgentEvidenceRepository)
    app.add(SqlAlchemyAgentTaskStore)

SQLAlchemy repository implementations for spakky-agent contracts.

UNCOMMITTED_SIGNALS_KEY = 'spakky.agent.uncommitted_signals' module-attribute

Session.info key holding signals appended in still-open transactions.

SqlAlchemyAgentStateRepository(session_manager)

Bases: IAgentStateRepository

SQLAlchemy materialized state repository for agent executions.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/agent/repository.py
def __init__(self, session_manager: SessionManager) -> None:
    self._session_manager = session_manager

SqlAlchemyAgentSignalRepository(session_manager, publisher=None)

Bases: IAgentSignalRepository

SQLAlchemy durable signal ledger that publishes rows after commit.

append only stages the ledger row against the transaction (or savepoint) that wrote it. When a live publisher is wired, staged signals are published only when the outermost transaction commits. Rolling back a savepoint discards just the rows written inside it, and ending the outermost transaction without commit (rollback or close()) discards the rest, so a running agent is never woken for a signal that did not durably commit.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/agent/repository.py
def __init__(
    self,
    session_manager: SessionManager,
    publisher: IAgentSignalPublisher | None = None,
) -> None:
    self._session_manager = session_manager
    self._publisher = publisher
    # Bound once so SQLAlchemy can recognize an already registered listener.
    self._after_commit = self._publish_committed
    self._after_soft_rollback = self._discard_rolled_back
    self._after_transaction_end = self._discard_unfinished

SqlAlchemyAgentEvidenceRepository(session_manager)

Bases: IAgentEvidenceRepository

SQLAlchemy append-only repository for agent evidence artifacts.

Context origin references are indexed so a source erasure can find every run that read the source.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/agent/repository.py
def __init__(self, session_manager: SessionManager) -> None:
    self._session_manager = session_manager

SqlAlchemyAgentTaskStore(session_manager)

Bases: ITaskStore

SQLAlchemy conversation-history store keyed by conversation_id.

Turns are appended after the last stored position of the conversation and read back in that order. When two writers append to one conversation at the same time, the unique (conversation_id, position) constraint lets only one of them succeed; the other fails with AgentConversationAppendConflictError instead of interleaving turns.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/agent/repository.py
def __init__(self, session_manager: SessionManager) -> None:
    self._session_manager = session_manager

SQLAlchemy schema mappings for spakky-agent persistence contracts.

AgentStateTable

Bases: AbstractMappableTable[AgentState]

Materialized state table for durable agent executions.

AgentSignalTable

Bases: AbstractMappableTable[AgentSignal]

Durable inbound signal queue table for agent executions.

AgentEvidenceTable

Bases: AbstractMappableTable[AgentEvidence]

Append-only evidence table for agent execution artifacts.

restore(origin_refs)

Rebuild the evidence with its origin index rows.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/agent/table.py
def restore(self, origin_refs: tuple[str, ...]) -> AgentEvidence:
    """Rebuild the evidence with its origin index rows."""
    return AgentEvidence(
        id=self.id,
        agent_state_id=self.agent_state_id,
        kind=AgentEvidenceKind(self.kind),
        payload=self.payload,
        model_step=self.model_step,
        origin_refs=origin_refs,
        summary=self.summary,
        digest=self.digest,
        manifest_ref=self.manifest_ref,
        reference=self.reference,
        created_at=self.created_at,
    )

AgentEvidenceOriginTable

Bases: AbstractTable

Index from a context source reference to the evidence that used it.

AgentConversationTurnTable

Bases: AbstractTable

Append-only transcript table for server-side agent conversations.

A turn is identified inside its conversation by position. The unique constraint keeps two writers from storing the same position, so a transcript can never be reordered or interleaved silently.

to_turn()

Rebuild the conversation turn stored in this row.

Source code in plugins/spakky-sqlalchemy/src/spakky/plugins/sqlalchemy/agent/table.py
def to_turn(self) -> ConversationTurn:
    """Rebuild the conversation turn stored in this row."""
    return ConversationTurn(
        role=ModelMessageRole(self.role),
        content=self.content,
        metadata=self.metadata_json,
    )

에러

AbstractSpakkySqlAlchemyError

Bases: AbstractSpakkyFrameworkError, ABC

Base exception for Spakky SQLAlchemy errors.

추가 모듈

Errors for SQLAlchemy-backed agent persistence.

AgentPersistenceRowNotFoundError

Bases: AbstractSpakkySqlAlchemyPersistencyError

Raised when an agent persistence row cannot be found.

AgentSignalTransactionMissingError

Bases: AbstractSpakkySqlAlchemyPersistencyError

Raised when a staged agent signal has no transaction to commit with.

AgentConversationAppendConflictError

Bases: AbstractSpakkySqlAlchemyPersistencyError

Raised when another writer appended to the same conversation first.