import tempfile
import uuid
from pathlib import Path
import jammi
import pyarrow as pa
import pyarrow.parquet as pq
from jammi.errors import BackendError, NotFound
from jammi.testing import LiveServer
from jammi_cookbook import fixtures
from jammi_cookbook.claims import claim
from jammi_cookbook.rails import tenant
TENANT_A = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
TENANT_B = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
work = Path(tempfile.mkdtemp())
def parquet(name: str, table: pa.Table) -> str:
pq.write_table(table, work / f"{name}.parquet")
return str(work / f"{name}.parquet")
def refused(action) -> bool:
try:
action()
return False
except BackendError:
return True
def isolation(db) -> dict:
"""Tenant A creates one of each resource; tenant B's view of each is measured."""
run = uuid.uuid4().hex[:8]
with tenant(db, TENANT_A):
db.add_source(f"src_a_{run}", url=parquet(f"src_a_{run}", pa.table({"id": [1]})),
format="parquet")
db.create_mutable_table(f"mt_a_{run}", schema=pa.schema([("id", pa.int64())]),
primary_key=["id"])
db.register_topic(f"tp_a_{run}", schema=pa.schema([("id", pa.int64())]))
db.register_channel(f"ch_a_{run}", priority=5, columns=[("note", "Utf8")])
db.add_source(f"pairs_{run}", url=str(fixtures.path("tiny_pairs.csv")), format="csv")
job = db.fine_tune(source=f"pairs_{run}", base_model=fixtures.model("tiny_bert"),
columns=["text_a", "text_b", "score"], method="lora",
task="text_embedding", lora_rank=4, epochs=1)
job.wait()
tuned = job.output_model_id
# One shared source whose rows carry their tenant, and one with no discriminator.
db.set_tenant("")
db.add_source(f"tagged_{run}", url=parquet(f"tagged_{run}", pa.table({
"id": [1, 2, 3, 4], "tenant_id": [TENANT_A, TENANT_A, TENANT_B, TENANT_B],
})), format="parquet")
with tenant(db, TENANT_B):
db.add_source(f"nodisc_b_{run}", url=parquet(f"nodisc_b_{run}", pa.table({"id": [7, 8, 9]})),
format="parquet")
with tenant(db, TENANT_B):
sources = {s["source_id"] for s in db.list_sources()}
cells = {
"list_sources": int(f"src_a_{run}" in sources),
"describe_source": int(db.describe_source(f"src_a_{run}") is not None),
"list_mutable_tables": int(any(t["id"] == f"mt_a_{run}" for t in db.list_mutable_tables())),
"list_topics": int(f"tp_a_{run}" in db.list_topics()),
"list_channels": int(any(c["channel_id"] == f"ch_a_{run}" for c in db.list_channels())),
"list_models (A's fine-tuned model)": int(any(m["model_id"] == tuned for m in db.list_models())),
}
shared = {
"the engine's global channels": sum(c["channel_id"] in ("vector", "inference", "bm25")
for c in db.list_channels()),
"the shared base model": int(any(m["model_id"] != tuned for m in db.list_models())),
}
# Collisions: B reuses A's names.
collisions = {
"create_mutable_table (A's name)": refused(lambda: db.create_mutable_table(
f"mt_a_{run}", schema=pa.schema([("id", pa.int64())]), primary_key=["id"])),
"register_topic (A's name)": not refused(lambda: db.register_topic(
f"tp_a_{run}", schema=pa.schema([("id", pa.int64())]))),
"register_channel (A's name)": not refused(lambda: db.register_channel(
f"ch_a_{run}", priority=1, columns=[("x", "Utf8")])),
}
# Destruction: B drops A's names.
b_drop_raised = refused(lambda: db.drop_mutable_table(f"mt_a_{run}"))
db.drop_topic(f"tp_a_{run}", if_exists=True)
with tenant(db, TENANT_A):
a_rows = db.sql(f"SELECT id FROM tagged_{run}.public.tagged_{run}").column("id").to_pylist()
caveat = db.sql(f"SELECT COUNT(*) FROM nodisc_b_{run}.public.nodisc_b_{run}").column(0)[0].as_py()
survives = {
"A's mutable table after B's drop": any(t["id"] == f"mt_a_{run}" for t in db.list_mutable_tables()),
"A's topic after B's drop": f"tp_a_{run}" in db.list_topics(),
}
cells["sql (B's tagged rows read by A)"] = sum(1 for i in a_rows if i in (3, 4))
return {"leaks": cells, "shared": shared, "caveat": caveat, "collisions": collisions,
"b_drop_raised": b_drop_raised, "survives": survives, "a_own_rows": sorted(a_rows)}51 Per-verb tenant isolation, on both transports — and the bring-your-own-auth seam
Verbs: set_tenant / tenant_scope across the tenant-scoped verb surface (list_sources · describe_source · list_mutable_tables · list_topics · list_channels · list_models · sql · the create_* / drop_* verbs) · Background: tenant isolation as a per-verb property of the catalog and the query analyzer, measured from the consumer side · Checked: tenancy (hard zeros where isolation must hold, positive counts where visibility is by design) + parity (the same matrix in process and from a server).
The tenancy chapter establishes the engine’s tenancy contract as two layers and one honest caveat: catalog-listing isolation and discriminator-column row isolation, both as hard zeros, plus the discriminator-less-source caveat as a positive visible count. This chapter extends it to the whole tenant-scoped verb surface. For each verb, tenant A creates a resource under its own scope and tenant B’s view of it is measured: B cannot see, read, overwrite, or destroy it. The measurement is one function, run against an in-process engine and a live server; the two matrices must agree.
Then it demonstrates the engine’s bring-your-own-auth seam: the engine authenticates nothing, so a gateway in front of it verifies a credential and binds the tenant the credential proves — shown over the real Flight SQL wire.
51.1 Part A — the per-verb isolation matrix
Every cell is measured the same way on each transport:
with jammi.connect(f"file://{tempfile.mkdtemp()}") as db:
local = isolation(db)
with LiveServer(tempfile.mkdtemp()) as server, jammi.connect(server.endpoint) as db:
served = isolation(db)
print(f"the two transports agree on every cell: {local == served}")2026-10-03T07:47:57.649901Z WARN jammi_kernels::admission: fused-kernel domain check failed; falling back to the eager composition op="attention_block_fused" predicate="head_dim_is_attention_block_fixed_head_dim"
the two transports agree on every cell: True
claim("the two transports agree on every cell", local == served)✓ the two transports agree on every cell
51.1.1 The hard zeros — B reaches none of A’s resource
for verb, leaked in local["leaks"].items():
print(f" {leaked} {verb}") 0 list_sources
0 describe_source
0 list_mutable_tables
0 list_topics
0 list_channels
0 list_models (A's fine-tuned model)
0 sql (B's tagged rows read by A)
claim("no tenant-scoped verb leaks A's resources to B", all(v == 0 for v in local["leaks"].values()),
f"{len(local['leaks'])} verbs")
claim("and the zero is not vacuous: A reads its own rows", local["a_own_rows"] == [1, 2])✓ no tenant-scoped verb leaks A's resources to B (7 verbs)
✓ and the zero is not vacuous: A reads its own rows
The catalog reads filter each registry to the current tenant’s rows and the global ones, so B’s listing carries none of A’s registrations, and a foreign describe_source is None — B cannot even confirm the source exists. The data layer is the discriminator column: a read of the shared tagged source is rewritten to the reader’s own rows.
51.1.2 The stated positives — visibility by design, as counts
for what, count in local["shared"].items():
print(f" B sees {what}: {count}")
print(f" A reads B's discriminator-less source whole: {local['caveat']} rows") B sees the engine's global channels: 3
B sees the shared base model: 1
A reads B's discriminator-less source whole: 3 rows
claim("what is global by design is visible to every tenant",
all(count > 0 for count in local["shared"].values()))
claim("and a discriminator-less source is read whole by anyone who names it", local["caveat"] == 3,
f"{local['caveat']} rows")✓ what is global by design is visible to every tenant
✓ and a discriminator-less source is read whole by anyone who names it (3 rows)
Three things are visible to every tenant, on purpose. The engine’s built-in evidence channels (vector, inference, bm25) are global. So is a model referenced from outside — a base encoder loaded from a hub or a path is a shared catalog row, not any tenant’s data; what a tenant produces, its fine-tuned model, is its own and does not leak (the hard zero above). And the tenancy chapter’s caveat: a source with no discriminator column is read whole by anyone who names it. Data isolation is the discriminator column, not source separation.
51.1.3 Collisions and destruction — never a cross-tenant clobber
for verb, isolated in local["collisions"].items():
print(f" {verb}: {'refused' if 'mutable' in verb else 'B gets its own'} ({isolated})")
print(f" B's drop of A's mutable-table name refused in B's namespace: {local['b_drop_raised']}")
for what, alive in local["survives"].items():
print(f" {what}: still there = {alive}") create_mutable_table (A's name): refused (True)
register_topic (A's name): B gets its own (True)
register_channel (A's name): B gets its own (True)
B's drop of A's mutable-table name refused in B's namespace: True
A's mutable table after B's drop: still there = True
A's topic after B's drop: still there = True
claim("a name collision never clobbers another tenant's resource",
all(local["collisions"].values()) and local["b_drop_raised"])
claim("and every one of A's resources survives B's attempts", all(local["survives"].values()))✓ a name collision never clobbers another tenant's resource
✓ and every one of A's resources survives B's attempts
A mutable table’s name is unique across tenants, so B reusing A’s name is refused; a topic and a channel live in per-tenant namespaces, so B’s reuse makes B’s own. And a destructive verb named by the wrong tenant resolves in that tenant’s namespace: B’s drop of A’s mutable table is a not-found, B’s drop of A’s topic touches nothing — A’s resources survive.
51.1.4 The result-table scan
A result table’s Parquet carries no tenant_id column, so the discriminator rewrite has nothing to act on; resolution is gated instead on the catalog row’s owner. A table tenant A materializes resolves for A; one materialized with no tenant bound is global, visible to both; and B naming A’s table is refused — while A’s own re-read, after B’s attempt, is unchanged.
rts = jammi.connect(f"file://{tempfile.mkdtemp()}")
def materialize(tag: str) -> str:
spine = parquet(f"spine_{tag}", pa.table({"entity": ["p", "q", "r"], "as_of": [10, 10, 10]}))
facts = parquet(f"facts_{tag}", pa.table({"entity": ["p", "q", "r"], "t": [10, 10, 10],
"val": [1.0, 2.0, 3.0]}))
rts.add_source(f"spine_{tag}", url=spine, format="parquet")
rts.add_source(f"facts_{tag}", url=facts, format="parquet")
return rts.asof_join(f"spine_{tag}", f"facts_{tag}", spine_by=["entity"], spine_time="as_of",
facts_by=["entity"], facts_time="t", direction="backward",
boundary="inclusive", project=["val"])
def scan(table: str) -> int:
return rts.sql(f'SELECT COUNT(*) AS n FROM "jammi.{table}"').to_pylist()[0]["n"]
with tenant(rts, TENANT_A):
private = materialize("a")
own = scan(private)
rts.set_tenant("")
shared_table = materialize("global")
with tenant(rts, TENANT_B):
b_refused = refused(lambda: scan(private))
b_global = scan(shared_table)
with tenant(rts, TENANT_A):
a_global, own_after = scan(shared_table), scan(private)
rts.close()
print(f"A reads its own table: {own} rows; the global table: A {a_global}, B {b_global}")
print(f"B naming A's table refused: {b_refused}; A's re-read after: {own_after} rows")A reads its own table: 3 rows; the global table: A 3, B 3
B naming A's table refused: True; A's re-read after: 3 rows
claim("a tenant's result table resolves for its owner and is refused to another tenant",
own > 0 and b_refused and own_after == own)
claim("and a table materialized with no tenant bound is visible to both", a_global == b_global > 0)✓ a tenant's result table resolves for its owner and is refused to another tenant
✓ and a table materialized with no tenant bound is visible to both
51.2 Part B — the BYO-auth seam, from the consumer side
The engine authenticates nothing on its own. The jammi-session-id header the stock interceptor reads is a client-minted, opaque transport correlation id — it identifies a connection, not a principal. Anyone who presents another session’s id assumes that session’s tenant. It is the right trade-off on a trusted network and the wrong one the moment an untrusted caller can reach the port. It is not a trust boundary.
Verifying a caller is the consumer’s job — a gateway placed in front of the engine. The engine’s grpc_byo_auth.rs worked example shows that seam for the typed gRPC verbs; the Flight SQL lane (db.sql()) is a separate pyarrow.flight transport and is the gateway-in-front’s responsibility there too (by design). The client carries the channel’s bearer on the Flight SQL lane as well as the typed verbs. So here is the consumer-side seam over that real Flight wire: a pyarrow.flight gateway reads the inbound bearer off a genuine db.sql() call, a generic HMAC-signed bearer token (no identity provider, no product name) it verifies, and a real-engine tenant-scoped read it returns — the credential binds the engine’s tenant_scope in front of the engine.
The credential is generic on purpose: an opaque subject plus a tenant claim, HMAC-SHA256 (Krawczyk, Bellare, and Canetti 1997) over both under a key only the consumer’s issuer and gateway share, presented as a bearer token (Jones and Hardt 2012). The tenant claim is inside the signed payload, so it cannot be forged without the key. It stands in for whatever a consumer’s identity system mints; the seam only needs the gateway to turn a verified claim into a tenant.
import hashlib
import hmac
# The CONSUMER's shared signing key — the engine never sees it. A real deployment
# rotates this; here it is fixed so the example is reproducible.
SIGNING_KEY = b"consumer-issuer-signing-key-not-jammi"
def mint_token(subject: str, tenant_id: str) -> str:
"""A generic signed token '<subject>.<tenant>.<hex-mac>' — BARE, no 'Bearer '
prefix. BearerCredentials prepends 'Bearer ' itself on the wire, so minting it
here too would double it to 'Bearer Bearer …' and never verify."""
claim = f"{subject}.{tenant_id}"
sig = hmac.new(SIGNING_KEY, claim.encode(), hashlib.sha256).hexdigest()
return f"{claim}.{sig}"
def verify_token(authorization):
"""Verify the wire's 'authorization' header; return its tenant claim, or None
if missing / malformed / failing the constant-time signature check. Strips the
one 'Bearer ' the wire carries. Only a VERIFIED claim yields a tenant — a
forged tenant the signature does not cover returns None."""
if not authorization or not authorization.startswith("Bearer "):
return None
claim, _, sig_hex = authorization[len("Bearer "):].rpartition(".")
subject, _, tenant_id = claim.partition(".")
if not claim or not sig_hex or not subject or not tenant_id:
return None
expected = hmac.new(SIGNING_KEY, claim.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sig_hex):
return None
return tenant_idThe gateway is the seam, as a real pyarrow.flight server. A db.sql() call presents its bearer on the Flight lane; a ServerMiddlewareFactory reads the inbound authorization header (pyarrow lowercases the key and hands each value as a list), the handlers verify it, derive the tenant from the verified claim, and bind it via the engine’s tenant_scope for the read. db.sql() makes two Flight calls (get_flight_info then do_get), each re-presenting the bearer, so the gateway verifies in both — rejecting in get_flight_info short-circuits the whole sql() before any read runs. On a missing or invalid credential the gateway raises FlightUnauthenticatedError, which the jammi client surfaces through the JammiError taxonomy as jammi.BackendError (detail: Unauthenticated); the request reads nothing, it does not fall through to an unscoped global read.
import jammi
import pyarrow as pa
import pyarrow.flight as flight
import pyarrow.parquet as pq
from jammi_cookbook.rails import tenant
class AuthMiddleware(flight.ServerMiddleware):
def __init__(self, authorization):
self.authorization = authorization
class AuthMiddlewareFactory(flight.ServerMiddlewareFactory):
"""Records the inbound 'authorization' header of every Flight call — the exact
value db.sql() put on the wire (the value is a LIST; take the first)."""
def __init__(self):
self.observed = []
def start_call(self, info, headers):
auth = headers.get("authorization")
value = auth[0] if auth else None
self.observed.append(value)
return AuthMiddleware(value)
class AuthGatewayServer(flight.FlightServerBase):
"""The seam: a Flight server that verifies the bearer in front of the engine."""
def __init__(self, location, db, factory):
super().__init__(location, middleware={"auth": factory})
self._db = db
self._schema = pa.schema([("source_id", pa.string())])
def _verified_tenant(self, context):
mw = context.get_middleware("auth")
tenant_id = verify_token(mw.authorization if mw is not None else None)
if tenant_id is None: # reject — never bind None
raise flight.FlightUnauthenticatedError("missing or invalid credential")
return tenant_id
def get_flight_info(self, context, descriptor):
self._verified_tenant(context) # short-circuits sql()
endpoint = flight.FlightEndpoint(b"sources", [])
return flight.FlightInfo(self._schema, descriptor, [endpoint], -1, -1)
def do_get(self, context, ticket):
tenant_id = self._verified_tenant(context)
with self._db.tenant_scope(tenant_id): # bind the VERIFIED tenant
rows = [s["source_id"] for s in self._db.list_sources()]
return flight.RecordBatchStream(pa.table({"source_id": rows}))
catalog = tempfile.mkdtemp()
work = tempfile.mkdtemp()
db = jammi.connect(f"file://{catalog}")
def write_src(name, tenant_id):
path = f"{work}/{name}.parquet"
pq.write_table(pa.table({"id": [1]}), path)
with tenant(db, tenant_id):
db.add_source(name, url=path, format="parquet")
write_src("auth_a", TENANT_A)
write_src("auth_b", TENANT_B)
factory = AuthMiddlewareFactory()
# Port 0: the kernel assigns one and the server reports it — nothing here
# holds a port number and releases it for someone else to race.
gateway = AuthGatewayServer(flight.Location.for_grpc_tcp("127.0.0.1", 0), db, factory)
gateway_endpoint = f"127.0.0.1:{gateway.port}"
def gateway_sources(token):
"""The production db.sql() Flight path: the bearer rides the REAL Flight wire
(BearerCredentials prepends 'Bearer '); anonymous when token is None."""
credentials = jammi.BearerCredentials(token) if token is not None else None
conn = jammi.connect(f"grpc://{gateway_endpoint}", credentials=credentials)
try:
return conn.sql("SELECT source_id FROM sources").column("source_id").to_pylist()
finally:
conn.close()The bearer rides the real Flight wire: an authenticated db.sql() puts Bearer <minted> on every Flight call the gateway’s middleware sees, while an anonymous db.sql() carries no authorization header at all.
minted_a = mint_token("subject-a", TENANT_A)
a_seen = gateway_sources(minted_a)
bearer_on_flight = bool(factory.observed) and all(
obs == f"Bearer {minted_a}" for obs in factory.observed
)
print(f"the gateway saw on the Flight wire: {factory.observed[0]}")
print(f"bearer rides the real Flight lane: {bearer_on_flight}")
assert bearer_on_flightthe gateway saw on the Flight wire: Bearer subject-a.aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa.bd9a3c3fb5b69994e2ef7590689ab0728d619347b57187dafacd1f11635b0bdd
bearer rides the real Flight lane: True
Two authenticated callers, two valid tokens for two distinct tenants — each db.sql() over Flight sees only its own tenant’s source. The tenant is inside the signed claim; neither caller asserts it in a plain header.
b_seen = gateway_sources(mint_token("subject-b", TENANT_B))
a_isolated = "auth_a" in a_seen and "auth_b" not in a_seen
b_isolated = "auth_b" in b_seen and "auth_a" not in b_seen
print(f"caller A sees {a_seen} isolated: {a_isolated}")
print(f"caller B sees {b_seen} isolated: {b_isolated}")
assert a_isolated and b_isolatedcaller A sees ['auth_a'] isolated: True
caller B sees ['auth_b'] isolated: True
An anonymous db.sql() carries no bearer, and the gateway rejects it in get_flight_info before any engine read runs — the caller reads nothing. It does not fall through to an unscoped read that could surface a global (tenant_id IS NULL) row.
before = len(factory.observed)
try:
gateway_sources(None)
missing_rejected = False
except jammi.BackendError:
missing_rejected = True
anon_no_bearer = all(obs is None for obs in factory.observed[before:])
print(f"anonymous db.sql() carried no bearer: {anon_no_bearer}")
print(f"missing credential rejected (not run unscoped): {missing_rejected}")
assert missing_rejected and anon_no_beareranonymous db.sql() carried no bearer: True
missing credential rejected (not run unscoped): True
An invalid credential — a forged tenant claim the signature does not cover — is rejected too. And the forgery buys nothing: a valid token for the same tenant the forgery claimed still resolves, proving the rejection was the signature, not a tenant blocklist. The seam authenticates the claim.
forged = f"subject-mallory.{TENANT_A}.deadbeef"
try:
gateway_sources(forged)
forged_rejected = False
except jammi.BackendError:
forged_rejected = True
legit_after = "auth_a" in gateway_sources(mint_token("subject-a", TENANT_A))
print(f"invalid (forged) credential rejected: {forged_rejected}")
print(f"a valid token for the same tenant still resolves: {legit_after}")
assert forged_rejected and legit_after
gateway.shutdown()invalid (forged) credential rejected: True
a valid token for the same tenant still resolves: True
The gateway’s tenant-scoped read over Flight is the same isolation as the embedded list_sources under the same tenant — the seam puts the wire bearer in front of the engine’s binding without changing what the engine returns.
with tenant(db, TENANT_A):
embedded_a = sorted(s["source_id"] for s in db.list_sources())
over_flight_eq_embedded = sorted(a_seen) == embedded_a
print(f"over-Flight read == embedded read under the same tenant: {over_flight_eq_embedded}")
assert over_flight_eq_embeddedover-Flight read == embedded read under the same tenant: True
db.close()51.3 What this chapter establishes
The engine isolates per verb: every tenant-scoped catalog read, describe, and discriminator-column row read is a hard zero, on both transports, and every destructive verb is tenant-scoped so a foreign tenant cannot reach across to destroy A’s resource. What is visible to every tenant by design — a built-in channel, a shared base model, a discriminator-less source — is measured as a positive count, not glossed. No verb leaks, and the in-process and served matrices are identical.
A result table (asof_join, generate_embeddings, …) isolates the same way despite carrying no tenant_id column of its own: the catalog row’s owner gates resolution of the bare jammi.{name} identifier (result_schema.rs), driven live here over the db.sql lane, mirroring the engine’s own standing oracle. It is the same organizational resolution-visibility property as the rest of the chapter, not a hostile-principal boundary — the trusted-network + BYO-auth posture is unchanged.
And the engine’s BYO-auth seam, demonstrated from the consumer side over the real Flight SQL wire: the credential rides the actual db.sql() Flight lane, not an in-process call — the gateway reads the bearer the client put on the wire and binds the engine’s tenant_scope in front of the read. The engine ships the credential plumbing (the bearer on both the typed gRPC verbs and the Flight lane) and the per-request tenant binding; the consumer supplies the auth (the generic credential, the gateway that verifies it and binds the verified tenant). Authentication runs in front of the engine, so the tenant the engine acts on is the one the credential proves — and a rejected caller fails the request in get_flight_info, never running unscoped. The engine enforces auth on no transport by design; the gateway in front is the consumer’s.