artifactr.sql¶
The sql, postgres and sqlite extras. See SQL storage.
SQL storage: workspaces in PostgreSQL or SQLite, through SQLAlchemy 2's asyncio extension.
Install artifactr-ai[postgres] (asyncpg) or artifactr-ai[sqlite] (aiosqlite). Upgrade the
database with migrate, then open workspaces over a SqlStorage::
engine = create_async_engine("postgresql+asyncpg://localhost/app")
await migrate(engine)
workspaces = Workspaces(SqlStorage(engine))
For SQLite, create the engine with create_sqlite_engine. create_schema creates
the tables without migrations, for tests and prototypes. AdvisoryLock is PostgreSQL's
lock across processes, which a connected app's calls take turns by (ADR-0085).
Storage¶
SqlStorage
¶
SqlStorage(
engine: AsyncEngine,
*,
clock: Clock = _utc_now,
poll_interval: timedelta = timedelta(seconds=0.5),
row_level_security: bool = False,
)
Storage in a SQL database, through SQLAlchemy's asyncio extension.
Create the tables with migrate first. The same code runs on
PostgreSQL (with its default READ COMMITTED isolation) and on SQLite, whose engines
must come from create_sqlite_engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
AsyncEngine
|
The database to use. The storage does not dispose of it. |
required |
clock
|
Clock
|
Returns the current time, for envelope timestamps and lease expiry. Defaults to the system clock in UTC. |
_utc_now
|
poll_interval
|
timedelta
|
How often a subscription checks the log for envelopes committed by other processes. Commits made through this storage wake its subscriptions at once. |
timedelta(seconds=0.5)
|
row_level_security
|
bool
|
Whether each transaction names its tenant to PostgreSQL, whose
policies, which the migrations create, then show it only that tenant's rows
( |
False
|
transaction
async
¶
transaction(scope: Scope) -> AsyncGenerator[_Transaction]
Begin a transaction; it holds the workspace row's lock until it ends.
Closing the session rolls back whatever it did not commit, and returns its connection.
workspaces
async
¶
workspaces(
tenant_id: TenantId,
*,
after: WorkspaceId | None = None,
limit: int = 100,
) -> list[WorkspaceId]
Return a page of a tenant's workspaces with an event in their logs, by id.
artifact
async
¶
artifact(
scope: Scope, artifact_id: ArtifactId
) -> Versioned[Artifact] | None
Return an artifact's current version, or None.
artifacts
async
¶
artifacts(
scope: Scope,
*,
kind: str | None = None,
include_archived: bool = False,
) -> list[Versioned[Artifact]]
Return current artifacts, optionally of one kind, oldest first.
revisions
async
¶
revisions(
scope: Scope, artifact_id: ArtifactId
) -> list[Revision]
Return an artifact's revisions, oldest first.
drop_revisions
async
¶
drop_revisions(
scope: Scope,
artifact_id: ArtifactId,
versions: Collection[int],
) -> int
Forget some of an artifact's earlier revisions; never its current version.
In one transaction, a statement for each 500 versions, so no statement holds more parameters than a database takes.
proposal
async
¶
proposal(
scope: Scope, proposal_id: ProposalId
) -> Proposal | None
Return a proposal, or None.
proposals
async
¶
proposals(
scope: Scope,
*,
status: Literal["pending", "accepted", "rejected"]
| None = None,
) -> list[Proposal]
Return proposals, optionally with one status, oldest first.
runs
async
¶
runs(
scope: Scope,
*,
thread_id: ThreadId | None = None,
status: RunStatus | None = None,
) -> list[Run]
Return runs, optionally of one thread and with one status, oldest first.
read
async
¶
read(
scope: Scope,
*,
after_seq: int = 0,
before_seq: int | None = None,
threads: Collection[ThreadId] | None = None,
limit: int | None = None,
last: int | None = None,
) -> list[Envelope]
Return logged envelopes in the window after_seq < seq < before_seq, in order.
Of those delivered to threads, if given: the first limit or the last last.
The filter and both ends of the window are in the query, and the last are read
backwards from the end of the log.
subscribe
async
¶
subscribe(
scope: Scope, *, after_seq: int = 0
) -> AsyncGenerator[Envelope]
Yield stored envelopes after after_seq, then each new one as it commits.
New envelopes arrive at once when they were committed through this storage, and
within poll_interval otherwise.
history
async
¶
history(
scope: Scope, thread_id: ThreadId
) -> Sequence[HistoryChunk]
Return a thread's history chunks, in the order they were appended.
acquire_lease
async
¶
Take or renew an exclusive lease. Return False if another holder has it.
renew_lease
async
¶
Renew a lease only if holder still has it, expired or not; never take one.
release_lease
async
¶
Release a lease if holder has it.
lease
async
¶
Return who holds a lease and when it expires, or None if no one holds it now.
cursor
async
¶
Return how far a named consumer of the log has got: the seq saved, or 0.
Engines and schema¶
create_sqlite_engine
¶
Create an async SQLite engine whose transactions take turns.
Every transaction on the engine, reads included, holds the database's write lock, so
transactions run one at a time, on the engine's one connection. A transaction waits for the
connection for up to the engine's pool_timeout (30 seconds), and for another process's
lock for up to the timeout connect argument of Python's sqlite3 (5 seconds unless
connect_args says otherwise). Use a database file (or a shared-cache memory database).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str | URL
|
A SQLite URL for an async driver, such as |
required |
**kwargs
|
Any
|
Passed to SQLAlchemy's |
{}
|
Returns:
| Type | Description |
|---|---|
AsyncEngine
|
The engine. Dispose of it when you are done. |
migrate
async
¶
migrate(
engine: AsyncEngine,
*,
application_role: str | None = None,
) -> None
Upgrade the database to artifactr's latest schema, creating the tables if needed.
Run it when the application deploys or starts, as the tables' owner. It is safe to run on every start: a database that is already up to date is left alone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
AsyncEngine
|
The database, as the tables' owner. |
required |
application_role
|
str | None
|
A role that owns nothing, which the application connects as with row-level security on: it is granted artifactr's tables, on PostgreSQL. It must exist. |
None
|
create_schema
async
¶
A lock across processes¶
AdvisoryLock
¶
A PostgreSQL advisory lock for each key, held across the processes on one database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
AsyncEngine
|
PostgreSQL's engine, best one of its own: each waiter holds one of its connections. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the engine isn't PostgreSQL's. |
held
async
¶
held(key: str, *, wait: float) -> AsyncGenerator[None]
Hold the key's lock, waiting for whoever holds it, in any process, at most wait s.
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If it, or a connection for it, wasn't had within |
Row-level security¶
tenancy
¶
Row-level security: each transaction tells PostgreSQL its tenant (lattice RFC-0001).
With the option on, SqlStorage opens its sessions as
TenantSession, which sets SETTING to its tenant, for the transaction only, as
the transaction begins. The policies the migrations create on PostgreSQL then show each
transaction only its tenant's rows. A pooled connection never carries a
tenant into its next transaction, and a session that names no tenant can't begin one.
lattice-core holds the tenant session, the policy and the grants, which every library's SQL storage shares (lattice ADR-0018); this module re-exports them.
CURRENT
module-attribute
¶
CURRENT: Final = (
f"current_setting('{TENANT_SETTING}', true)"
)
The transaction's tenant, in SQL: null, or empty, when it names none, which no row's is.
TENANT
module-attribute
¶
TENANT: Final = 'tenant_id'
The key of a TenantSession's tenant in its info.
SETTING
module-attribute
¶
SETTING: Final = 'lattice.tenant_id'
The PostgreSQL setting that holds a transaction's tenant.
TenantSession
¶
Bases: Session
A session that tells PostgreSQL its tenant as each transaction begins.
It sets TENANT_SETTING to the tenant in its info. SQLite has no row-level security,
so there it sets nothing, but a session must still name its tenant.
grant
¶
grant(
connection: Connection,
role: str,
tables: Collection[str],
) -> None
Let a role use some tables as storage does, and their sequences, on PostgreSQL.
It grants the role USAGE on the current schema, reading and writing each table, and
USAGE on the sequences the tables own. Granting again changes nothing.
tenant_policy
¶
The DDL that keeps a table's rows to their tenant, on PostgreSQL.
table and column go into the DDL as they are, unquoted, unlike grant's role
and tables: pass only trusted identifiers, such as a model's own table name. The policy is
enabled, not forced, so the tables' owner isn't held by it. A transaction
sees, changes and adds only rows whose column is its tenant; one that names none, or an
empty one, sees nothing.