diff --git a/docs/backends.md b/docs/backends.md index bdafc636..7ddb4803 100644 --- a/docs/backends.md +++ b/docs/backends.md @@ -21,6 +21,7 @@ HydraDBStore("bolt://127.0.0.1:17687", auth=("neo4j", "")) | `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. @@ -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 @@ -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:reader-pw@127.0.0.1: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:reader-pw@127.0.0.1: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:reader-pw@127.0.0.1:5433/postgres \ + --database work retrieve "who works at Acme" + selfgraph --store postgres --uri postgresql://reader:reader-pw@127.0.0.1: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::`, 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 , FROM WHERE = ANY(...)`; +- `SELECT , FROM WHERE 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. diff --git a/docs/cli.md b/docs/cli.md index f4177561..1345e93e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -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. | diff --git a/scripts/probes/secret_echo.py b/scripts/probes/secret_echo.py index 9ff372cb..8db38feb 100644 --- a/scripts/probes/secret_echo.py +++ b/scripts/probes/secret_echo.py @@ -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. @@ -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: @@ -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: diff --git a/src/selfgraph/runtime.py b/src/selfgraph/runtime.py index 2b63d123..41ed0075 100644 --- a/src/selfgraph/runtime.py +++ b/src/selfgraph/runtime.py @@ -96,8 +96,9 @@ _log = logging.getLogger("selfgraph") -STORES = ("neo4j", "cypher", "memgraph", "hydradb", "falkordb", "kuzu") -_IGNORED_BY_STORE = {"kuzu": ("auth", "database")} +STORES = ("neo4j", "cypher", "memgraph", "hydradb", "falkordb", "postgres", "kuzu") +_IGNORED_BY_STORE = {"kuzu": ("auth", "database"), "postgres": ("auth",)} +_POSTGRES_SCHEMES = ("postgres", "postgresql") _FALKOR_SCHEMES = ("redis", "rediss", "falkor", "falkors") _FALKOR_ADDRESS = "host:port or a redis://, rediss://, falkor://, or falkors:// URL" _PARAM_REF = re.compile(r"\$(\w+)") @@ -452,6 +453,26 @@ def _falkor_address(uri: str) -> tuple[Any, int | None, bool]: return parsed, port, scheme in ("rediss", "falkors") +def _require_postgres(settings: GraphSettings) -> None: + """Reject a postgres store setting without a postgresql:// URI or without the pg_hydradb graph name. + + @param settings (GraphSettings): the resolved settings. + @return (None): nothing; raises ValidationError with code invalid_setting. + """ + if split_scheme(settings.uri)[0].lower() not in _POSTGRES_SCHEMES: + raise ValidationError( + "invalid Postgres address: the 'postgres' store expects a postgresql:// URI", + code="invalid_setting", + field="uri", + ) + if not settings.database: + raise ValidationError( + f"the 'postgres' store needs the pg_hydradb graph name; pass {setting_hint('database')}", + code="invalid_setting", + field="database", + ) + + def _url_unquote(text: str) -> str: """Decode the percent escapes of a URL user or password, rejecting a malformed escape as the TypeScript SDK does. @@ -531,6 +552,10 @@ def _build_store(settings: GraphSettings) -> GraphStore: return store_cls(settings.uri, auth=settings.auth, database=settings.database) if kind == "falkordb": return _falkor_store(settings.uri, settings) + if kind == "postgres": + from .stores.pg_hydradb import PgHydraDBStore + + return PgHydraDBStore(settings.uri, graph=settings.database, namespace=settings.namespace or "default") from .stores.hydradb import HydraDBStore return HydraDBStore(settings.uri, auth=settings.auth, database=settings.database) @@ -666,13 +691,15 @@ def check_settings(settings: GraphSettings) -> GraphSettings: ) if kind != "kuzu": if not settings.uri: - address = _FALKOR_ADDRESS if kind == "falkordb" else "a Bolt URI" + address = {"falkordb": _FALKOR_ADDRESS, "postgres": "a postgresql:// URI"}.get(kind, "a Bolt URI") raise ValidationError( f"the {kind!r} store needs {address}; pass {setting_hint('uri')}", code="invalid_setting", field="uri" ) _require_server_uri(kind, settings.uri) if kind == "falkordb": _falkor_address(settings.uri) + if kind == "postgres": + _require_postgres(settings) require_schema_mode(settings.schema_mode or "warn") require_level("level", settings.level or "balanced") require_level("max_tier", settings.max_tier or "max") diff --git a/tests/test_pg_hydradb_store.py b/tests/test_pg_hydradb_store.py index 83799dcd..f602c4dd 100644 --- a/tests/test_pg_hydradb_store.py +++ b/tests/test_pg_hydradb_store.py @@ -204,3 +204,19 @@ async def counted(sql, *args): run(g.store.close()) later_page = g.store.match_edges("default", from_label="Entity", to_in=["company:globex"], skip=500) assert _code(lambda: later_page) == "store_closed" + + +def test_the_cli_and_the_mcp_server_read_the_graph_from_settings(work, capsys): + import selfgraph.mcp.server as srv + from selfgraph.cli import main + from selfgraph.runtime import GraphSettings + + name, reader = work + assert main(["--store", "postgres", "--uri", reader, "--database", name, "path", "person:2", "company:acme"]) == 0 + assert "company:acme" in capsys.readouterr().out + run(srv.configure(GraphSettings(store="postgres", uri=reader, database=name, read_only=True))) + try: + result = run(srv.retrieve(query="who works at Acme")) + assert "GRAPH | Ann Lee -[WORKS_AT]-> Acme" in result["context"] + finally: + run(srv.close()) diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 29d65629..c24dcb10 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -853,3 +853,16 @@ def test_falkordb_nested_values_preserve_nulls_and_nonfinite_numbers(): assert _to_json({"values": (None, float("nan"), float("inf"), float("-inf"), 2.5)}) == { "values": [None, None, None, None, 2.5] } + + +def test_the_postgres_store_needs_a_postgresql_uri_and_a_graph_name(): + from selfgraph.stores.pg_hydradb import PgHydraDBStore + + with pytest.raises(ValidationError, match="expects a postgresql:// URI") as bad_uri: + check_settings(GraphSettings(store="postgres", uri="bolt://reader:pw@h/db", database="work")) + with pytest.raises(ValidationError, match="needs the pg_hydradb graph name") as no_graph: + check_settings(GraphSettings(store="postgres", uri="postgresql://reader:pw@h/db")) + assert (bad_uri.value.field, no_graph.value.field) == ("uri", "database") + assert "pw" not in str(bad_uri.value) + g = build_graph(GraphSettings(store="postgres", uri="postgresql://reader:pw@h/db", database="work")) + assert isinstance(g.store, PgHydraDBStore) and g.store._graph == "work" diff --git a/typescript/src/runtime.ts b/typescript/src/runtime.ts index 8c2b7a30..bf3e4d38 100644 --- a/typescript/src/runtime.ts +++ b/typescript/src/runtime.ts @@ -58,6 +58,7 @@ import { CypherStore, Neo4jStore } from "./stores/cypher.js"; import { FalkorDBStore } from "./stores/falkordb.js"; import { HydraDBStore } from "./stores/hydradb.js"; import { KuzuStore } from "./stores/kuzu.js"; +import { PgHydraDBStore } from "./stores/pgHydradb.js"; import { clamp, type Level, PRESETS, requireLevel } from "./tiers.js"; import { checkOptions, isUnstorable, MAX_JSON_DEPTH, requireCleanJson, requireNamespace } from "./validate.js"; @@ -110,7 +111,10 @@ export const DEFAULT_SETTINGS: Readonly = Object.freeze({ read_only: null, }); -const IGNORED_BY_STORE: Record> = { kuzu: ["auth", "database"] }; +const IGNORED_BY_STORE: Record> = { + kuzu: ["auth", "database"], + postgres: ["auth"], +}; const FALKOR_SCHEMES = ["redis", "rediss", "falkor", "falkors"]; const FALKOR_ADDRESS = "host:port or a redis://, rediss://, falkor://, or falkors:// URL"; const PARAM_REF = new RegExp(`\\$([${PY_WORD_CLASS}]+)`, "gu"); @@ -648,8 +652,34 @@ const SERVER_STORES: Record new CypherStore(uri, boltOptions(s)) }, hydradb: { address: "a Bolt URI", build: (uri, s) => new HydraDBStore(uri, boltOptions(s)) }, falkordb: { address: FALKOR_ADDRESS, build: falkorStore }, + postgres: { + address: "a postgresql:// URI", + build: (uri, s) => + new PgHydraDBStore(uri, { graph: s.database!, namespace: s.namespace ?? DEFAULT_SETTINGS.namespace }), + }, }; +/** + * Reject a postgres store setting without a postgresql URI or without the pg_hydradb graph name. + * + * @param uri (string): the configured URI. + * @param database (string | null): the configured graph name. + */ +function requirePostgres(uri: string, database: string | null): void { + if (!["postgres", "postgresql"].includes(splitScheme(uri)[0].toLowerCase())) { + throw new ValidationError("invalid Postgres address: the 'postgres' store expects a postgresql:// URI", { + code: "invalid_setting", + field: "uri", + }); + } + if (!database) { + throw new ValidationError(`the 'postgres' store needs the pg_hydradb graph name; pass ${settingHint("database")}`, { + code: "invalid_setting", + field: "database", + }); + } +} + export const STORES: readonly string[] = [...Object.keys(SERVER_STORES), "kuzu"]; /** @@ -723,6 +753,7 @@ export function buildStore(settings: GraphSettings): GraphStore { const server = SERVER_STORES[kind]; if (server === undefined) throw unknownStore(settings); requireStoreUri(kind, settings.uri); + if (kind === "postgres") requirePostgres(settings.uri!, settings.database); return server.build(settings.uri!, settings); } @@ -853,6 +884,7 @@ export function checkSettings(settings: GraphSettings): GraphSettings { const kind = storeKind(settings); if (!STORES.includes(kind)) throw unknownStore(settings); if (kind !== "kuzu") requireStoreUri(kind, settings.uri); + if (kind === "postgres") requirePostgres(settings.uri!, settings.database); requireSchemaMode(settings.schema_mode || "warn"); requireLevel("level", settings.level || "balanced"); requireLevel("max_tier", settings.max_tier || "max"); diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 9a0a53a2..b02ad59e 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -93,6 +93,7 @@ _llm_concurrency, _llm_timeout, _read_only, + check_settings, dumps, namespace_listing, parse_json, @@ -103,6 +104,7 @@ ) from selfgraph.schema import validate_against_schema from selfgraph.stores.kuzu import _kuzu_error +from selfgraph.stores.pg_hydradb import PgHydraDBStore from selfgraph.terms import expand_tokens, schema_forms LENIENT_EVENT_TIMES = [ @@ -2068,6 +2070,18 @@ async def _raise_later(exc): raise exc +DEAD_PG = "postgresql://reader:secret@127.0.0.1:1/app" + + +async def _checked(settings): + """Validate settings inside a coroutine, so error_of can await the failure. + + @param settings (GraphSettings): the settings. + @return (None): nothing; raises what check_settings raises. + """ + check_settings(settings) + + async def error_of(call): """Await a call that should fail and return its error as the wire fields both SDKs report. @@ -2199,6 +2213,10 @@ async def choice_errors(graph): "read_only_store": await error_of(_raise_later(read_only_store("upsert_node"))), "unsupported_read": await error_of(_raise_later(unsupported_read("list every entity"))), "graph_unavailable": await error_of(_raise_later(graph_unavailable("it's", "is not registered"))), + "postgres_write": await error_of(PgHydraDBStore(DEAD_PG, graph="work").upsert_node("n", "Entity", "x", {})), + "postgres_scan": await error_of(PgHydraDBStore(DEAD_PG, graph="work").count_nodes_by_ns("Entity")), + "postgres_uri": await error_of(_checked(GraphSettings(store="postgres", uri="bolt://u:p@h/db", database="g"))), + "postgres_graph": await error_of(_checked(GraphSettings(store="postgres", uri=DEAD_PG))), "list_limit_zero": await error_of(graph.entities.list(limit=0)), "list_limit_text": await error_of(graph.entities.list(limit="5")), "list_limit_float_non_integer": await error_of(graph.entities.list(limit=5.5)), diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index 891fab54..ad264ab7 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -70,6 +70,7 @@ import { NotFoundError, neighborsDot, neighborsMermaid, + PgHydraDBStore, SelfGraph, SelfGraphError, toJsonable, @@ -104,6 +105,7 @@ import { dumps } from "../../src/output.js"; import { tokens } from "../../src/retrieval.js"; import { buildLlm, + checkSettings, DEFAULT_SETTINGS, falkorCredentials, globPattern, @@ -114,6 +116,7 @@ import { readOnlySetting, SYNC_GLOBS, scanFolder, + settingsFromEnv, syncFiles, } from "../../src/runtime.js"; import { Schema, validateAgainstSchema } from "../../src/schema.js"; @@ -2480,6 +2483,8 @@ const USES_SPEC = { class Opaque {} +const DEAD_PG = "postgresql://reader:secret@127.0.0.1:1/app"; + /** * Run a call that should fail and return its error as the wire fields both SDKs report. * @@ -2630,6 +2635,14 @@ async function choiceErrors(graph: SelfGraph): Promise { throw graphUnavailable("it's", "is not registered"); }), + postgres_write: await errorOf(() => + new PgHydraDBStore(DEAD_PG, { graph: "work" }).upsertNode("n", "Entity", "x", {}), + ), + postgres_scan: await errorOf(() => new PgHydraDBStore(DEAD_PG, { graph: "work" }).countNodesByNs()), + postgres_uri: await errorOf(async () => + checkSettings(settingsFromEnv({ store: "postgres", uri: "bolt://u:p@h/db", database: "g" }, {})), + ), + postgres_graph: await errorOf(async () => checkSettings(settingsFromEnv({ store: "postgres", uri: DEAD_PG }, {}))), list_limit_zero: await errorOf(() => graph.entities.list({ limit: 0 })), list_limit_text: await errorOf(() => graph.entities.list({ limit: "5" } as never)), list_limit_float_non_integer: await errorOf(() => graph.entities.list({ limit: 5.5 })), diff --git a/typescript/test/pgHydradbStore.test.ts b/typescript/test/pgHydradbStore.test.ts index 206b445e..c388148f 100644 --- a/typescript/test/pgHydradbStore.test.ts +++ b/typescript/test/pgHydradbStore.test.ts @@ -4,7 +4,9 @@ import { readFileSync } from "node:fs"; import pg from "pg"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { PgHydraDBStore, SelfGraph, StoreError } from "../src/index.js"; +import { PgHydraDBStore, SelfGraph, StoreError, type ValidationError } from "../src/index.js"; +import { callTool, close, configure } from "../src/mcp.js"; +import { buildStore, checkSettings, settingsFromEnv } from "../src/runtime.js"; const OWNER_URI = process.env.SG_PG_HYDRADB_URI ?? process.env.PG_HYDRADB_URI; const PROJECT = "3f2b8c1e-8f5c-4c2a-9d7e-1a2b3c4d5e6f"; @@ -48,6 +50,27 @@ it("a password in the uri query stays out of errors", () => { ]); }); +it("the postgres store needs a postgresql uri and a graph name", () => { + const fail = (settings: Record): ValidationError => { + try { + checkSettings(settingsFromEnv({ store: "postgres", ...settings }, {})); + } catch (exc) { + return exc as ValidationError; + } + throw new Error("accepted"); + }; + const badUri = fail({ uri: "bolt://reader:pw@h/db", database: "work" }); + const noGraph = fail({ uri: "postgresql://reader:pw@h/db" }); + expect([badUri.field, noGraph.field]).toEqual(["uri", "database"]); + expect(badUri.message).toContain("expects a postgresql:// URI"); + expect(badUri.message).not.toContain("pw"); + expect(noGraph.message).toContain("needs the pg_hydradb graph name"); + const store = buildStore( + settingsFromEnv({ store: "postgres", uri: "postgresql://reader:pw@h/db", database: "work" }, {}), + ); + expect(store).toBeInstanceOf(PgHydraDBStore); +}); + describe.skipIf(!OWNER_URI)("PgHydraDBStore", () => { let name = ""; let reader = ""; @@ -215,6 +238,16 @@ describe.skipIf(!OWNER_URI)("PgHydraDBStore", () => { expect(await codeOf(laterPage)).toBe("store_closed"); }); + it("the mcp server reads the graph from settings", async () => { + await configure(settingsFromEnv({ store: "postgres", uri: reader, database: name, read_only: "true" }, {})); + try { + const found = await callTool("retrieve", { query: "who works at Acme" }); + expect((found.result as { context: string }).context).toContain("GRAPH | Ann Lee -[WORKS_AT]-> Acme"); + } finally { + await close(); + } + }); + it("a walk cut by pg_hydradb marks the result truncated", async () => { await owner(`INSERT INTO ${name}.people SELECT g, 'P' || g FROM generate_series(100, 5200) g`); await owner(`INSERT INTO ${name}.employment SELECT g, g, 'globex' FROM generate_series(100, 5200) g`);