54  Building a graph from data

Verbs: generate_embeddings · build_neighbor_graph · eval_embeddings · Background: topology from data — graph construction and the Laplacian (Stanković et al. 2020, Part I) · Checked: provenance (where each edge came from) + measurement (same-subject precision@10).

This case study puts the book’s capabilities together into one graph machine-learning pipeline over the ogbn-arxiv papers, in four tiers: construct a graph, analyze (propagate over) it, learn on it, and predict from it with honest coverage. A graph is the substrate of everything downstream. Tier 01 builds two of them over the same papers and contrasts them — the contrast the rest of the case study turns on.

This chapter builds both, live. At small scale (the default) it runs in seconds on a CPU over 400 papers with a random-weight fixture encoder; at full scale the same cells run 4,000 papers through an embedding-trained ModernBERT (gte-modernbert-base) on a GPU (see The two datasets, at two scales).

The keystone’s steps are defined once, in jammi_cookbook.keystone, so every later chapter can rebuild what it needs from a fresh engine; the chapter that introduces a step shows its code. Tier 01’s step embeds each paper’s title and abstract:

def embed(db, arxiv: Arxiv, scale: Scale) -> str:
    """Tier 01: embed every paper's title and abstract."""
    return db.generate_embeddings(
        source=arxiv.papers,
        model=encoders.text(scale),
        columns=["title", "abstract"],
        key="paper_id",
    )
import tempfile

import jammi
from jammi_cookbook import datasets, encoders, scale
from jammi_cookbook.claims import claim

SCALE = scale.current()
MODEL = encoders.text(SCALE)

db = jammi.connect(f"file://{tempfile.mkdtemp()}")
arxiv = datasets.arxiv(db, SCALE)
embeddings = keystone.embed(db, arxiv, SCALE)
neighbor_graph = db.build_neighbor_graph(arxiv.papers, k=10, exact=True)

def rows(table: str, columns: str = "*") -> list[dict]:
    return db.sql(f'SELECT {columns} FROM "jammi.{table}"').to_pylist()


print(f"scale:                {SCALE} ({MODEL})")
print(f"papers embedded:      {len(rows(embeddings, '_row_id'))}")
print(f"neighbor-graph edges: {len(rows(neighbor_graph, 'src'))}")
print("neighbor-graph columns:", list(rows(neighbor_graph)[0]))
2026-10-03T07:42:16.501408Z  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"
scale:                small (local:/__w/jammi-ai/jammi-ai/cookbook/book/jammi_cookbook/_fixtures/tiny_bert)
papers embedded:      400
neighbor-graph edges: 4000
neighbor-graph columns: ['src', 'dst', 'rank', 'similarity']

A result table the engine produced is queried as "jammi.<table>". The neighbor graph is an edge table (src, dst, rank, similarity) — the provenance rail at the construct tier: every derived edge records its similarity and its rank among a node’s neighbours, so an edge’s origin is a queryable fact, not an assumption.

54.1 The contrast: homophily on the subject label

The two graphs differ in what they encode. Homophily on the subject label is the fraction of edges whose endpoints share a subject; the chance level to read it against is the probability that two papers drawn at random share one, \(\sum_s p_s^2\) over the subject mix.

papers = db.sql(f"SELECT paper_id, title, subject FROM {arxiv.papers}.public.{arxiv.papers}")
papers = papers.to_pylist()
subject = {p["paper_id"]: p["subject"] for p in papers}
cites = db.sql(f"SELECT src, dst FROM {arxiv.cites}.public.{arxiv.cites}").to_pylist()


def homophily(edges: list[dict]) -> float:
    return sum(subject[e["src"]] == subject[e["dst"]] for e in edges) / len(edges)


chance = keystone.subject_chance(db, arxiv)
cite_homophily = homophily(cites)
neighbor_homophily = homophily(rows(neighbor_graph, "src, dst"))
print(f"citation-graph homophily:  {cite_homophily:.3f}")
print(f"neighbor-graph homophily:  {neighbor_homophily:.3f}")
print(f"chance (subject mix):      {chance:.3f}")
citation-graph homophily:  0.537
neighbor-graph homophily:  0.431
chance (subject mix):      0.356
claim("citations connect papers of one subject far more often than chance",
      cite_homophily > chance, f"{cite_homophily:.3f} against {chance:.3f}")
claim("so do the encoder's nearest neighbours", neighbor_homophily > chance,
      f"{neighbor_homophily:.3f} against {chance:.3f}")
✓ citations connect papers of one subject far more often than chance (0.537 against 0.356)
✓ so do the encoder's nearest neighbours (0.431 against 0.356)

The citation graph is well above chance at both scales — that correlation is what later breaks conformal exchangeability (tier 04). The neighbor graph’s homophily is a property of the encoder. At full scale the embedding model’s neighbours share a subject about as often as citations do. At small scale the fixture encoder’s weights are random, yet its neighbours still beat chance: a word is the same random vector wherever it appears, so papers that share vocabulary land near each other — lexical overlap alone, no learned meaning. The declared graph carries the subject signal whatever the encoder knows.

