Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 178 additions & 2 deletions docs/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ HydraDBStore("bolt://127.0.0.1:17687", auth=("neo4j", "<token>"))
| `FalkorDBStore` | FalkorDB over its Redis protocol. | `falkordb` |
| `KuzuStore` | Embedded Kuzu, in process, no server. | `kuzu` |
| `HydraDBStore` | HydraDB 0.5.0 or newer. | core |
| `PgHydraDBStore` | Postgres tables that a pg_hydradb graph registers, read-only ([details](#postgres-tables-read-only)). | `postgres` |

Neo4j and Memgraph are tested on Bolt.

Expand Down Expand Up @@ -99,10 +100,10 @@ SelfGraph.connect(store="neo4j", uri="bolt://localhost:7687", auth="neo4j:passwo

| Setting | Rules |
|---------|-------|
| `store` | `hydradb`, `neo4j`, `cypher`, `memgraph` (uses `CypherStore`), `falkordb`, or `kuzu`. Unset: embedded Kuzu at `~/.selfgraph/default.kuzu` when there is no URI (needs the `kuzu` extra), and HydraDB when there is one. |
| `store` | `hydradb`, `neo4j`, `cypher`, `memgraph` (uses `CypherStore`), `falkordb`, `postgres` (uses `PgHydraDBStore`), or `kuzu`. Unset: embedded Kuzu at `~/.selfgraph/default.kuzu` when there is no URI (needs the `kuzu` extra), and HydraDB when there is one. |
| `uri` | Kuzu: the file path. A path-like URI such as `graph.kuzu` without `store="kuzu"` fails with a hint to pass it. FalkorDB: see below. An empty URI is a `ValidationError`. |
| `auth` | FalkorDB: `user:password`, or a bare password for the default user. FalkorDB takes no tokens. It wins over credentials in the URI. |
| `database` | FalkorDB: the graph name, default `selfgraph` (the `graph=` argument of `FalkorDBStore`). The graph is created on first use. |
| `database` | FalkorDB: the graph name, default `selfgraph` (the `graph=` argument of `FalkorDBStore`). The graph is created on first use. Postgres: the pg_hydradb graph name, required. |
| `namespace` | Unset means `default`. An empty or blank one is a `ValidationError`, as for `SelfGraph(namespace="")`. |

A FalkorDB `uri` is `host:port`, or a `redis://`, `rediss://`, `falkor://`, or
Expand Down Expand Up @@ -286,3 +287,178 @@ output when it is false.
For FalkorDB's optional native RESP parser, install `selfgraph[falkordb-fast]`.
The regular `falkordb` extra remains available without it.

## Postgres tables (read-only)

`PgHydraDBStore` reads tables that already live in Postgres. It uses
[pg_hydradb](https://github.com/hydra-db/hydradb/tree/main/crates/pg-hydradb),
a Postgres extension that keeps an index of the links between your tables.
A row of a vertex table is an entity. A row of an edge table is a current relation
with one version. The tables stay the source of truth: the store never writes.

You do the setup. Self Graph never changes anything in your database.

1. Build Postgres 17 with pg_hydradb. Save this as `Dockerfile`:

```dockerfile
FROM postgres:17-bookworm AS build
RUN apt-get update && apt-get install -y --no-install-recommends build-essential curl \
ca-certificates git pkg-config libclang-dev clang postgresql-server-dev-17
RUN curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain 1.99.0
ENV PATH=/root/.cargo/bin:$PATH
RUN git clone --depth 1 https://github.com/hydra-db/hydradb /src
WORKDIR /src/crates/pg-hydradb
RUN PGRX_PG_CONFIG_PATH=/usr/lib/postgresql/17/bin/pg_config \
cargo build --release --locked --no-default-features --features pg17

FROM postgres:17-bookworm
COPY --from=build /src/crates/pg-hydradb/target/release/libpg_hydradb.so /usr/lib/postgresql/17/lib/pg_hydradb.so
COPY --from=build /src/crates/pg-hydradb/pg_hydradb.control /src/crates/pg-hydradb/sql/pg_hydradb--0.1.0.sql \
/usr/share/postgresql/17/extension/
```

Then start it:

```sh
docker build -t pg-hydradb .
docker run -d --name pg-hydradb -e POSTGRES_PASSWORD=owner -p 5433:5432 pg-hydradb
```

Port 5433 keeps it clear of a Postgres that already runs on this machine.
On a server you run yourself, `just pg-install 17` in the hydradb repository
installs the extension instead. Hosted Postgres services do not offer
pg_hydradb, so use a copy of the tables in a Postgres you control.

2. Register the graph and create a login that can only read. Run this as the
table owner, for example with `docker exec -i pg-hydradb psql -U postgres`:

```sql
CREATE EXTENSION pg_hydradb;
CREATE TABLE people (id bigint PRIMARY KEY, full_name text);
CREATE TABLE companies (slug text PRIMARY KEY, name text NOT NULL);
CREATE TABLE employment (id bigint PRIMARY KEY,
person_id bigint NOT NULL REFERENCES people, company_slug text NOT NULL REFERENCES companies);
INSERT INTO people VALUES (1, 'Ann Lee'), (2, 'Bob Stone');
INSERT INTO companies VALUES ('acme', 'Acme'), ('globex', 'Globex');
INSERT INTO employment VALUES (10, 1, 'acme'), (11, 2, 'globex');
SELECT hydradb.create_graph('work',
'[{"label": "person", "table": "public.people", "key": "id"},
{"label": "company", "table": "public.companies", "key": "slug"}]',
'[{"label": "works_at", "table": "public.employment", "key": "id",
"source": "person_id", "source_label": "person",
"target": "company_slug", "target_label": "company"}]');
CREATE ROLE reader LOGIN PASSWORD 'reader-pw';
GRANT SELECT ON people, companies, employment TO reader;
```

3. Install the extra and connect:

```sh
pip install "selfgraph[postgres]"
```

```python
import asyncio

from selfgraph import SelfGraph
from selfgraph.stores.pg_hydradb import PgHydraDBStore


async def main():
store = PgHydraDBStore("postgresql://reader:[email protected]:5433/postgres", graph="work")
async with SelfGraph(store) as graph:
print(await store.draft_schema())
print((await graph.retrieve("who works at Acme")).context)
print(await graph.neighbors("company:acme"))


asyncio.run(main())
```

In TypeScript, install the `pg` driver next to the SDK:

```sh
npm install @hydradb/selfgraph pg
```

```ts
import { PgHydraDBStore, SelfGraph } from "@hydradb/selfgraph";

const store = new PgHydraDBStore("postgresql://reader:[email protected]:5433/postgres", { graph: "work" });
const graph = new SelfGraph(store);
console.log(await store.draftSchema());
console.log((await graph.retrieve("who works at Acme")).context);
await graph.close();
```

The TypeScript options are `graph`, `names`, `statementTimeout`, `seedLimit`,
and `poolSize`.

The CLI and the MCP server take the same store from settings. The URI holds
the login, and `database` names the pg_hydradb graph. The MCP server also
needs its extra, `pip install "selfgraph[postgres,mcp]"`:

```sh
selfgraph --store postgres --uri postgresql://reader:[email protected]:5433/postgres \
--database work retrieve "who works at Acme"
selfgraph --store postgres --uri postgresql://reader:[email protected]:5433/postgres \
--database work mcp --read-only
```

**Ids and names.** An entity id is the vertex label and the row key:
`person:1`, `company:acme`. A relation id is `relation:<edge label>:<key>`, such
as `relation:works_at:10`. The entity type and the relation type come from the
labels, as `Schema.from_tables` names a table (`person` is `Person`, `works_at`
is `WORKS_AT`); an edge table with a `kind` column uses each row's kind.
`draft_schema()` returns these types as a schema, with each table as a synonym and
a mapping. An entity's name is its display column: pass `names={"person":
"full_name"}`, or the store takes the first text column called `name`,
`full_name`, `display_name`, `title`, `label`, `login`, or `username`, else the
first text column. A row whose name is NULL shows its key. A store serves one
namespace (`namespace=`, default `default`; the CLI and MCP pass theirs), so two
graphs with different namespaces cannot share one store.

**What works.** `retrieve` from a question or from `entity_ids`, `neighbors`,
`find_path`, `entities.get`, `entities.find`, and `relations.get`. Each read sees
the rows as they are now: pg_hydradb's triggers update its link index in the same
transaction as the application's write.

**What is refused.** Every write raises `StoreError` with code `read_only_store`.
A read that lists or counts every row (`entities.list`, `relations.list`,
`check_answerable`, `namespaces`, `suggest_schema`) or runs Cypher raises code
`unsupported_read`; `readiness` reports the graph ready with no counts. A graph that is not registered, is paused for
`hydradb.refresh_graph`, or that the login cannot read fails `initialize` with code
`graph_unavailable`. A query that runs past `statement_timeout` (10 s by default)
raises `TransientError` with code `store_busy`.

**What the store runs.** Every statement is fixed in the code. Values are always
bound parameters, and table and column names come only from the pg_hydradb
registry, quoted. Each connection starts with `default_transaction_read_only=on`
and the `statement_timeout`, and the pool runs no reset statement. The statements
are:

- reads of `hydradb.graphs`, `hydradb.graph_vertex_tables`, and
`hydradb.graph_edge_tables`, with the catalog rows that name their tables and
columns;
- `hydradb.reachable_edges(graph, seeds, options)` for one hop at a time;
- `SELECT <key>, <columns> FROM <registered table> WHERE <key> = ANY(...)`;
- `SELECT <key>, <name> FROM <registered table> WHERE <name> ILIKE $1 LIMIT $2`,
once per table and query word, to find the rows a question names.

The name lookup reads up to `seed_limit` (200) rows per table and word. A
trigram index makes it fast on a large table:

```sql
CREATE EXTENSION pg_trgm;
CREATE INDEX people_full_name_trgm ON people USING gin (full_name gin_trgm_ops);
```

**Limits.** One hop reads at most 5,000 edges per row, pg_hydradb's limit; a row
with more edges is read partially and the result has `truncated` set to true.
pg_hydradb still loads every edge of such a row, about 0.5 s for 50,000 edges.
pg_hydradb refuses walks for a login that row-level security applies to. An edge
label or kind whose type Self Graph keeps for its own edges (such as `prefers` or
`has_profile`) fails with `graph_unavailable`; register it under another label. Name
lookups use Postgres `ILIKE`, so a spelling that differs only by full Unicode case
folding (`ß` and `ss`) is not found. A text
key is reachable by id only when it is already in id form: lowercase, with no
spaces. Rows carry no other properties, sources, or history.
6 changes: 3 additions & 3 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ or `--contradiction` on an insert or `relation create`) wins after it.

| Flag | Meaning |
|------|---------|
| `--store` | `hydradb`, `neo4j`, `cypher`, `memgraph`, `falkordb`, or `kuzu`. Default: embedded `kuzu` at `~/.selfgraph/default.kuzu`, or `hydradb` when `--uri` is given. So a Kuzu path needs `--store kuzu --uri graph.kuzu`. |
| `--uri` | Bolt URI for the Bolt stores. File path for `kuzu`. `host:port` or a `redis://`, `rediss://`, `falkor://`, or `falkors://` URL for `falkordb` ([details](backends.md#from-settings)). |
| `--store` | `hydradb`, `neo4j`, `cypher`, `memgraph`, `falkordb`, `postgres` (read-only Postgres tables, see [Backends](backends.md#postgres-tables-read-only)), or `kuzu`. Default: embedded `kuzu` at `~/.selfgraph/default.kuzu`, or `hydradb` when `--uri` is given. So a Kuzu path needs `--store kuzu --uri graph.kuzu`. |
| `--uri` | Bolt URI for the Bolt stores. File path for `kuzu`. `host:port` or a `redis://`, `rediss://`, `falkor://`, or `falkors://` URL for `falkordb` ([details](backends.md#from-settings)). A `postgresql://` URI with the login for `postgres`. |
| `--auth` | `user:password`, or a bare token with user `neo4j`. For `falkordb`, `user:password` or a bare password for the default user; it wins over credentials in the URI. |
| `--database` | Bolt: database name (default: the server default). FalkorDB: graph name (default `selfgraph`). |
| `--database` | Bolt: database name (default: the server default). FalkorDB: graph name (default `selfgraph`). Postgres: the pg_hydradb graph name, required. |
| `--namespace` | Graph namespace, default `default`. |
| `--llm-provider`, `--llm-model`, `--llm-api-key`, `--llm-base-url` | LLM settings for `insert text`. A provider-prefixed model such as `openai/gpt-4o-mini` needs no `--llm-provider`. Routers such as `openrouter`, and any `--llm-base-url`, take vendor-prefixed models. |
| `--llm-timeout` | Seconds to wait for each LLM call, default 120. A positive decimal or exponent number in ASCII digits, such as `30`, `1.5`, or `1e1`; no underscores, no `0x` prefix. |
Expand Down
81 changes: 78 additions & 3 deletions scripts/probes/secret_echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,76 @@ async def _mcp(store_kind, uri, password):
return text


async def _postgres(password):
"""Open the postgres store with a marker password in its URI on every entry point and capture the failures.

@param password (str): the marker password.
@return (list[tuple[str, str]]): (path, captured text) per entry point.
"""
from urllib.parse import quote

import selfgraph.mcp.server as srv
from selfgraph.cli import main
from selfgraph.runtime import GraphSettings, build_graph
from selfgraph.stores.pg_hydradb import PgHydraDBStore

uri = f"postgresql://reader:{quote(password, safe='')}@127.0.0.1:1/app"
settings = GraphSettings(store="postgres", uri=uri, database="work")
calls = [
("api.direct", lambda: selfgraph_call(PgHydraDBStore(uri, graph="work"))),
("api.settings", lambda: build_graph(settings).entities.get("person:1")),
("mcp", lambda: _postgres_mcp(srv, settings)),
]
out = [("cli", await asyncio.to_thread(_postgres_cli, main, uri))]
for path, call in calls:
buffer = io.StringIO()
try:
with redirect_stdout(buffer), redirect_stderr(buffer):
await call()
except Exception as exc: # noqa: BLE001
buffer.write(_chain_text(exc))
out.append((path, buffer.getvalue()))
return out


def _postgres_cli(main, uri):
"""Run the CLI against the dead postgres store and capture both streams.

@param main (Callable): the CLI entry point.
@param uri (str): the URI with the marker password.
@return (str): stdout and stderr.
"""
stdout, stderr = (io.TextIOWrapper(io.BytesIO(), encoding="utf-8", write_through=True) for _ in range(2))
with redirect_stdout(stdout), redirect_stderr(stderr):
main(["--store", "postgres", "--uri", uri, "--database", "work", "entity", "get", "person:1"])
return _text(stdout) + _text(stderr)


def selfgraph_call(store):
"""Read one entity through a graph over a store.

@param store (Any): the store.
@return (Awaitable): the read.
"""
import selfgraph

return selfgraph.SelfGraph(store=store).entities.get("person:1")


async def _postgres_mcp(srv, settings):
"""Configure the MCP server for the postgres store and call one tool.

@param srv (module): the MCP server module.
@param settings (GraphSettings): the settings.
@return (Any): the tool result, an error payload.
"""
try:
await srv.configure(settings)
print(await srv.get_entity(id="person:1"))
finally:
await srv.close()


async def run(store_kind):
"""Run every entry point for every marker password and collect any leaks.

Expand All @@ -154,11 +224,14 @@ async def run(store_kind):
leaks = []
for password in PASSWORDS:
token = password[password.index("TOKEN") : password.index("END") + 3]
if store_kind == "postgres":
leaks += [(path, password, token) for path, text in await _postgres(password) if token in text]
continue
checks = [
("api.direct", await _api_direct(store_kind, DEAD_URI, password)),
("api.settings", await _api_settings(store_kind, DEAD_URI, password, embed=False)),
("api.uri_embedded", await _api_settings(store_kind, DEAD_URI, password, embed=True)),
("cli", _cli(store_kind, DEAD_URI, password)),
("cli", await asyncio.to_thread(_cli, store_kind, DEAD_URI, password)),
("mcp", await _mcp(store_kind, DEAD_URI, password)),
]
for path, text in checks:
Expand All @@ -174,10 +247,12 @@ def main(argv=None):
@return (int): 0 when nothing leaked, 1 otherwise.
"""
parser = argparse.ArgumentParser(description="Force connection failures with a marker password and grep for it.")
parser.add_argument("--store", default="neo4j", choices=["neo4j", "hydradb", "cypher"], help="bolt store kind")
stores = ["neo4j", "hydradb", "cypher", "postgres"]
parser.add_argument("--store", default="neo4j", choices=stores, help="store kind")
args = parser.parse_args(argv)
leaks = asyncio.run(run(args.store))
print(f"secret-echo scan: store {args.store}, {len(PASSWORDS)} passwords, 5 paths each")
paths = 4 if args.store == "postgres" else 5
print(f"secret-echo scan: store {args.store}, {len(PASSWORDS)} passwords, {paths} paths each")
print(" target is a dead port (127.0.0.1:1); no real server is contacted")
if leaks:
for path, password, token in leaks:
Expand Down
Loading
Loading