Metadata-Version: 2.4
Name: ghost-graph
Version: 0.1.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Requires-Dist: pytest>=8 ; extra == 'test'
Provides-Extra: test
License-File: LICENSE
Summary: Keys and edges of an ontology's relationships in compressed sparse rows, walked in memory
License-Expression: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/arango-solutions-org/ghost-graph

# ghost-graph

> The name is a nod to *The Ghost Map* (Steven Johnson, 2006): in 1854 John
> Snow mapped the Broad Street cholera deaths and found the pump nobody could
> see. A ghost graph holds the shape of the connections, while the data stays
> in the systems that own it until a question asks for it. "Ghost" means the
> data is not here, not that the answer is not grounded: every value an answer
> shows is fetched from its source and cited.

Keys and edges of an ontology's relationships, held in compressed sparse rows
and walked in memory. This is the **topology tier** of the Contextual Data
Fabric (CDF ADR-0011, module M13).

It holds **no property values**. A walk returns canonical keys, and the caller
fetches whatever values its answer shows from the sources that own them.

- **Named in the ontology.** Every class and relationship is registered by IRI,
  and a built `Topology` carries the manifest `contentHash` it was built against.
- **One id per entity.** Classes that share a canonical key share a key space.
  Class membership is a bitmap, and a superclass includes its subclasses'
  members.
- **SPARQL's two semantics.** `expand` (fixed hops) returns one row per path;
  `reachable` (`+` / `*`) returns each (start, end) pair once.
- **Refuses, never truncates.** A walk over its limit raises
  `TopologyLimitExceeded`. A foreign key that points at nothing is dropped and
  counted in `relationship_stats`.

The CSR core is [`graph_builder`](https://github.com/neo4j-labs/graph), pinned
exactly, and connected components are the same project's `graph` crate, pinned
the same way; this crate owns the API above them. PageRank is ghost-graph's
own, so its scores repeat exactly and match the usual PageRank.

## Install

```sh
pip install ghost-graph
```

Wheels are built for Linux (x86_64, aarch64) and macOS (x86_64, arm64), for
Python 3.11 and later; elsewhere pip builds from source, which needs Rust.
Releases are described in [RELEASE.md](RELEASE.md).

## Use

```python
from ghost_graph import TopologyBuilder

b = TopologyBuilder(manifest_hash, as_of)
b.add_class("urn:c#Account", "account", ["a1", "a2"])
b.add_class("urn:c#Contact", "contact", ["c1"])
b.add_relationship("urn:c#contactsToAccounts", "urn:c#Contact", "urn:c#Account", [("c1", "a1")])
t = b.build()
t.expand("urn:c#Contact", ["c1"], [("urn:c#contactsToAccounts", "out", None)], limit=1000)

# From every Contact, landing only on accounts a source has already filtered:
t.expand("urn:c#Contact", None, [("urn:c#contactsToAccounts", "out", None, ["a1"])], limit=1000)
```

`None` for the start keys walks from every member of the start class; an
empty list matches nothing. A step's optional fourth element (and
`reachable`'s `target_keys`) narrows where the walk lands. Those keys are read
in the landing class's key space, so a key from another key space matches
nothing.

A walk's `limit` counts its starts as well as its rows (`expand`) or pairs
(`reachable`), so a whole-class walk on a class larger than the limit is
refused before it starts.

`limit` bounds what a walk returns and holds, not how much it reads: a hop
reads every neighbour of the paths it extends, landing or not, and each start
of `reachable` searches everything it can reach, whether or not it lands on
`target_keys`. The keyword-only `max_visits` bounds that work: for `expand` and
`expand_columns`, every neighbour a hop reads, over all hops; for `reachable`,
every node a search visits (its start, then each node it reaches for the first
time), over all starts. A walk that would make more visits raises
`TopologyLimitExceeded` before it reads them. The default, `None`, sets no
budget. A budget never changes an answer: the walk returns what it would
without one, or is refused.

```python
t.reachable("urn:c#Account", None, "urn:c#parentAccount",
            target_keys=["a3"], limit=1000, max_visits=1_000_000)
```

Classes and subclass links come before the first relationship, which makes
class membership final; one added after it is refused. A relationship's pairs
can then arrive in batches (`extend_relationship`) and build exactly as if
added at once.

## Analytics

PageRank, weakly connected components and shortest paths run over one class's
members and the edges of one or more relationships between them (CDF M13 FR-8):

```python
ranks, iterations, error = t.page_rank("urn:c#Account", ["urn:c#parentAccount"], limit=1_000_000)
components = t.connected_components("urn:c#Account", ["urn:c#parentAccount"], limit=1_000_000)
paths = t.shortest_paths("urn:c#Account", ["urn:c#parentAccount"], "a1", limit=1_000_000)
```

- **Nodes** are every member of the class, including members no edge touches,
  so PageRank's node total and the components of one are right. **Edges** are
  the relationships' pairs with both ends members, so a subclass gets the
  subgraph its members induce. A pair held by two of the relationships is one
  edge; a pair `(u, u)` is a self-loop and is kept.
- Every relationship must run from the class's key space to itself. Between two
  key spaces an id names two different entities, and one graph over both would
  join them; that is refused.
- **PageRank** is directed: a relationship given as its IRI is followed from
  domain to range, or give `(iri, "in")` to reverse it. The defaults are
  `damping=0.85`, `max_iterations=20`, `tolerance=1e-4`. Scores come back as
  `(key, score)` in the class's id order, with the iterations run and the last
  iteration's total change, so a run that stopped at `max_iterations` before
  converging says so. They are the usual PageRank (networkx's): a node with no
  out-edge shares its score with every node, and the scores sum to 1.
- **Components** are weak (edges followed either way): each is a list of keys
  in id order, components in the order of their first member.
- **Shortest paths** count hops from one source (edges carry no weight; the
  tier holds no property values). Each member reached comes back as
  `(key, distance, parent)` in id order, `parent` being the member before it
  on a shortest path, the lowest-id one among equals, and `None` for the
  source. A source that is not a member of the class reaches nothing.
  Relationships are given as for PageRank.
- **Limits.** PageRank and components return one row per member, so a class
  with more members than `limit` is refused before anything is built. Shortest
  paths refuse once more than `limit` members are reached.
- **Determinism.** Keys and their order are fixed by the snapshot. Component
  membership is exact, and so are shortest paths. PageRank runs on one thread and adds in a fixed order,
  so the same snapshot and parameters give the same scores bit for bit, and a
  sort by score gives the same order every run.

All three release the GIL. PageRank and components build the graph they run
over for the call and drop it after: at its peak, while it is built, up to
about 24 bytes per edge. Shortest paths read the relationships as held and
build nothing.

## Develop

```sh
cargo test && cargo clippy --all-targets --features python
uv venv .venv && uv pip install --python .venv/bin/python maturin pytest
VIRTUAL_ENV=$PWD/.venv .venv/bin/maturin develop --release
VIRTUAL_ENV=$PWD/.venv .venv/bin/python -m pytest tests
VIRTUAL_ENV=$PWD/.venv .venv/bin/python scripts/smoke_scale.py
```

Set `VIRTUAL_ENV` explicitly: `maturin develop` installs into whatever virtual
environment is active, which in a shell opened for another project is that
project's.