54.2 The measurement rail: retrieval precision from the embeddings

The construct tier ends in a real number: same-subject retrieval precision@10 — ask with a paper’s title, count how many of the ten papers retrieved share its subject. The relevance target is the subject label, never the embedding similarity, so it is a fair baseline that tiers 02–03 must beat. The engine measures it: eval_embeddings encodes each query with the model that produced the table, searches the table, and scores against the golden.

golden = keystone.subject_golden(db, arxiv)
report = db.eval_embeddings(
    source=arxiv.papers, embedding_table=embeddings, golden_source=golden, k=10
)
precision = report["aggregate"]["precision_at_k"]
print(f"tier01 precision@10 (raw embeddings): {precision:.3f}")
tier01 precision@10 (raw embeddings): 0.403

54.3 Bridge note (deepened in the bridge chapters)

An edge is a self-search. The derived neighbor graph is self-kNN: kNN-graph construction (monograph Part I) expressed as the engine retrieving, for every row, its nearest rows. The derived similarity graph is the commodity; the declared citation graph carries the signal embeddings cannot reconstruct — the circularity contract that the whole book turns on.


55 Air Routes — the on-ramp

The keystone above runs on ogbn-arxiv. The book opens, though, on Air Routes — Neptune’s own teaching dataset: 3,504 airports, a declared route graph (airport↔︎airport) and a contains hierarchy (continent→airport). The same recipe runs here unchanged.

Neptune-contrast. Neptune loads a given graph and runs CALL neptune.algo.* over it. Jammi constructs the similarity graph from the airport text and registers the declared route/contains graphs beside it — the two-graphs contrast in miniature.

air = datasets.air_routes(db)
air_embeddings = db.generate_embeddings(
    source=air.airports, model=MODEL, columns=["desc", "city", "country", "region"], key="code"
)
air_graph = db.build_neighbor_graph(air.airports, k=10, exact=True)
airports = db.sql(
    f"SELECT code, continent FROM {air.airports}.public.{air.airports}"
).to_pylist()
routes = db.sql(f"SELECT src, dst FROM {air.routes}.public.{air.routes}").to_pylist()
contains = db.sql(f"SELECT src, dst FROM {air.contains}.public.{air.contains}").to_pylist()
print(f"airports embedded:    {len(rows(air_embeddings, '_row_id'))}")
print(f"neighbor-graph edges: {len(rows(air_graph, 'src'))}")
print(f"route edges:          {len(routes)}")
print(f"contains edges:       {len(contains)}")
airports embedded:    3504
neighbor-graph edges: 35040
route edges:          50637
contains edges:       7008

55.1 Homophily of route vs contains on the continent label

The two declared graphs encode different structure.

  • route connects airport↔︎airport; its homophily is the share of flights that stay on one continent.
  • contains is the continent→country→airport hierarchy. The source carries no continent→country edge (a transcontinental country’s continent is ambiguous), so the honest continent-homophily of the declared hierarchy is measured over the edges whose parent is a continent: the fraction whose child airport’s continent matches that parent.
continent = {a["code"]: a["continent"] for a in airports}
continents = {c for c in continent.values() if c}

on_one_continent = [
    (r["src"], r["dst"]) for r in routes if continent.get(r["src"]) and continent.get(r["dst"])
]
route_h = sum(continent[s] == continent[d] for s, d in on_one_continent) / len(on_one_continent)
under_a_continent = [
    (r["src"], continent.get(r["dst"])) for r in contains
    if r["src"] in continents and continent.get(r["dst"])
]
contains_h = sum(p == c for p, c in under_a_continent) / len(under_a_continent)
print(f"route homophily (continent):    {route_h:.3f}")
print(f"contains homophily (continent): {contains_h:.3f}")
route homophily (continent):    0.826
contains homophily (continent): 0.990
claim("the declared hierarchy is more continent-consistent than the route graph",
      contains_h > route_h, f"{contains_h:.3f} against {route_h:.3f}")
✓ the declared hierarchy is more continent-consistent than the route graph (0.990 against 0.826)

The declared hierarchy is near-perfectly continent-consistent (the few exceptions are airports the source lists under two continents), while routes are mostly, not entirely, intracontinental: a declared hierarchy carries clean structure a route graph only approximates.

55.2 The tenancy rail: what the engine isolates — and what it does not

Air Routes is the clean place to make the tenancy rail honest. The engine isolates by tenant at two layers, and there is a caveat that matters. We demonstrate all three on the same engine handle, binding a tenant scope with set_tenant (an opaque UUID — the engine validates the form, never who the tenant is). The rails.tenant context manager wraps the engine’s tenant_scope and restores the prior scope on exit.

The load-bearing fact, stated plainly: “a separate source per tenant” is not data isolation. Registering region A’s airports as one source and region B’s as another keeps them apart only because they were split in Python before registration. The genuine engine properties are the two below — and the third block shows where isolation stops.

