From d976b66d19e1451139ffeac57c5a3d6f18a80918 Mon Sep 17 00:00:00 2001 From: adityamishra-hydradb <321510987+adityamishra-hydradb@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:20:15 +0530 Subject: [PATCH] Read Postgres tables through pg_hydradb with a read-only store Signed-off-by: adityamishra-hydradb <321510987+adityamishra-hydradb@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 1 + src/selfgraph/stores/pg_hydradb.py | 708 +++++++++++++++++++++++++++++ tests/fixtures/pg_hydradb_work.sql | 30 ++ tests/test_errors.py | 24 +- tests/test_pg_hydradb_store.py | 180 ++++++++ 5 files changed, 937 insertions(+), 6 deletions(-) create mode 100644 src/selfgraph/stores/pg_hydradb.py create mode 100644 tests/fixtures/pg_hydradb_work.sql create mode 100644 tests/test_pg_hydradb_store.py diff --git a/pyproject.toml b/pyproject.toml index 79e218bf..24f99fbb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,7 @@ ner = ["spacy>=3.0"] falkordb = ["falkordb>=1.0"] falkordb-fast = ["falkordb>=1.0", "hiredis>=3.2.0"] kuzu = ["kuzu>=0.6"] +postgres = ["asyncpg>=0.30"] mcp = ["mcp>=2.2"] otel = ["opentelemetry-api>=1.20"] code = [ diff --git a/src/selfgraph/stores/pg_hydradb.py b/src/selfgraph/stores/pg_hydradb.py new file mode 100644 index 00000000..5959e498 --- /dev/null +++ b/src/selfgraph/stores/pg_hydradb.py @@ -0,0 +1,708 @@ +from __future__ import annotations + +import asyncio +import json +import re +from collections.abc import Iterable, Mapping +from contextlib import asynccontextmanager +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Any +from urllib.parse import unquote + +from .._serde import EDGE_TYPES, L_ENTITY, encode_entity_props, encode_relation_props +from .._tables import _words, from_tables +from ..errors import ( + STORE_CLOSED_MESSAGE, + SetupError, + StoreError, + TransientError, + ValidationError, + connection_reason, + error_reason, + escape_controls, + graph_unavailable, + mask_uri, + read_only_store, + redact_uri, + require_encoded_userinfo, + unsupported_read, +) +from ..ids import normalize_rel_type, slug +from ..models import as_input +from ..retrieval import mark_partial +from ..schema import Schema + +__all__ = ["PgHydraDBStore"] + +_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) +_NAME_COLUMNS = ("name", "full_name", "display_name", "title", "label", "login", "username") +_CASTS = {"smallint": "bigint", "integer": "bigint", "bigint": "bigint", "uuid": "uuid"} +_SEEDS_PER_WALK = 128 +_MAX_EDGES = 5000 +_SEED_TERMS = 16 +_GRAPH = "SELECT needs_refresh FROM hydradb.graphs WHERE name = $1" +_TABLES = """SELECT t.label, n.nspname, c.relname, t.key_column::text AS key, format_type(k.atttypid, NULL) AS key_type, +has_table_privilege(c.oid, 'SELECT') AS readable, {extra} +FROM hydradb.{registry} t JOIN pg_class c ON c.oid = t.relation JOIN pg_namespace n ON n.oid = c.relnamespace +JOIN pg_attribute k ON k.attrelid = c.oid AND k.attname = t.key_column WHERE t.graph = $1 ORDER BY t.label""" +_VERTEX_TABLES = _TABLES.format( + registry="graph_vertex_tables", + extra="ARRAY(SELECT a.attname::text FROM pg_attribute a WHERE a.attrelid = c.oid AND a.attnum > 0 " + "AND NOT a.attisdropped AND a.atttypid IN ('text'::regtype, 'varchar'::regtype, 'bpchar'::regtype) " + "ORDER BY a.attnum) AS text_columns", +) +_EDGE_TABLES = _TABLES.format( + registry="graph_edge_tables", + extra="t.source_column::text AS source, t.source_label, t.target_column::text AS target, t.target_label, " + "t.kind_column::text AS kind", +) +_WALK = ( + "SELECT w->'truncated' AS truncated, (SELECT coalesce(jsonb_agg(jsonb_build_array(i->>'label', i->>'key')), " + "'[]') FROM jsonb_array_elements(w->'items') i) AS items FROM hydradb.reachable_edges($1, $2::jsonb, $3::jsonb) w" +) +_WRITES = ( + "lock_node", + "upsert_node", + "upsert_nodes", + "create_edge", + "create_edges", + "update_current_edge", + "remove_node_label", + "delete_node", + "delete_nodes", + "delete_nodes_by", + "delete_edges", + "delete_edges_touching_by_type", +) + + +def _ident(name: str) -> str: + """Quote a Postgres identifier read from the pg_hydradb registry. + + @param name (str): the raw identifier. + @return (str): the identifier in double quotes, inner quotes doubled. + """ + return '"' + name.replace('"', '""') + '"' + + +def _like(text: str) -> str: + """Escape the LIKE wildcards and the escape character in text. + + @param text (str): the literal text. + @return (str): the text, matched literally by ILIKE. + """ + return re.sub(r"([\\%_])", r"\\\1", text) + + +@dataclass(frozen=True) +class _Table: + label: str + prefix: str + ref: str + type: str + key: str + cast: str + name: str | None = None + source: str = "" + source_label: str = "" + target: str = "" + target_label: str = "" + kind: str | None = None + + def key_of(self, text: str) -> Any: + """Read one key from the text after an id's colon, typed as the key column is. + + @param text (str): the key text. + @return (Any): an int, a uuid string, or the text; None when the text cannot be a key of this table. + """ + if self.cast == "bigint": + return int(text) if re.fullmatch(r"-?[0-9]{1,19}", text) and -(2**63) <= int(text) < 2**63 else None + if self.cast == "uuid": + return text if re.fullmatch(r"[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}", text) else None + return text + + def lookup(self, columns: str, where: str) -> str: + """Build the fixed read of some columns of this table's rows. + + @param columns (str): the quoted columns, each cast to text. + @param where (str): the condition, over bound parameters only. + @return (str): the statement. + """ + return f"SELECT {self.key}::text AS k, {columns} FROM {self.ref} WHERE {where}" + + def by_keys(self) -> str: + """The condition that keeps the rows whose key is in the JSON array bound as $1. + + @return (str): the condition; one JSON parameter needs no driver array type. + """ + return f"{self.key} = ANY(ARRAY(SELECT jsonb_array_elements_text($1::jsonb)::{self.cast}))" + + +class PgHydraDBStore: + def __init__( + self, + uri: str, + *, + graph: str, + names: Mapping[str, str] | None = None, + statement_timeout: float = 10.0, + seed_limit: int = 200, + pool_size: int = 4, + namespace: str = "default", + ) -> None: + """A read-only store over tables a pg_hydradb graph registers: rows are entities, edge rows relations. + + @param uri (str): the postgresql:// URI of a login with SELECT on the graph's tables. + @param graph (str): the pg_hydradb graph name. + @param names (Mapping[str, str] | None): the display-name column per vertex label; a label left out uses + its first text column called name, full_name, display_name, title, label, login, or username, else + its first text column. + @param statement_timeout (float): seconds each statement may run before Postgres cancels it. + @param seed_limit (int): the most rows one name lookup returns per table and query word. + @param pool_size (int): the most connections the store opens. + @param namespace (str): the one namespace the rows are read under; a read for another raises ValidationError. + """ + require_encoded_userinfo(uri) + self._uri, self._graph, self._names = uri, graph, dict(names or {}) + self._timeout_ms = str(max(1, int(statement_timeout * 1000))) + self._seed_limit, self._pool_size, self._namespace = seed_limit, pool_size, namespace + self._pool: Any = None + self._closed = self._ready = False + self._starting = asyncio.Lock() + self._vertices: dict[str, _Table] = {} + self._edges: dict[str, _Table] = {} + self._draft: dict[str, Any] = {} + + async def initialize(self) -> None: + """Connect and read the graph's registration once, failing when it is missing, paused, or unreadable.""" + if self._ready: + return + if self._closed: + raise StoreError(STORE_CLOSED_MESSAGE, code="store_closed") + async with self._starting: + if self._ready: + return + if self._closed: + raise StoreError(STORE_CLOSED_MESSAGE, code="store_closed") + try: + import asyncpg + except ImportError as exc: + raise SetupError('the postgres store needs asyncpg: pip install "selfgraph[postgres]"') from exc + settings = {"default_transaction_read_only": "on", "statement_timeout": self._timeout_ms} + try: + pool = self._pool = await asyncpg.create_pool( + self._uri, min_size=1, max_size=self._pool_size, reset=_keep_session, server_settings=settings + ) + except Exception as exc: # noqa: BLE001 + raise self._error(exc) from None + try: + await self._load_registry() + except BaseException: + self._pool = None + await pool.close() + raise + self._ready = True + + async def _open(self, ns: str) -> None: + """Check that a read is for the store's namespace, then connect once. + + @param ns (str): the namespace the caller reads. + @return (None): nothing; raises ValidationError for another namespace. + """ + if ns != self._namespace: + raise ValidationError( + f"this postgres store serves namespace {self._namespace!r}, not {ns!r}", field="namespace" + ) + await self.initialize() + + async def _load_registry(self) -> None: + """Read the graph's vertex and edge tables, checking that this login can read each one.""" + self._vertices, self._edges = {}, {} + found = await self._query(_GRAPH, self._graph) + if not found: + raise graph_unavailable(self._graph, "is not registered; ask the owner to run hydradb.create_graph") + if found[0]["needs_refresh"] is not None: + reason = escape_controls(found[0]["needs_refresh"]) + raise graph_unavailable(self._graph, f"is paused ({reason}); ask the owner to run hydradb.refresh_graph") + vertex_rows = await self._query(_VERTEX_TABLES, self._graph) + edge_rows = await self._query(_EDGE_TABLES, self._graph) + for row in [*vertex_rows, *edge_rows]: + if not row["readable"]: + table = f"{row['nspname']}.{row['relname']}" + raise graph_unavailable(self._graph, f"cannot be read by this login: grant SELECT on {table}") + unknown = sorted(set(self._names) - {row["label"] for row in vertex_rows}) + if unknown: + raise ValidationError(f"names: {unknown[0]!r} is not a vertex label of {self._graph!r}", field="names") + draft = from_tables([{"name": row["label"]} for row in vertex_rows], self._graph) + for row, entity in zip(vertex_rows, draft["entities"], strict=True): + entity["synonyms"] = list(dict.fromkeys([*entity["synonyms"], " ".join(_words(row["relname"]))])) + entity["mappings"] = [{"table": f"{row['nspname']}.{row['relname']}"}] + texts = row["text_columns"] + name = self._names.get(row["label"]) or next((c for c in _NAME_COLUMNS if c in texts), None) + name = name or next(iter(texts), None) + if name is not None and name not in texts: + raise ValidationError(f"names: {name!r} is not a text column of {row['relname']!r}", field="names") + table = _table(row, entity["name"], name=None if name is None else _ident(name)) + self._vertices[table.prefix] = table + relations: dict[str, dict] = {} + for row in edge_rows: + ends = {"source_label": row["source_label"], "target_label": row["target_label"]} + kind = None if row["kind"] is None else _ident(row["kind"]) + table = _table( + row, + normalize_rel_type(row["label"]), + source=_ident(row["source"]), + target=_ident(row["target"]), + kind=kind, + **ends, + ) + self._edges[table.prefix] = table + self._allowed(table.type) + if kind is None: + relation = relations.setdefault( + table.type, {"type": table.type, "from": {"types": []}, "to": {"types": []}} + ) + for side, label in (("from", table.source_label), ("to", table.target_label)): + if self._vertices[slug(label)].type not in relation[side]["types"]: + relation[side]["types"].append(self._vertices[slug(label)].type) + self._draft = {**draft, "relations": list(relations.values())} + + async def draft_schema(self) -> Schema: + """Draft a schema from the graph's registration: an entity type per vertex label, a relation per edge label. + + Types are named from the labels as Schema.from_tables names tables, with the table as a synonym and a + mapping. An edge table with a kind column adds no relation type, since its types are values in its rows. + + @return (Schema): the draft schema. + """ + await self.initialize() + return as_input(Schema, self._draft, "schema") + + def _allowed(self, type: str) -> str: + """Refuse an edge type that Self Graph keeps for its own edges, since reads would hide such relations. + + @param type (str): the relation type of an edge label or kind. + @return (str): the type; raises StoreError with code graph_unavailable when it is reserved. + """ + if type in EDGE_TYPES: + raise graph_unavailable(self._graph, f"has edges of type {type!r}, which Self Graph reserves; rename it") + return type + + async def close(self) -> None: + """Close the connection pool once any first connect has finished; later calls raise StoreError.""" + self._closed = True + async with self._starting: + self._ready = False + pool, self._pool = self._pool, None + if pool is not None: + await pool.close() + + async def _fetch(self, query: str, *args: Any) -> list: + """Run one fixed, parameterised read and return its rows, mapping a driver error to a coded one. + + @param query (str): the statement. + @param args (Any): its parameters. + @return (list): the rows. + """ + await self.initialize() + return await self._query(query, *args) + + async def _query(self, query: str, *args: Any) -> list: + """Run one statement on the pool, mapping a driver error to a coded one. + + @param query (str): the statement. + @param args (Any): its parameters. + @return (list): the rows. + """ + if self._pool is None: + raise StoreError(STORE_CLOSED_MESSAGE, code="store_closed") + try: + return await self._pool.fetch(query, *args) + except Exception as exc: # noqa: BLE001 + raise self._error(exc) from None + + def _error(self, exc: BaseException) -> StoreError: + """Map a driver error to a coded error that never shows the URI's password. + + @param exc (BaseException): the driver error. + @return (StoreError): the error to raise. + """ + state = getattr(exc, "sqlstate", None) + reason = self._redact(error_reason(exc)) + if state is None: + shown = mask_uri(self._uri.split("?", 1)[0]) + return StoreError( + f"cannot reach Postgres at {shown!r}: {self._redact(connection_reason(exc))}", code="store_unreachable" + ) + if state == "57014": + return TransientError(f"Postgres cancelled a query at the statement timeout: {reason}", code="store_busy") + if state in ("28000", "28P01"): + return StoreError(f"Postgres rejected the login: {reason}", code="store_auth_failed") + if state == "3D000": + return StoreError(f"Postgres has no such database: {reason}", code="database_not_found") + if state == "42501": + return graph_unavailable(self._graph, f"cannot be read by this login: {reason}") + if state in ("3F000", "42P01", "42883"): + return graph_unavailable(self._graph, "is unavailable: pg_hydradb is not installed in this database") + if "unknown graph" in reason: + return graph_unavailable(self._graph, "is not registered; ask the owner to run hydradb.create_graph") + if "refresh_graph" in reason or "row-level security" in reason: + return graph_unavailable(self._graph, f"cannot be queried: {reason}") + return StoreError(f"Postgres rejected a query: {reason}", code="query_failed") + + def _redact(self, text: str) -> str: + """Hide the URI's user, password, and any password query parameter in a driver message. + + @param text (str): the message. + @return (str): the message with control characters escaped and credentials replaced by ***. + """ + text = redact_uri(text, self._uri) + for secret in re.findall(r"[?&]password=([^&#]+)", self._uri): + text = text.replace(secret, "***").replace(unquote(secret), "***") + return escape_controls(text) + + def _keys(self, tables: Mapping[str, _Table], ids: Iterable[str]) -> dict[str, list[Any]]: + """Group ids by the registered table their prefix names, as typed keys, dropping ids of no table. + + @param tables (Mapping[str, _Table]): the vertex or edge tables by id prefix. + @param ids (Iterable[str]): the ids, without the "relation:" prefix of a relation id. + @return (dict[str, list[Any]]): each table prefix with its keys, in first-seen order. + """ + keys: dict[str, list[Any]] = {} + for id in dict.fromkeys(ids): + prefix, _, text = id.partition(":") + key = tables[prefix].key_of(text) if prefix in tables else None + if key is not None: + keys.setdefault(prefix, []).append(key) + return keys + + def _entity(self, ns: str, table: _Table, key: str, name: str | None) -> dict: + """Encode one vertex row as an entity's stored properties. + + @param ns (str): namespace. + @param table (_Table): the vertex table. + @param key (str): the row key as text. + @param name (str | None): the display name, or None to show the key. + @return (dict): the entity properties. + """ + at = {"created_at": _EPOCH, "updated_at": _EPOCH} + name = name if name and name.strip() else key + empty: dict[str, Any] = {"aliases": [], "external_ids": {}, "properties": {}} + return encode_entity_props( + ns=ns, id=f"{table.prefix}:{key}", type=table.type, name=name, source_count=1, **at, **empty + ) + + async def _nodes(self, ns: str, ids: Iterable[str]) -> list[dict]: + """Read vertex rows by id, one key lookup per table. + + @param ns (str): namespace. + @param ids (Iterable[str]): entity ids. + @return (list[dict]): the entities found, as stored properties. + """ + await self._open(ns) + found = [] + for prefix, keys in self._keys(self._vertices, ids).items(): + t = self._vertices[prefix] + query = t.lookup("NULL AS n" if t.name is None else f"{t.name}::text AS n", t.by_keys()) + found += [self._entity(ns, t, row["k"], row["n"]) for row in await self._fetch(query, json.dumps(keys))] + return found + + async def seed_candidates(self, ns: str, terms: Iterable[str]) -> list[dict]: + """Read the rows whose display name holds a query word, a bounded lookup per table and word. + + @param ns (str): namespace. + @param terms (Iterable[str]): the query words. + @return (list[dict]): the matching entities, as stored properties. + """ + return await self._named(ns, [f"%{_like(t)}%" for t in sorted(set(terms))[:_SEED_TERMS]]) + + async def entities_matching(self, ns: str, keys: Iterable[str]) -> list[dict]: + """Read the rows whose display name holds the words of a folded-name match key, for entity lookups. + + @param ns (str): namespace. + @param keys (Iterable[str]): match keys; only "form:" keys apply, as rows have no aliases or external ids. + @return (list[dict]): the candidate entities, as stored properties. + """ + forms = sorted({k[5:] for k in keys if k.startswith("form:") and k[5:].strip()}) + exact = [_like(f) for f in forms] + return await self._named(ns, [*exact, *("%" + "%".join(_like(w) for w in f.split()) + "%" for f in forms)]) + + async def _named(self, ns: str, patterns: list[str]) -> list[dict]: + """Run the fixed ILIKE lookup on each table's display column, one pattern per statement. + + @param ns (str): namespace. + @param patterns (list[str]): ILIKE patterns with literal text escaped. + @return (list[dict]): the matching entities, as stored properties, each once. + """ + await self._open(ns) + found: dict[str, dict] = {} + for t in (t for t in self._vertices.values() if t.name is not None): + query = t.lookup(f"{t.name}::text AS n", f"{t.name} ILIKE $1 LIMIT $2") + for pattern in patterns: + for row in await self._fetch(query, pattern, self._seed_limit): + props = self._entity(ns, t, row["k"], row["n"]) + found[props["id"]] = props + return list(found.values()) + + async def get_node(self, ns: str, label: str, id: str) -> dict | None: + """Fetch one row as an entity by id. + + @param ns (str): namespace. + @param label (str): node label; only Entity has rows. + @param id (str): entity id, ":". + @return (dict | None): the entity properties, or None. + """ + found = await self._nodes(ns, [id]) if label == L_ENTITY else [] + return found[0] if found else None + + async def node_exists(self, ns: str, label: str, id: str) -> bool: + return await self.get_node(ns, label, id) is not None + + async def match_nodes( + self, + ns: str, + label: str, + *, + equals: dict | None = None, + any_of: dict | None = None, + order_by: str = "id", + skip: int = 0, + limit: int = 1000, + id_gt: str | None = None, + ) -> list[dict]: + """Return the rows with the given ids as entities; a read with no id list is refused. + + @param ns (str): namespace. + @param label (str): node label; only Entity has rows. + @param equals (dict | None): property name to required value. + @param any_of (dict | None): must hold only "id", the entity ids to read. + @param order_by (str): property to order by. + @param skip (int): rows to skip. + @param limit (int): maximum rows. + @param id_gt (str | None): keep only entities whose id sorts after this one. + @return (list[dict]): entity properties. + """ + if label != L_ENTITY: + return [] + if set(any_of or {}) != {"id"}: + raise unsupported_read("list every entity") + rows = [p for p in await self._nodes(ns, any_of["id"]) if _keeps(p, equals, id_gt)] + rows.sort(key=lambda p: (str(p.get(order_by)), p["id"])) + return rows[skip : skip + limit] + + async def _walk(self, seeds: list[tuple[str, Any]], direction: str) -> list[list[str]]: + """List the edges one hop from the seeds with reachable_edges, halving the seeds when a walk is cut short. + + @param seeds (list[tuple[str, Any]]): (vertex label, key) pairs, at most _SEEDS_PER_WALK. + @param direction (str): "outgoing" or "incoming". + @return (list[list[str]]): the reached edges as [label, key text]; marks the read partial when one seed alone + is cut. + """ + grouped: dict[str, list[Any]] = {} + for label, key in seeds: + grouped.setdefault(label, []).append(key) + options = {"max_depth": 1, "direction": direction, "max_edges": _MAX_EDGES, "max_sources": _SEEDS_PER_WALK} + [row] = await self._fetch(_WALK, self._graph, json.dumps(grouped), json.dumps(options)) + if any(reason != "depth" for reason in json.loads(row["truncated"])): + if len(seeds) > 1: + half = len(seeds) // 2 + return [*await self._walk(seeds[:half], direction), *await self._walk(seeds[half:], direction)] + mark_partial() + return json.loads(row["items"]) + + async def _adjacent(self, ns: str, ids: list[str], direction: str) -> list[dict]: + """Read every edge one hop from some entities, a walk per batch of rows and a key lookup per edge table. + + @param ns (str): namespace. + @param ids (list[str]): the entity ids. + @param direction (str): "outgoing" or "incoming". + @return (list[dict]): the edges, as _edge_rows returns them. + """ + await self._open(ns) + seeds = [(self._vertices[p].label, k) for p, keys in self._keys(self._vertices, ids).items() for k in keys] + items: list[list[str]] = [] + for at in range(0, len(seeds), _SEEDS_PER_WALK): + items += await self._walk(seeds[at : at + _SEEDS_PER_WALK], direction) + prefixes = {t.label: t.prefix for t in self._edges.values()} + return await self._edge_rows(ns, [f"relation:{prefixes[label]}:{key}" for label, key in items]) + + async def _edge_rows(self, ns: str, ids: Iterable[str]) -> list[dict]: + """Read edge rows by relation id, one key lookup per table. + + @param ns (str): namespace. + @param ids (Iterable[str]): relation ids, "relation::". + @return (list[dict]): maps with props, from_id, to_id, and type. + """ + await self._open(ns) + found = [] + for prefix, keys in self._keys(self._edges, (i.removeprefix("relation:") for i in ids)).items(): + t = self._edges[prefix] + kind = "NULL" if t.kind is None else f"{t.kind}::text" + query = t.lookup(f"{t.source}::text AS s, {t.target}::text AS t, {kind} AS kind", t.by_keys()) + for row in await self._fetch(query, json.dumps(keys)): + rid = f"relation:{t.prefix}:{row['k']}" + props = encode_relation_props( + ns=ns, + id=rid, + revision=1, + properties={}, + event_time=None, + created_at=_EPOCH, + is_current=True, + source_count=1, + ) + rtype = self._allowed(normalize_rel_type(row["kind"])) if row["kind"] else t.type + ends = {"from_id": f"{slug(t.source_label)}:{row['s']}", "to_id": f"{slug(t.target_label)}:{row['t']}"} + found.append({"props": props, **ends, "type": rtype}) + return found + + async def match_edges( + self, + ns: str, + *, + from_label: str, + to_label: str | None = None, + type: str | None = None, + from_id: str | None = None, + to_id: str | None = None, + from_in: list[str] | None = None, + to_in: list[str] | None = None, + current_only: bool = False, + equals: dict | None = None, + order_by: str = "id", + skip: int = 0, + limit: int = 1000, + id_gt: str | None = None, + ) -> list[dict]: + """Return the edges out of or into given entities, walked in pg_hydradb; a read with no endpoint is refused. + + @param ns (str): namespace. + @param from_label (str): source node label; only Entity has edges. + @param to_label (str | None): destination node label, or None for any. + @param type (str | None): required relation type. + @param from_id (str | None): required source id. + @param to_id (str | None): required destination id. + @param from_in (list[str] | None): keep only edges whose source id is in this list. + @param to_in (list[str] | None): keep only edges whose destination id is in this list. + @param current_only (bool): every edge row is current, so this changes nothing. + @param equals (dict | None): required edge property values. + @param order_by (str): edge property to order by. + @param skip (int): rows to skip. + @param limit (int): maximum rows. + @param id_gt (str | None): keep only edges whose id sorts after this one. + @return (list[dict]): maps with props, from_id, to_id, type. + """ + if from_label != L_ENTITY or to_label not in (None, L_ENTITY): + return [] + froms, tos = _wanted(from_id, from_in), _wanted(to_id, to_in) + if froms is None and tos is None: + raise unsupported_read("list every relation") + start, direction = (froms, "outgoing") if froms is not None else (tos, "incoming") + rows = [ + e + for e in await self._adjacent(ns, sorted(start), direction) + if (froms is None or e["from_id"] in froms) + and (tos is None or e["to_id"] in tos) + and (type is None or e["type"] == type) + and _keeps(e["props"], equals, id_gt) + ] + rows.sort(key=lambda e: (str(e["props"].get(order_by)), e["props"]["id"], e["from_id"], e["to_id"])) + return rows[skip : skip + limit] + + async def get_current_edge(self, ns: str, id: str) -> dict | None: + """Fetch one edge row by relation id. + + @param ns (str): namespace. + @param id (str): relation id, "relation::". + @return (dict | None): a map with props, from_id, to_id, type, or None. + """ + found = await self._edge_rows(ns, [id]) + return found[0] if found else None + + async def list_edge_versions(self, ns: str, id: str) -> list[dict]: + return await self._edge_rows(ns, [id]) + + async def child_nodes(self, ns: str, *args: Any, **kwargs: Any) -> list[dict]: + return [] + + async def count_nodes_by_ns(self, label: str) -> dict[str, int]: + raise unsupported_read("count every row") + + async def count_edges_by_ns(self, from_label: str, to_label: str, *, current_only: bool = False) -> dict[str, int]: + raise unsupported_read("count every row") + + async def run_cypher(self, query: str, params: Mapping[str, Any] | None = None) -> Any: + raise unsupported_read("run Cypher") + + @asynccontextmanager + async def transaction(self): + """Refuse a write transaction, since the tables belong to the application. + + @return (AsyncIterator[PgHydraDBStore]): never yields; raises StoreError with code read_only_store. + """ + raise read_only_store("a write transaction") + yield self + + +def _refuse(name: str): + """Build a write primitive that refuses with read_only_store. + + @param name (str): the primitive name. + @return (Callable[..., Awaitable[None]]): the refusing method. + """ + + async def refuse(self: PgHydraDBStore, *args: Any, **kwargs: Any) -> None: + """Refuse the write.""" + raise read_only_store(name) + + refuse.__name__ = name + return refuse + + +for _name in _WRITES: + setattr(PgHydraDBStore, _name, _refuse(_name)) + + +def _table(row: Mapping[str, Any], type: str, **columns: Any) -> _Table: + """Describe one registered table from its registry row. + + @param row (Mapping[str, Any]): the registry row. + @param type (str): the entity or relation type its rows get. + @param columns (Any): the display, endpoint, and kind columns. + @return (_Table): the table. + """ + ref = f"{_ident(row['nspname'])}.{_ident(row['relname'])}" + cast = _CASTS.get(row["key_type"], "text") + return _Table(row["label"], slug(row["label"]), ref, type, _ident(row["key"]), cast, **columns) + + +def _keeps(props: Mapping[str, Any], equals: dict | None, id_gt: str | None) -> bool: + """Report whether a node or edge passes an equality filter and a keyset bound. + + @param props (Mapping[str, Any]): its properties. + @param equals (dict | None): property name to required value. + @param id_gt (str | None): the id it must sort after, or None. + @return (bool): True when it passes. + """ + return (id_gt is None or props["id"] > id_gt) and all(props.get(k) == v for k, v in (equals or {}).items()) + + +def _wanted(one: str | None, many: list[str] | None) -> set[str] | None: + """Combine a required id and an id list into the ids to keep, or None for no restriction. + + @param one (str | None): the one id required, or None. + @param many (list[str] | None): the ids accepted, or None. + @return (set[str] | None): the ids to keep. + """ + if one is None: + return None if many is None else set(many) + return {one} if many is None or one in many else set() + + +async def _keep_session(connection: Any) -> None: + """Return a connection to the pool as it is, so the pool runs no reset statement on the user's server. + + @param connection (Any): the pooled connection. + @return (None): nothing. + """ diff --git a/tests/fixtures/pg_hydradb_work.sql b/tests/fixtures/pg_hydradb_work.sql new file mode 100644 index 00000000..a143e60c --- /dev/null +++ b/tests/fixtures/pg_hydradb_work.sql @@ -0,0 +1,30 @@ +CREATE EXTENSION IF NOT EXISTS pg_hydradb; +CREATE SCHEMA __SCHEMA__; +CREATE TABLE __SCHEMA__.people (id bigint PRIMARY KEY, full_name text); +CREATE TABLE __SCHEMA__.companies (slug text PRIMARY KEY, name text NOT NULL); +CREATE TABLE __SCHEMA__.employment (id bigint PRIMARY KEY, person_id bigint NOT NULL REFERENCES __SCHEMA__.people, + company_slug text NOT NULL REFERENCES __SCHEMA__.companies); +CREATE TABLE __SCHEMA__.mentorships (id bigint PRIMARY KEY, mentor_id bigint NOT NULL REFERENCES __SCHEMA__.people, + mentee_id bigint NOT NULL REFERENCES __SCHEMA__.people); +CREATE TABLE __SCHEMA__.projects (id uuid PRIMARY KEY, title text NOT NULL); +CREATE TABLE __SCHEMA__.contributions (id bigint PRIMARY KEY, person_id bigint NOT NULL REFERENCES __SCHEMA__.people, + project_id uuid NOT NULL REFERENCES __SCHEMA__.projects); +INSERT INTO __SCHEMA__.people VALUES (1, 'Ann Lee'), (2, 'Bob Stone'), (3, 'Chloé Durand'), (4, NULL); +INSERT INTO __SCHEMA__.companies VALUES ('acme', 'Acme'), ('globex', 'Globex'); +INSERT INTO __SCHEMA__.employment VALUES (10, 1, 'acme'), (11, 2, 'globex'), (12, 3, 'acme'); +INSERT INTO __SCHEMA__.mentorships VALUES (20, 2, 1), (21, 3, 3); +INSERT INTO __SCHEMA__.projects VALUES ('__PROJECT__', 'Graph Engine'); +INSERT INTO __SCHEMA__.contributions VALUES (30, 1, '__PROJECT__'); +SELECT hydradb.create_graph('__SCHEMA__', + '[{"label": "person", "table": "__SCHEMA__.people", "key": "id"}, + {"label": "company", "table": "__SCHEMA__.companies", "key": "slug"}, + {"label": "project", "table": "__SCHEMA__.projects", "key": "id"}]', + '[{"label": "works_at", "table": "__SCHEMA__.employment", "key": "id", "source": "person_id", + "source_label": "person", "target": "company_slug", "target_label": "company"}, + {"label": "mentors", "table": "__SCHEMA__.mentorships", "key": "id", "source": "mentor_id", + "source_label": "person", "target": "mentee_id", "target_label": "person"}, + {"label": "contributes_to", "table": "__SCHEMA__.contributions", "key": "id", "source": "person_id", + "source_label": "person", "target": "project_id", "target_label": "project"}]'); +CREATE ROLE __SCHEMA__ LOGIN PASSWORD 'pw-__SCHEMA__'; +GRANT USAGE ON SCHEMA __SCHEMA__ TO __SCHEMA__; +GRANT SELECT ON ALL TABLES IN SCHEMA __SCHEMA__ TO __SCHEMA__; diff --git a/tests/test_errors.py b/tests/test_errors.py index 58ce1ad0..4e44e2bb 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -22,6 +22,7 @@ SelfGraph, StoreError, TransientError, + ValidationError, ) from selfgraph._serde import decode_entity from selfgraph.errors import ( @@ -32,10 +33,7 @@ connection_reason, error_reason, escape_controls, - graph_unavailable, internal_error, - read_only_store, - unsupported_read, ) from selfgraph.llm.base import _fatal from selfgraph.mcp.server import run_cypher @@ -43,6 +41,7 @@ from selfgraph.resolution import ResolutionDecision from selfgraph.runtime import GraphSettings, check_settings from selfgraph.stores.kuzu import _kuzu_error +from selfgraph.stores.pg_hydradb import PgHydraDBStore ROOT = pathlib.Path(__file__).resolve().parent.parent DOCS = (ROOT / "docs" / "errors.md").read_text() @@ -225,6 +224,8 @@ def test_every_code_comes_back_from_a_real_call(monkeypatch, tmp_path): closed_store = HydraDBStore(CLOSED_PORT, auth="token") run(closed_store.close()) hydradb, no_token = HydraDBStore(CLOSED_PORT, auth="token"), HydraDBStore(CLOSED_PORT) + postgres = PgHydraDBStore("postgresql://reader:pw@127.0.0.1:1/app", graph="work") + denied = type("PostgresError", (Exception,), {"sqlstate": "42501"})("permission denied for table people") llm = LLMConfig(provider="openai", model="gpt-4o-mini") strict = {"schema": {"entities": [{"name": "Person"}]}, "schema_mode": "strict"} triggers = { @@ -277,9 +278,9 @@ def test_every_code_comes_back_from_a_real_call(monkeypatch, tmp_path): "store_auth_failed": lambda: _raise(no_token._error(DriverError("Neo.ClientError.Security.Unauthorized", ""))), "database_not_found": lambda: _raise(hydradb._error(DriverError("", "database does not exist"))), "wrong_engine": lambda: _raise(hydradb._error(DriverError("", "unsupported protocol version"))), - "read_only_store": lambda: _raise(read_only_store("upsert_node")), - "unsupported_read": lambda: _raise(unsupported_read("count every row")), - "graph_unavailable": lambda: _raise(graph_unavailable("work", "cannot be read by this login")), + "read_only_store": lambda: postgres.upsert_node("n", "Entity", "x", {}), + "unsupported_read": lambda: postgres.count_nodes_by_ns("Entity"), + "graph_unavailable": lambda: _raise(postgres._error(denied)), "write_too_large": lambda: hydradb.upsert_node("n", "Entity", "x", {"id": "x", "blob": "x" * 3_000_000}), "write_conflict": lambda: _raise(hydradb._error(DriverError("", "transaction conflict"))), "store_busy": lambda: _busy_falkordb(monkeypatch).run_cypher("RETURN 1"), @@ -486,3 +487,14 @@ def test_actionable_error_hints(code, hint): assert exc.hint == hint assert exc.to_dict()["hint"] == hint assert "\n" not in hint + + +def test_a_postgres_password_in_the_uri_query_stays_out_of_errors(): + store = PgHydraDBStore("postgresql://127.0.0.1:1/app?user=reader&password=s3cr%23et", graph="work") + refused = store._error(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) + rejected = store._error(type("PgError", (Exception,), {"sqlstate": "28P01"})("password s3cr#et and s3cr%23et")) + assert str(refused) == "cannot reach Postgres at 'postgresql://127.0.0.1:1/app': connection refused" + assert (rejected.code, str(rejected)) == ("store_auth_failed", "Postgres rejected the login: password *** and ***") + with pytest.raises(ValidationError, match="unencoded character") as raw: + PgHydraDBStore("postgresql://reader:sec/ret@db/app", graph="work") + assert "sec/ret" not in str(raw.value) diff --git a/tests/test_pg_hydradb_store.py b/tests/test_pg_hydradb_store.py new file mode 100644 index 00000000..1545d2e8 --- /dev/null +++ b/tests/test_pg_hydradb_store.py @@ -0,0 +1,180 @@ +import asyncio +import os +import pathlib +import uuid +from urllib.parse import urlsplit, urlunsplit + +import pytest +from helpers import run + +from selfgraph import SelfGraph, StoreError, ValidationError + +OWNER_URI = os.environ.get("SG_PG_HYDRADB_URI") or os.environ.get("PG_HYDRADB_URI") +asyncpg = pytest.importorskip("asyncpg") if OWNER_URI else None +pytestmark = pytest.mark.skipif(not OWNER_URI, reason="set SG_PG_HYDRADB_URI to a Postgres with pg_hydradb") +PROJECT = "3f2b8c1e-8f5c-4c2a-9d7e-1a2b3c4d5e6f" +SETUP = (pathlib.Path(__file__).parent / "fixtures" / "pg_hydradb_work.sql").read_text(encoding="utf-8") + + +async def _owner(sql: str, *args): + conn = await asyncpg.connect(OWNER_URI) + try: + return await conn.fetch(sql, *args) if args else await conn.execute(sql) + finally: + await conn.close() + + +@pytest.fixture +def work(): + name = f"sg_{uuid.uuid4().hex[:10]}" + run(_owner(SETUP.replace("__SCHEMA__", name).replace("__PROJECT__", PROJECT))) + parts = urlsplit(OWNER_URI) + reader = urlunsplit(parts._replace(netloc=f"{name}:pw-{name}@{parts.hostname}:{parts.port or 5432}")) + yield name, reader + run(_owner(f"SELECT hydradb.drop_graph('{name}'); DROP SCHEMA {name} CASCADE; DROP ROLE {name};")) + + +def _graph(work, **options): + from selfgraph.stores.pg_hydradb import PgHydraDBStore + + name, reader = work + return SelfGraph(PgHydraDBStore(reader, graph=name, **options)) + + +def _code(call) -> str: + with pytest.raises(StoreError) as caught: + run(call()) + return caught.value.code + + +def test_retrieve_from_a_question_finds_the_rows_that_answer_it(work): + g = _graph(work) + result = run(g.retrieve("who works at Acme")) + assert result.seeds[0].id == "company:acme" + assert "GRAPH | Ann Lee -[WORKS_AT]-> Acme" in result.context + assert "GRAPH | Chloé Durand -[WORKS_AT]-> Acme" in result.context + assert "company:globex" not in {s.id for s in result.seeds} + assert "truncated" not in result.model_dump() + + +def test_entity_ids_neighbors_paths_and_the_schema_draft_read_the_tables(work): + g = _graph(work) + assert run(g.entities.get("person:4")).name == "4" + assert run(g.entities.get(f"project:{PROJECT}")).type == "Project" + seeded = run(g.retrieve(entity_ids=["person:1"], depth=1)) + assert {e.id for e in seeded.subgraph.entities} == {"person:1", "person:2", "company:acme", f"project:{PROJECT}"} + near = run(g.neighbors("person:3")) + assert [(n.entity.id, n.distance) for n in near.neighbors] == [("company:acme", 1)] + assert {r.id for r in near.relations} == {"relation:works_at:12", "relation:mentors:21"} + path = run(g.find_path("person:2", "company:acme", direction="both")) + assert [(s.relation.type, s.entity.id) for s in path.steps] == [ + ("MENTORS", "person:1"), + ("WORKS_AT", "company:acme"), + ] + assert run(g.relations.get("relation:works_at:10")).to_entity == "company:acme" + schema = run(g.store.draft_schema()) + assert [e.name for e in schema.entities] == ["Company", "Person", "Project"] + assert {r.type: (r.from_.types, r.to.types) for r in schema.relations}["WORKS_AT"] == (["Person"], ["Company"]) + + +def test_a_row_the_application_writes_shows_up_on_the_next_read(work): + g = _graph(work) + assert "Dana" not in run(g.retrieve("who works at Globex")).context + run( + _owner( + f"INSERT INTO {work[0]}.people VALUES (5, 'Dana Wu'); INSERT INTO {work[0]}.employment VALUES (13, 5, 'globex')" + ) + ) + assert "GRAPH | Dana Wu -[WORKS_AT]-> Globex" in run(g.retrieve("who works at Globex")).context + + +def test_writes_and_full_scans_are_refused_with_a_code(work): + g = _graph(work) + assert _code(lambda: g.entities.create("Eve", "Person")) == "read_only_store" + assert _code(lambda: g.insert.facts({"entities": [{"type": "Person", "name": "Eve"}]})) == "read_only_store" + assert _code(lambda: g.store.upsert_node("default", "Entity", "person:9", {})) == "read_only_store" + assert _code(lambda: g.entities.list()) == "unsupported_read" + assert _code(lambda: g.run_cypher("MATCH (n) RETURN n")) == "unsupported_read" + grants = run(_owner("SELECT privilege_type FROM information_schema.role_table_grants WHERE grantee = $1", work[0])) + assert {row["privilege_type"] for row in grants} == {"SELECT"} + + +def test_a_missing_paused_or_unreadable_graph_fails_to_connect(work): + name, reader = work + from selfgraph.stores.pg_hydradb import PgHydraDBStore + + missing = PgHydraDBStore(reader, graph="no_such_graph") + assert _code(missing.initialize) == "graph_unavailable" + run(_owner(f"REVOKE SELECT ON {name}.projects FROM {name}")) + with pytest.raises(StoreError, match=f"grant SELECT on {name}.projects") as caught: + run(_graph(work).initialize()) + assert caught.value.code == "graph_unavailable" + assert f"pw-{name}" not in str(caught.value) + run( + _owner( + f"GRANT SELECT ON {name}.projects TO {name}; ALTER TABLE {name}.people ALTER COLUMN full_name TYPE text USING upper(full_name)" + ) + ) + with pytest.raises(StoreError, match="is paused") as caught: + run(_graph(work).initialize()) + assert caught.value.code == "graph_unavailable" + + +def test_a_walk_cut_by_pg_hydradb_marks_the_result_truncated(work): + name = work[0] + run(_owner(f"INSERT INTO {name}.people SELECT g, 'P' || g FROM generate_series(100, 5200) g")) + run(_owner(f"INSERT INTO {name}.employment SELECT g, g, 'globex' FROM generate_series(100, 5200) g")) + g = _graph(work) + near = run(g.neighbors("company:globex", limit=10_000)) + assert near.truncated + assert 5000 <= len(near.neighbors) < 5102 + assert not run(g.neighbors("company:acme")).truncated + + +def test_edge_cases_of_keys_labels_names_and_first_use(work): + from selfgraph.stores.pg_hydradb import PgHydraDBStore + + name, reader = work + top, low = 2**63 - 1, -(2**63) + run( + _owner( + f"CREATE TABLE {name}.big (id bigint PRIMARY KEY, name text); CREATE TABLE {name}.relation (id bigint PRIMARY KEY, name text);" + f"CREATE TABLE {name}.link (id bigint PRIMARY KEY, a bigint NOT NULL REFERENCES {name}.big, b bigint NOT NULL REFERENCES {name}.relation);" + f"INSERT INTO {name}.big VALUES ({top}, 'Top'), ({low}, 'Low'); INSERT INTO {name}.relation VALUES (1, 'Rel');" + f"INSERT INTO {name}.link VALUES ({top}, {top}, 1); INSERT INTO {name}.people SELECT g, 'Annabelle ' || g FROM generate_series(50, 52) g;" + f"INSERT INTO {name}.people VALUES (53, 'Ann'); GRANT SELECT ON ALL TABLES IN SCHEMA {name} TO {name};" + f"""SELECT hydradb.create_graph('{name}_x', '[{{"label": "big", "table": "{name}.big", "key": "id"}}, + {{"label": "relation", "table": "{name}.relation", "key": "id"}}]', '[{{"label": "relation", "table": "{name}.link", + "key": "id", "source": "a", "source_label": "big", "target": "b", "target_label": "relation"}}]')""" + ) + ) + g = SelfGraph(PgHydraDBStore(reader, graph=f"{name}_x")) + assert run(g.entities.get(f"big:{low}")).name == "Low" + assert [n.entity.id for n in run(g.neighbors(f"big:{top}")).neighbors] == ["relation:1"] + assert run(g.relations.get(f"relation:relation:{top}")).to_entity == "relation:1" + assert run(g.entities.get(f"big:{top + 1}")) is None + other = SelfGraph(g.store, namespace="tenant-b") + with pytest.raises(ValidationError, match="serves namespace 'default', not 'tenant-b'"): + run(other.entities.get(f"big:{low}")) + people = PgHydraDBStore(reader, graph=name, seed_limit=2) + assert [m.entity.id for m in run(SelfGraph(people).entities.find("Ann"))] == ["person:53"] + later = PgHydraDBStore(reader, graph=f"{name}_y") + assert _code(later.initialize) == "graph_unavailable" + run( + _owner( + f"""SELECT hydradb.create_graph('{name}_y', '[{{"label": "person", "table": "{name}.people", "key": "id"}}]', + '[{{"label": "prefers", "table": "{name}.mentorships", "key": "id", "source": "mentor_id", + "source_label": "person", "target": "mentee_id", "target_label": "person"}}]')""" + ) + ) + with pytest.raises(StoreError, match="'PREFERS', which Self Graph reserves"): + run(later.initialize()) + fresh = PgHydraDBStore(reader, graph=name) + + async def together(): + return await asyncio.gather(*(fresh.get_node("default", "Entity", f"person:{i}") for i in (1, 2, 3, 53))) + + found = run(together()) + assert [p["name"] for p in found] == ["Ann Lee", "Bob Stone", "Chloé Durand", "Ann"] + run(fresh.close()) + run(_owner(f"SELECT hydradb.drop_graph('{name}_x'); SELECT hydradb.drop_graph('{name}_y')"))