ITZMA is still taking shape, and its API can change between releases. Version 0.2.1: serde_with security fix
Docs / Python

Python API

The package, async handles, web servers, settings and exceptions.

On this page

The itzma package embeds Itzma in your process. You open a namespace once, keep it warm in memory, and S3, GCS, Azure or a local directory holds the data. Installation covers installing it.

A first session

python
import numpy as np
import itzma
from itzma import attr

store = itzma.Store("memory://")  # or "file:///var/lib/itzma", "s3://bucket/prefix", "gs://bucket/prefix", "az://container/prefix"
schema = itzma.Schema(
    dim=4,
    metric=itzma.Metric.COSINE,
    attrs={"tag": itzma.AttrType.STRING, "year": itzma.AttrType.NUMBER},
)
ns = itzma.Namespace.create(store, "docs", schema)

ns.upsert(
    [
        {"id": "a", "vector": [1, 0, 0, 0], "attrs": {"tag": "news", "year": 2024}},
        {"id": "b", "vector": [0, 1, 0, 0], "attrs": {"tag": "blog", "year": 2021}},
    ]
)

hits = ns.query([0.9, 0.1, 0, 0], top_k=5, filter=attr("year") >= 2022)
print(hits.ids, hits.distances)
print(hits.to_polars())  # id, distance, then one typed column per declared attribute

A later process opens it by id, and the schema comes back with it:

python
again = itzma.Namespace.open(store, "docs")
print(again.schema)

Writes take three shapes:

python
ns.upsert(rows)  # list of dicts
ns.upsert(ids=ids, vectors=matrix, attrs=attr_dicts)  # numpy (any float dtype)
ns.upsert(df)  # pyarrow, Polars or DuckDB table

Writing, Filtering and Maintenance cover the calls in detail.

Async

AsyncNamespace has the same calls as awaitables. Each query runs on Itzma’s own threads, so the event loop stays free and many queries can be in flight at once.

python
async with await itzma.AsyncNamespace.create(store, "async", schema) as ns:
    n = 2_000
    await ns.upsert(
        ids=[str(i) for i in range(n)],
        vectors=rng.standard_normal((n, DIM)),
        attrs=[{"shard": i % 4} for i in range(n)],
    )

    # Each query runs on Itzma's own threads, so the event loop stays free.
    queries = rng.standard_normal((20, DIM))
    results = await asyncio.gather(
        *(ns.query(q, top_k=3, filter=attr("shard") == i % 4) for i, q in enumerate(queries))
    )

In a web server

Open each namespace once per process and share the handle across requests. Every call releases the GIL, and the async methods never block the event loop.

python
@asynccontextmanager
async def lifespan(app: FastAPI):
    store = itzma.Store("s3://my-bucket/itzma", region="us-east-1")
    app.state.ns = await itzma.AsyncNamespace.open(
        store, "docs", cache=itzma.Cache(ram_bytes=2 << 30)
    )
    app.state.ns.start_maintenance(timedelta(seconds=60))
    yield
    app.state.ns.close()


app = FastAPI(lifespan=lifespan)


@app.post("/search")
async def search(vector: list[float]):
    hits = await app.state.ns.query(vector, top_k=10)
    return [{"id": h.id, "distance": h.distance} for h in hits]

Django or Flask under gunicorn: open the namespace in each worker, not in the master. With --preload, open it in a post_fork hook or lazily on first use:

python
# gunicorn.conf.py
def post_fork(server, worker):
    import myapp.search

    myapp.search.ns = itzma.Namespace.open(itzma.Store("s3://my-bucket/itzma"), "docs")

A handle opened before a fork refuses to work in the child and says so. Itzma keeps one tokio runtime per process and builds a fresh one in each child.

Settings

  • S3. Region and credentials come from the AWS SDK’s usual chain: AWS_* environment variables, ~/.aws profiles, web identity, then the container or instance role. The region falls back to us-east-1. Keywords override them: region, endpoint, access_key_id, secret_access_key, session_token, allow_http (for a local MinIO). env=False ignores the environment and profiles; with no keys it then uses the instance role. Reading a missing object needs s3:ListBucket, or S3 answers 403 instead of 404.
  • GCS. gs://bucket/prefix uses Google’s default credentials (Workload Identity on GKE and Cloud Run, or gcloud auth application-default login). For an emulator, pass endpoint and control_endpoint (the gRPC one) together, and anonymous=True to send no credentials.
  • Azure. az://container/prefix with account. credential picks how to sign in: "managed_identity" (the default), "workload_identity", "developer_tools" (az login) or "anonymous"; or pass sas_token instead. endpoint overrides https://<account>.blob.core.windows.net; token credentials need https, so an emulator such as Azurite takes a SAS token.
  • Each keyword is refused on a URL whose scheme does not use it.
  • Cache. itzma.Cache(ram_bytes=..., nvme_dir=..., nvme_bytes=...) keeps segment and index bytes in RAM and optionally on a local disk. The manifest is never cached, so a write is visible to the next query either way.
  • Large loads. An Arrow table or stream (pyarrow, Polars, DuckDB, anything with __arrow_c_stream__) is read one record batch at a time and written in chunks of about target_bytes (32 MiB by default), with depth (2) encoded chunks waiting at most, so a load of any size runs in bounded memory. If it fails part way, the error carries first_seq, last_seq and rows_written; resume an unkeyed load from rows_written. With key=, chunk n is written under "<key>#<n>", so the key can be at most 107 bytes, and a retry with retry_from=e.first_seq writes only the missing chunks.
  • Fetch policy. fetch=itzma.FetchPolicy.local() on create or open suits a memory:// or file:// store; the default, FetchPolicy.object_store(), suits S3, GCS and Azure. Caching explains both.
  • Read budget. read_budget= caps the bytes one query or compaction may read (1 GiB by default). Going over raises ReadBudgetExceeded.
  • Threads. itzma.configure(worker_threads=n) sets the runtime’s thread count; call it before anything else. itzma.configure(cpu_threads=n, maintenance_cpu_threads=m) sizes the two compute pools that queries, decoding and index builds run on; call it before the first query or build.

Exceptions

Everything raises a subclass of itzma.ItzmaError: InvalidInput (and its subclasses InvalidVector, InvalidAttrs, InvalidQuery, BatchTooLarge), NamespaceExists, NamespaceNotFound, ReadBudgetExceeded, KeyConflict, Contention, FormatTooNew, FormatTooOld, Corrupt and StoreError. The useful details are attributes, for example e.expected and e.got on InvalidVector.

Docs
esc

Loading the docs…