55.2.1 Layer 1 — catalog-listing isolation (a hard zero)

list_sources filters the registry to the bound tenant: tenant_id = $cur OR tenant_id IS NULL. A source registered under tenant B does not appear in tenant A’s listing.

import os

import pyarrow as pa
import pyarrow.parquet as pq

from jammi_cookbook import rails

work = tempfile.mkdtemp()
TENANT_A = "11111111-1111-1111-1111-111111111111"  # North America
TENANT_B = "22222222-2222-2222-2222-222222222222"  # Europe

na = sorted(a["code"] for a in airports if a["continent"] == "NA")
eu = sorted(a["code"] for a in airports if a["continent"] == "EU")


def register(name: str, table: pa.Table) -> None:
    path = os.path.join(work, f"{name}.parquet")
    pq.write_table(table, path)
    db.add_source(name, url=path, format="parquet")


with rails.tenant(db, TENANT_A):
    register("air_na", pa.table({"code": na}))
with rails.tenant(db, TENANT_B):
    register("air_eu", pa.table({"code": eu}))

with rails.tenant(db, TENANT_A):
    a_listed = sorted(s["source_id"] for s in db.list_sources())
print(f"tenant A lists: {a_listed}")
print(f"B's 'air_eu' visible to A: {'air_eu' in a_listed}")
tenant A lists: ['air_airports', 'air_contains', 'air_na', 'air_routes', 'arxiv_cites', 'arxiv_papers', 'arxiv_subject_golden']
B's 'air_eu' visible to A: False
claim("a source registered under tenant B is absent from tenant A's listing",
      not set(a_listed) & {"air_eu"})
✓ a source registered under tenant B is absent from tenant A's listing

55.2.2 Layer 2 — row-level isolation via a discriminator column (a hard zero)

The analyzer injects tenant_id = $cur OR IS NULL onto a TableScan only when the queried table’s schema carries a tenant_id column. So two tenants reading the same discriminator-tagged source get disjoint rows. We tag every North American airport for tenant A and every European one for tenant B in one shared source, register it globally, and query it under each tenant.

with rails.tenant(db, ""):  # a global registration: tenant_id IS NULL
    register("air_tagged", pa.table({
        "code": na + eu,
        "tenant_id": [TENANT_A] * len(na) + [TENANT_B] * len(eu),
    }))

with rails.tenant(db, TENANT_A):
    seen_a = sorted(r["code"] for r in db.sql(
        "SELECT code FROM air_tagged.public.air_tagged").to_pylist())
with rails.tenant(db, TENANT_B):
    seen_b = sorted(r["code"] for r in db.sql(
        "SELECT code FROM air_tagged.public.air_tagged").to_pylist())

print(f"tenant A reads {len(seen_a)} rows from the shared source (North America: {len(na)})")
print(f"tenant B reads {len(seen_b)} rows from the shared source (Europe: {len(eu)})")
print(f"overlap: {len(set(seen_a) & set(seen_b))}")
tenant A reads 989 rows from the shared source (North America: 989)
tenant B reads 605 rows from the shared source (Europe: 605)
overlap: 0
rails.assert_rows_isolated(seen_a, set(eu), tenant_id=TENANT_A)
claim("the discriminator gives each tenant exactly its own rows of the shared source",
      set(seen_a) == set(na) and set(seen_b) == set(eu))
✓ the discriminator gives each tenant exactly its own rows of the shared source

55.2.3 The caveat — a discriminator-less source is globally readable

This is the honest limit. A source with no tenant_id column is globally readable by any tenant that names it: there is no column for the analyzer to filter on, and the engine does not authenticate — access-gating lives above the engine (a Flight SQL / gRPC interceptor). We register Europe’s airports under tenant B with no discriminator column, then read them under tenant A.

with rails.tenant(db, TENANT_B):
    register("air_eu_nodisc", pa.table({"code": eu}))

with rails.tenant(db, TENANT_A):
    seen_global = sorted(r["code"] for r in db.sql(
        "SELECT code FROM air_eu_nodisc.public.air_eu_nodisc").to_pylist())

print(f"tenant A reads B's discriminator-less source: {len(seen_global)} of {len(eu)} rows")
tenant A reads B's discriminator-less source: 605 of 605 rows
claim("a discriminator-less source is globally readable: A reads every one of its rows",
      set(seen_global) == set(eu), f"{len(seen_global)} of {len(eu)}")
✓ a discriminator-less source is globally readable: A reads every one of its rows (605 of 605)
db.close()

Neptune-contrast. Multi-tenant isolation on a property graph is a deployment-and-governance concern Neptune leaves to IAM/VPC around the database. Here, two layers are substrate properties: set_tenant scopes catalog listing, and a tenant_id discriminator column row-filters a shared source. But the engine does not authenticate — a discriminator-less source any tenant can name is global by design, so cross-tenant data isolation is a property you opt into (a discriminator column) or gate above (an interceptor), not a blanket guarantee.