Alopex Python バインディング
Python から AlopexDB を操作するためのバインディングです。
Database/Transaction の基本機能に加え、ベクトル検索(numpy)と Unity Catalog 互換の Catalog API(polars)を提供します。
インストール
pip install alopex
Catalog API (polars) を使う場合:
pip install alopex[polars]
開発テストでは、ファイル名と行番号を保つ軽量デバッグ情報のdev profileで maturin を利用できます。
maturin develop -m crates/alopex-py/Cargo.toml
オプション依存:
- numpy を使う場合:
pip install alopex[numpy] - polars を使う場合:
pip install alopex[polars]
対応バージョン
| 依存関係 | 対応バージョン |
|---|---|
| Python | 3.8+ |
| Polars | 0.20+ (Catalog API) |
| NumPy | 1.20+ (Vector API) |
基本的な使い方
Database / Transaction
from alopex import Database, TxnMode
db = Database.new()
with db.begin(TxnMode.READ_WRITE) as txn:
txn.put(b"user:1", b"alice")
txn.commit()
with db.begin(TxnMode.READ_ONLY) as txn:
value = txn.get(b"user:1")
print(value)
db.close()
組み込み Database.execute_sql() は auto-commit です。SQL の BEGIN や SAVEPOINT を渡す代わりに、明示トランザクションのメソッドを使います。保存点メソッドは組み込み Transaction と AsyncTransaction で利用できます。
with db.begin(TxnMode.READ_WRITE) as txn:
txn.execute_sql("INSERT INTO orders (id) VALUES (1)")
txn.savepoint("before_optional_item")
txn.execute_sql("INSERT INTO orders (id) VALUES (2)")
txn.rollback_to("before_optional_item")
txn.release("before_optional_item")
txn.commit()
サーバー接続(v0.8.8)
alopex.connect(target) は接続先の指定だけで組み込み↔サーバーを切り替えます。
戻り値の形は両サーフェスで一致します(SELECT は列順を保った list[dict]、DML は
int、DDL は None)。
import alopex
embedded = alopex.connect("/var/lib/alopex/db") # 組み込み Database
remote = alopex.connect("https://127.0.0.1:8080", # RemoteDatabase
api_key="secret")
for db in (embedded, remote):
db.execute_sql("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)")
db.execute_sql("INSERT INTO items (id, name) VALUES (?, ?)", [1, "alpha"])
assert db.execute_sql("SELECT id, name FROM items") == [{"id": 1, "name": "alpha"}]
with remote.begin() as txn: # サーバーセッション(/session/begin)
txn.execute_sql("INSERT INTO items (id, name) VALUES (2, 'beta')")
txn.commit()
remote.close()
組み込みDatabaseでは、繰り返し実行する1文をprepare()できます。bind indexは
1-basedで、?だけを受け付けます。
statement = embedded.prepare("INSERT INTO items (id, name) VALUES (?, ?)")
statement.bind(1, 2)
statement.bind(2, "beta")
statement.execute()
statement.reset()
statement.finalize()
Database.prepareが返すPreparedStatement.execute_many(rows)は、None / bool / number / text /
vector の行を1 transactionで実行します。各行は list または tuple にし、途中の行が
失敗した場合は先行行も rollback されます。
batch = embedded.prepare("INSERT INTO items (id, name) VALUES (?, ?)")
assert batch.execute_many([(3, "gamma"), (4, "delta")]) == [1, 1]
Transaction.prepare(sql)も同じPreparedStatement型を返します。handleは元の
transactionで実行し、自動commitしません。Transaction.execute_many(sql, rows)は
同じbatch経路の簡略形です。SQLは単一の非制御文、値はnative scalar/vectorに限ります。
Decimal/datetimeの文字列展開へのfallbackは行いません。
Transaction-owned batchの実行エラーはtransactionをfailedにします。呼出元は明示的に rollbackするか、呼出前に作成したsavepointへrollback_toしてください。batchだけを自動で 巻き戻す保証はありません。commitを試してnative失敗した場合、handleはrolled_back状態へ 移り、再rollbackは不要です。型・個数のpreflight拒否はSQL書込前に発生します。
元transactionのcommit/rollback/dropまたはDatabase.close後は、prepared handleの bind/reset/parameter_count/execute/execute_manyも拒否されます。finalizeは終了後も可能で、 自身のowner参照だけを解放します(2回目はエラー)。元transactionのdropは従来どおりrollback し、prepared handleが生きていてもtransactionを延命しません。active stream中の実行は拒否され、 全消費後は再実行できます。途中closeしたstreamはrollbackを必要とします。
| target | 結果 |
|---|---|
http://host:port / https://host:port |
RemoteDatabase |
:memory:(既定) |
Database.open_in_memory() |
file:///path/db / /path/db |
Database.open(path) |
s3://bucket/prefix |
NotImplementedError(ALOPEX-PY204) |
| その他 | ValueError(ALOPEX-PY205) |
RemoteDatabase の主なオプション:
| オプション | 既定 | 説明 |
|---|---|---|
api_key |
None |
x-api-key ヘッダ。headers で Authorization: Bearer も可 |
timeout |
60.0 |
サーバー既定 query_timeout(30s)の 2 倍。サーバー側の分類済みエラーを優先させる |
sql_path / api_prefix |
URL の path 由来 | /api/sql/query も同一ハンドラ |
ssl_context |
None |
ssl.create_default_context() の差し替え(mTLS もここ) |
insecure |
False |
非 loopback への平文 http:// を許可する場合に必須 |
retries |
0 |
接続確立の失敗だけを再試行。送信済みリクエストは絶対に再送しない |
keep_alive / idle_reconnect_seconds |
True / 5.0 |
1 インスタンス 1 コネクション。並列実行はスレッドごとにインスタンスを作る |
サーバーに等価物が無い操作は AttributeError ではなく理由付きの
NotImplementedError(code == "ALOPEX-PY204")になります: execute_sql_stream /
query_stream / flush / memory_usage / routing_diagnostics / thread_mode /
HNSW 系 / トランザクションの KV・ベクトル系 / begin(TxnMode.READ_ONLY)。
cluster_status() は実装済みで、組み込みと同じ ClusterStatusSnapshot を返します。
エラーコードはサーバーの安定コード(UNAUTHORIZED / QUERY_TIMEOUT /
SESSION_EXPIRED / ALOPEX-E### ほか)をそのまま AlopexError.code に載せ、
.correlation_id と .http_status も付きます。例外型は両サーフェスで一致し、
実行中に起きるエラー(CAST 失敗 = ALOPEX-E004 など)は安定コードも一致します。
ただしパース・カタログ・型検査のエラーはサーバー側のルーティング前段で
ALOPEX-E999 に潰れます(本来のコードはメッセージ内にのみ残る)。これは CLI の
HTTP 経路でも同じサーバー側の既知の問題で、詳細と追跡は
docs/python-server-client.md の D20 を参照してください。クライアント固有は
ALOPEX-PY201(接続失敗)/ ALOPEX-PY202(タイムアウト)/ ALOPEX-PY203
(プロトコル違反)/ ALOPEX-PY204(サーバーに等価物なし)/ ALOPEX-PY205
(不正な接続先・オプション)の 5 つです。閉じたハンドルの操作は組み込みと同じ
AlopexError("database is closed") + ALOPEX-PY999 です。
サーバーセッションはサーバーの session_ttl(既定 300 秒)で失効し、
SESSION_EXPIRED として観測されます(組み込みトランザクションには TTL がありません)。
詳細は docs/python-server-client.md を参照してください。
v0.8 embedded-local stream / DataFrame API
v0.8 の stream API は embedded-local database 専用です。remote session(サーバー
セッション)は RemoteDatabase.begin() で利用できますが、stream・remote
DataFrame execution は引き続き提供しません(サーバーの JSONL ストリームは列名
メタデータを持たないため、組み込みの dict yield 契約を満たせません)。Database は既定で thread_mode="multi" であり、
thread_mode="single" を選ぶと database、transaction、stream、DataFrame、LazyFrame は作成した
Python thread だけで使用できます。
同期 SQL / scan stream
execute_sql_stream() は、単一 table の local SELECT、row-local WHERE、projection、LIMIT /
OFFSET の documented subset を一行ずつ返します。query_stream() は LocalScan.table、csv、
parquet、columnar_segment、lazyframe の五つだけを受け取ります。非対応 SQL、callback、remote
source は stream を開く前に AlopexError となります。
from alopex import Database, LocalScan
db = Database.new()
db.execute_sql("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
db.execute_sql("INSERT INTO users (id, name) VALUES (1, 'one'), (2, 'two')")
with db.execute_sql_stream(
"SELECT id, name FROM users WHERE id >= 1",
resource_limit_bytes=64 * 1024 * 1024,
timeout=5.0,
) as stream:
for row in stream:
print(row)
print(stream.status)
# {"terminal": "exhausted", "rows_delivered": 2,
# "resource_limit_bytes": ..., "resource_scope": "sql_row",
# "transaction_effect": "none"}
DataFrameStream.status は同じ構造で、rows_delivered の代わりに
batches_delivered、resource_scope="dataframe_batch" を返します。normal exhaustion は以後
end-of-stream、close/cancel/timeout/failure は以後も同じ識別可能な terminal error を返します。
transaction 内の stream は暗黙 commit しません。正常に exhaustion した read stream は commit 可能であり、
early close、cancel、failure は transaction.status["stream_effect"] と stream の
transaction_effect で確認した後に rollback してください。active stream 中の commit は拒否されます。
Python DataFrame streaming / expressions
LazyFrame.collect_batches() は Phase 3 と同じ source、row order、schema、NULL、resource
contract で有限 DataFrame batch を返します。concat、concat_str、select、filter、
with_columns は同じ expression semantics を使用します。
from alopex import DataFrame, col, concat_str, lit
plan = (
DataFrame({"id": [1, 2, 3], "left": ["a", "b", "c"], "right": ["x", "y", "z"]})
.lazy()
.filter(col("id").gt(lit(1)))
.select([
col("id").add(lit(10)).alias("next_id"),
concat_str([col("left"), col("right")], "-").alias("label"),
])
)
with plan.collect_batches(chunk_size=1) as batches:
for batch in batches:
print(batch.to_dict(as_series=False))
asyncio
alopex.asyncio は Python 3.8 以上の標準 asyncio loop をサポートし、caller に Rust/Tokio runtime を
要求しません。prefetch_batches は read ahead の上限、max_buffered_batches は ready result
buffer の上限です。両者は 0 <= prefetch_batches <= max_buffered_batches、かつ
max_buffered_batches >= 1 でなければなりません。consumer_idle_timeout と timeout の単位は秒です。
native worker は bounded Rust payload だけを保持し、Python の row / DataFrame 変換は asyncio consumer 側で
行われます。Python の producer queue や callback は使用しません。
import asyncio
from alopex.asyncio import AsyncDatabase
async def main() -> None:
async with await AsyncDatabase.new() as db:
await db.execute_sql("CREATE TABLE events (id INTEGER PRIMARY KEY)")
await db.execute_sql("INSERT INTO events (id) VALUES (1), (2)")
stream = await db.execute_sql_stream(
"SELECT id FROM events",
prefetch_batches=1,
max_buffered_batches=1,
consumer_idle_timeout=5.0,
)
async with stream:
async for row in stream:
print(row)
asyncio.run(main())
同じ stream で同時に二つの anext() を実行すると stream_busy です。task cancellation、aclose()、
cancel()、idle timeout は stream の native source を終端させ、後続の独立した database operation を継続できます。
ベクトル検索(numpy 必須)
import numpy as np
from alopex import Database, Metric, TxnMode
db = Database.new()
with db.begin(TxnMode.READ_WRITE) as txn:
vec = np.array([1.0, 0.0, 0.0], dtype=np.float32)
txn.upsert_vector(b"k1", None, vec, Metric.COSINE)
results = txn.search_similar(vec, Metric.COSINE, 1, return_vectors=True)
print(results[0].key, results[0].score)
if results[0].vector is not None:
print(results[0].vector.dtype, results[0].vector.shape)
NumPy 入出力とゼロコピー条件(v0.3.5)
入力(Python → Rust):
- dtype:
float32が優先。float64はfloat32に変換して処理します。 - layout: C-contiguous が優先。非連続(strided/Fortran order 等)は C-contiguous に変換して処理します。
- ゼロコピー入力:
float32かつ C-contiguous の場合は Rust 側でコピーなしに参照します。
出力(Rust → Python):
Transaction.search_similar(..., return_vectors=True)の場合、SearchResult.vectorにnumpy.ndarray[float32]を含められます。Transaction.search_similar(..., zero_copy_return=True)/Transaction.get_vector(..., zero_copy_return=True)の場合、可能なら所有権移譲によるゼロコピー返却を行います(Falseの場合はコピー)。
GIL:
upsert_vector/search_similar/search_hnswは重い処理中に GIL を解放します。
HNSW インデックス(numpy 必須)
import numpy as np
from alopex import Database, HnswConfig, TxnMode
db = Database.new()
db.create_hnsw_index("idx", HnswConfig(2))
with db.begin(TxnMode.READ_WRITE) as txn:
vec = np.array([1.0, 0.0], dtype=np.float32)
txn.upsert_to_hnsw("idx", b"k1", vec, None)
txn.commit()
results, stats = db.search_hnsw("idx", np.array([1.0, 0.0], dtype=np.float32), 1)
print(stats.nodes_visited, stats.distance_computations, stats.search_time_us)
HNSW キャッシュ
db = Database.open("app.alopex", hnsw_cache_bytes=512 * 1024 * 1024,
hnsw_cache_entries=128)
retained_bytes = db.warm_hnsw_index("idx")
print(db.hnsw_cache_stats())
db.set_hnsw_cache_limit(256 * 1024 * 1024, entries=64)
new、open_in_memory、EmbeddedConfig でも同じ設定を指定できます。
件数は正の整数です。バイト数を0にすると保持を無効にします。
上限は推定グラフ容量で、プロセスのRSS、一時ロード中のグラフ、実行中の読み手の保持分は含みません。
LRUで最終アクセスが古い索引から追い出します。上限を超える索引でも検索はでき、
oversize_skips を加算し、索引ごとに一度警告します。ウォームアップは保持できた容量を返し、
保持できなければ0、索引がない場合や破損している場合はエラーを返します。
統計には上限・使用量・件数、累積の hits、実際のグラフロード試行数 misses、
evictions、oversize_skips、invalidations、load_ns_total、保持中の索引一覧を含みます。
索引別の hits と last_access_ns は共有グラフのアクセスを示します。
last_access_ns はキャッシュ初期化からの経過ナノ秒です。
db.begin() は開始時の共有グラフだけを自身のKVスナップショットと一緒に取得し、
SQL呼び出し間で再利用します。キャッシュにないグラフはそのトランザクションのKVから読み、
共有キャッシュへ公開しません。最初の書き込み時は独立したグラフへコピーします。
保持上限の変更は、明示トランザクションの次のSQL呼び出しでも適用します。
書き込み開始時のジャーナル準備と最初のグラフコピーのコストは別途かかります。
alopex.asyncio.AsyncDatabase にも同じ設定と3メソッドがあります。
有限のネイティブ処理を所有スレッドで実行するため、ウォームアップ中はイベントループをブロックします。
Catalog API(polars 必須)
import polars as pl
from alopex import Catalog, ColumnInfo
Catalog.create_catalog("main")
Catalog.create_namespace("main", "default")
columns = [ColumnInfo("id", "int", 0, False)]
Catalog.create_table("main", "default", "users", columns, "/tmp/users.parquet")
df = pl.DataFrame({"id": [1, 2], "name": ["a", "b"]})
Catalog.write_table(
df,
"main",
"default",
"users",
delta_mode="overwrite",
storage_location="/tmp/users.parquet",
)
lazy_frame = Catalog.scan_table("main", "default", "users")
print(lazy_frame.collect())
注意事項
- numpy / polars が未インストールの場合、対応 API は AlopexError を返します。
- Phase 1 では Parquet のみ対応しています。
Metadata
Release files for alopex 0.8.16
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| alopex-0.8.16.tar.gz | 1.8 MB | With provenance | Details |
Built distributions (wheels)
| File | Reset | |||
|---|---|---|---|---|
| alopex-0.8.16-cp38-abi3-win_amd64.whl | CPython 3.8 | abi3 | Windows x86-64 | Details |
| alopex-0.8.16-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl | CPython 3.8 | abi3 | Linux glibc 2.17+ x86-64 | Details |
| alopex-0.8.16-cp38-abi3-macosx_11_0_arm64.whl | CPython 3.8 | abi3 | macOS 11.0+ ARM64 | Details |
| alopex-0.8.16-cp38-abi3-macosx_10_12_x86_64.whl | CPython 3.8 | abi3 | macOS 10.12+ x86-64 | Details |
Total release size: 48.3 MB
Release files / alopex-0.8.16.tar.gz
| Download URL | alopex-0.8.16.tar.gz |
|---|---|
| Size | 1.8 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5333c0577b2e7f4d30ef4664ed2f7dfed27f18fd357ca08da35d105e8de8c807
|
|
BLAKE2b-256 checksum How to use checksums |
8e7fc5c127d59c1b9669bbee9204d203c4b3a98dcf9360c00141992bc0cd0ad4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.
Transparency logRelease files / alopex-0.8.16-cp38-abi3-win_amd64.whl
| Download URL | alopex-0.8.16-cp38-abi3-win_amd64.whl |
|---|---|
| Size | 12.0 MB |
| Tags | CPython 3.8 Windows x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
194401d71e5c41ab8e976330f6007529961aeeb1773aa9162a321725f079a0be
|
|
BLAKE2b-256 checksum How to use checksums |
418ebff73e93ee7d38f72304d0fcd4bd8c879dbd8d11f27336c3c1ca997480d7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.
Transparency logRelease files / alopex-0.8.16-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
| Download URL | alopex-0.8.16-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl |
|---|---|
| Size | 12.5 MB |
| Tags | CPython 3.8 Linux glibc 2.17+ x86-64 abi3 |
|
SHA-256 checksum How to use checksums |
ac9f4b1fd2fa0e78d634334242de4290ae4b34bf700515b59937ea2c718a98c3
|
|
BLAKE2b-256 checksum How to use checksums |
b9db1d06cb5b00d4d119995035b4ec641a95285ef09bad0d800bd0a02056a8d1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.
Transparency logRelease files / alopex-0.8.16-cp38-abi3-macosx_11_0_arm64.whl
| Download URL | alopex-0.8.16-cp38-abi3-macosx_11_0_arm64.whl |
|---|---|
| Size | 10.6 MB |
| Tags | CPython 3.8 abi3 macOS 11.0+ ARM64 |
|
SHA-256 checksum How to use checksums |
b8a77483b9fd4fd6e88f5760ca0732bfcf1015716c6fde07a57865284995a6ff
|
|
BLAKE2b-256 checksum How to use checksums |
2be3307ab2bc8e15d21b2388a40529c55af5320df4c54d9d59bc2988598a63b3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.
Transparency logRelease files / alopex-0.8.16-cp38-abi3-macosx_10_12_x86_64.whl
| Download URL | alopex-0.8.16-cp38-abi3-macosx_10_12_x86_64.whl |
|---|---|
| Size | 11.4 MB |
| Tags | CPython 3.8 abi3 macOS 10.12+ x86-64 |
|
SHA-256 checksum How to use checksums |
28d3ee891bfa9ac107b4b7fe56a6612ca55d19a6414f0cae26ce433171076d5e
|
|
BLAKE2b-256 checksum How to use checksums |
d7a7447af5351c3329ac6182f13c7c7eea2b4e3fad1b75088d34a5c7eddae13d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.
Transparency logSecurity for alopex 0.8.16
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
All 5 files in this release have been uploaded with provenance metadata.
Attestation for alopex-0.8.16.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 19, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.