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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ await graph.retrieve("which employers") # seeds Company entities through the sy

## Backends

HydraDB requires version 0.5.0 or later.
HydraDB requires version 0.5.0 or later. See [Run HydraDB locally](docs/quickstart.md#run-hydradb-locally).

```python
from selfgraph import CypherStore, FalkorDBStore, HydraDBStore, KuzuStore, Neo4jStore
Expand All @@ -173,7 +173,7 @@ Neo4jStore("bolt://localhost:7687", auth=("neo4j", "password"))
CypherStore("bolt://localhost:7687", auth=("user", "password")) # Memgraph and other Bolt engines
FalkorDBStore(host="localhost", port=6379)
KuzuStore("graph.kuzu") # embedded
HydraDBStore("bolt://127.0.0.1:17687", auth=("neo4j", "<token>"))
HydraDBStore("bolt://127.0.0.1:7687", auth=("neo4j", "<token>"))
```

See [backends](https://github.com/hydra-db/selfgraph/blob/main/docs/backends.md) to configure from settings or add your own store.
Expand Down
14 changes: 10 additions & 4 deletions docs/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Neo4jStore("bolt://localhost:7687", auth=("neo4j", "password"))
CypherStore("bolt://localhost:7687", auth=("user", "password"))
FalkorDBStore(host="localhost", port=6379)
KuzuStore("graph.kuzu")
HydraDBStore("bolt://127.0.0.1:17687", auth=("neo4j", "<token>"))
HydraDBStore("bolt://127.0.0.1:7687", auth=("neo4j", "<token>"))
```

| Store | Target | Extra |
Expand Down Expand Up @@ -44,8 +44,14 @@ Any other shape raises `ValidationError` when the store is built.
(`connectionTimeout` and `connectionAcquisitionTimeout` in TypeScript). Pass your
own driver settings to change them.

**`HydraDBStore`** takes its token bare or in the second slot of a pair. Each
node or edge row goes in one Bolt message, which HydraDB caps at 2 MiB, so a row
**`HydraDBStore`** takes its token bare or in the second slot of a pair.
See [Run HydraDB locally](quickstart.md#run-hydradb-locally) for the address
and token setup. On initialization, a server that reports a HydraDB version
below 0.5.0 raises [`unsupported_store_version`](errors.md#unsupported_store_version).
If the server does not report a recognizable HydraDB version, the connection
probe still runs.

Each node or edge row goes in one Bolt message, which HydraDB caps at 2 MiB, so a row
may take at most 2 MiB minus 64 KiB. A larger row raises `StoreError` before
it is written. Batches are split to stay under the cap.

Expand Down Expand Up @@ -93,7 +99,7 @@ and the other `SELFGRAPH_*` variables. Every setting is validated when the graph
is built.

```python
SelfGraph.connect(store="hydradb", uri="bolt://127.0.0.1:17687", auth="neo4j:<token>")
SelfGraph.connect(store="hydradb", uri="bolt://127.0.0.1:7687", auth="neo4j:<token>")
SelfGraph.connect(store="kuzu", uri="graph.kuzu")
SelfGraph.connect(store="neo4j", uri="bolt://localhost:7687", auth="neo4j:password")
```
Expand Down
5 changes: 5 additions & 0 deletions docs/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,10 @@ Another process has the embedded database open. Stop the process holding that da

The backend credentials are missing or were rejected. Supply valid credentials with `auth`, `--auth`, or `SELFGRAPH_AUTH`, then reconnect. Keep credentials out of source code and error reports.

#### `unsupported_store_version`

Upgrade HydraDB to at least the version named in the error, then reconnect.

#### `database_not_found`

The database named in the connection settings does not exist on the server. Correct the database name, or ask the user to create that database, then reconnect.
Expand Down Expand Up @@ -404,6 +408,7 @@ port, or a non-Bolt URI such as `http://` fails there.
| No token | `HydraDB needs a token: pass auth=TOKEN to HydraDBStore (or set SELFGRAPH_AUTH)` | `pass --auth TOKEN (or SELFGRAPH_AUTH)` |
| Protocol mismatch, or a missing database reported by Neo4j or Memgraph | adds `if this is Neo4j or Memgraph, pass store="neo4j" (or store="memgraph")` | adds `pass --store neo4j (or memgraph)` |
| Missing database on HydraDB | `database 'foo' not found` | `database 'foo' not found` |
| HydraDB version below 0.5.0 | `unsupported_store_version` names the server version and minimum | Same message and upgrade hint |

**Neo4j and Memgraph.** `initialize()` lists the existing constraints first and
skips the constraint DDL when they are all in place. Concurrent CLI calls do not
Expand Down
5 changes: 5 additions & 0 deletions docs/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ back to the regex pass. Install one:
python -m spacy download en_core_web_sm
```

For a HydraDB entry, set `SELFGRAPH_AUTH` in the environment of the process
that launches the MCP server. If you keep the token in a private file, export
it with `export SELFGRAPH_AUTH="$(cat ./path/to/token-file)"` before starting
that process. See [Run HydraDB locally](quickstart.md#run-hydradb-locally).

For TypeScript, run `npm install @hydradb/selfgraph`. See
[TypeScript](typescript.md#install) for its optional packages.

Expand Down
47 changes: 47 additions & 0 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,50 @@ To build the store and LLM config from settings or environment variables, use
[From settings](backends.md#from-settings).

Continue with [time-aware reads, superseding facts, and entity resolution](tutorial/index.md).

## Run HydraDB locally

Use HydraDB 0.5.0 or newer. Follow [Run a local node](https://github.com/hydra-db/hydradb/blob/v0.5.0/README.md#run-a-local-node)
in the HydraDB repository to configure local storage and the token file, then
start `cargo run --locked --features server-runtime --bin graph-node`.
The example listens on Bolt at `127.0.0.1:7687`.

In a second shell in the HydraDB checkout, export the token and connection settings.

```bash
export SELFGRAPH_STORE=hydradb
export SELFGRAPH_URI=bolt://127.0.0.1:7687
export SELFGRAPH_AUTH="$(cat .hydradb/auth-token)"
```

Install the Python SDK with `pip install selfgraph`. Save the snippet as
`connect.py` and run `python connect.py`.

```python
import asyncio

from selfgraph import SelfGraph


async def main() -> None:
async with SelfGraph.from_env():
print("Connected to HydraDB")


asyncio.run(main())
```

Install the TypeScript SDK with `npm install @hydradb/selfgraph`. Save the
snippet as `connect.mjs` and run `node connect.mjs`.

```javascript
import { SelfGraph } from "@hydradb/selfgraph";

const graph = SelfGraph.fromEnv();
try {
await graph.initialize();
console.log("Connected to HydraDB");
} finally {
await graph.close();
}
```
5 changes: 4 additions & 1 deletion skill/references/runtime.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# Runtime and surfaces

Choose a store for its deployment. Kuzu is embedded and takes a local path.
HydraDB takes a server URI and credentials. Store logic stays separate from SDK logic.
HydraDB takes a server URI and credentials. Use HydraDB 0.5.0 or newer; an older release raises
`unsupported_store_version` at connect. For the local server address and token setup, see
[Run HydraDB locally](https://github.com/hydra-db/selfgraph/blob/main/docs/quickstart.md#run-hydradb-locally).
Store logic stays separate from SDK logic.
Every graph closes its store; create a new store for a new graph instance.

Configure the same store, URI, and namespace on every surface. CLI connection flags
Expand Down
3 changes: 3 additions & 0 deletions src/selfgraph/_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ class Change:
files: Mapping[str, str] | None = None


HYDRADB_INSTALL_WARNING = "HydraDB needs a token. Set SELFGRAPH_AUTH in the environment that starts the MCP server."


def server_command() -> tuple[str, list[str]]:
"""The command an agent runs to start this install's MCP server.

Expand Down
25 changes: 20 additions & 5 deletions src/selfgraph/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,16 @@
from ._context import CONTEXT_FORMATS
from ._diagram import DIAGRAM_FORMATS, neighbors_dot, neighbors_mermaid
from ._diff import timeline_view
from ._install import AGENTS, apply_changes, apply_hooks, install_llm, plan_hooks, plan_install, server_command
from ._install import (
AGENTS,
HYDRADB_INSTALL_WARNING,
apply_changes,
apply_hooks,
install_llm,
plan_hooks,
plan_install,
server_command,
)
from .citations import check_citations
from .code._files import SKIPPED_NAMES
from .code._remote import remote_name
Expand Down Expand Up @@ -64,6 +73,7 @@
sync_glob,
)
from .schema import ContradictionMode, Schema, SchemaMode
from .stores._cypher import parse_auth
from .tiers import LADDERS, LEVELS

__all__ = ["main", "build_parser"]
Expand Down Expand Up @@ -1610,11 +1620,12 @@ def error_text(exc: SelfGraphError, command: str) -> str:
return "\n".join(lines)


def _install(args: argparse.Namespace, settings: dict[str, str]) -> int:
def _install(args: argparse.Namespace, given: dict[str, str], settings: GraphSettings) -> int:
"""Add or remove the MCP server in each agent's config and print one line per file.

@param args (argparse.Namespace): the parsed install command.
@param settings (dict[str, str]): the settings given as flags that the store does not ignore.
@param given (dict[str, str]): the settings given as flags that the store does not ignore.
@param settings (GraphSettings): the effective settings, including inherited environment variables.
@return (int): the process exit code.
"""
command, server_args = server_command()
Expand All @@ -1624,11 +1635,15 @@ def _install(args: argparse.Namespace, settings: dict[str, str]) -> int:
remove=args.remove,
command=command,
args=server_args,
settings=settings,
settings=given,
cwd=Path.cwd(),
home=Path.home(),
)
print("\n".join(apply_changes(changes, dry_run=args.dry_run)), flush=True)
if changes and not args.remove and store_kind(settings) == "hydradb":
auth = parse_auth(settings.auth)
if auth is None or not auth[1].strip():
print(f"warning: {HYDRADB_INSTALL_WARNING}", file=sys.stderr)
return 0


Expand Down Expand Up @@ -1744,7 +1759,7 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "llm":
return _enable_llm(args, given)
if args.command == "install":
return _install(args, given)
return _install(args, given, settings)
if args.command == "code" and args.action == "hook":
return _code_hook(args, given)
return asyncio.run(_run_with_diagnostics(args, settings))
Expand Down
2 changes: 2 additions & 0 deletions src/selfgraph/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"store_unreachable",
"store_locked",
"store_auth_failed",
"unsupported_store_version",
"database_not_found",
"wrong_engine",
"read_only_store",
Expand Down Expand Up @@ -202,6 +203,7 @@
"`--auth`, or `SELFGRAPH_AUTH`, then reconnect. Keep credentials out of source code and error "
"reports."
),
"unsupported_store_version": ("Upgrade HydraDB to at least the version named in the error, then reconnect."),
"database_not_found": (
"The database named in the connection settings does not exist on the server. Correct the database "
"name, or ask the user to create that database, then reconnect."
Expand Down
26 changes: 23 additions & 3 deletions src/selfgraph/stores/hydradb.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
_OTHER_ENGINE_HINT = f"; if this is Neo4j or Memgraph, {OTHER_ENGINE_HINT}"
_NO_TOKEN = f"HydraDB needs a token: {TOKEN_HINT}"
_LABEL_KEY = re.compile(r"[A-Za-z0-9_.-]+")
_MIN_VERSION = (0, 5, 0)
_SERVER_VERSION = re.compile(
r"(?:^| )SlateDBGraph/(([0-9]{1,9})\.([0-9]{1,9})\.([0-9]{1,9})(-[0-9A-Za-z.-]+)?)(?:\+[0-9A-Za-z.-]+)?$"
)


def _transient(lowered: str) -> bool:
Expand Down Expand Up @@ -468,11 +472,27 @@ async def transaction(self) -> AsyncIterator[HydraDBStore]:
raise failure

async def initialize(self) -> None:
"""Check the server is reachable and accepts the credentials with one cheap read; nothing is created.
"""Check connectivity, credentials, and the HydraDB version with one read.

@return (None): nothing; raises StoreError when the server cannot be reached or rejects the login.
@return (None): nothing; raises StoreError on a failed read or an unsupported version.
"""
await self._run("MATCH (n:_SgInit) RETURN count(*) AS n")
async with self._session() as session:
try:
result = await session.run("MATCH (n:_SgInit) RETURN count(*) AS n", {})
summary = await result.consume()
except Exception as exc: # noqa: BLE001
raise self._error(exc) from exc
agent = summary.server.agent
version = _SERVER_VERSION.search(agent) if isinstance(agent, str) else None
if version is None:
return
numbers = (int(version[2]), int(version[3]), int(version[4]))
if numbers < _MIN_VERSION or (numbers == _MIN_VERSION and version[5]):
minimum = ".".join(map(str, _MIN_VERSION))
raise StoreError(
f"HydraDB {version[1]} is unsupported; SelfGraph requires HydraDB {minimum} or newer",
code="unsupported_store_version",
)

async def close(self) -> None:
"""Close the driver and its connection pool; later calls fail with StoreError."""
Expand Down
64 changes: 62 additions & 2 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import types
from decimal import InvalidOperation
from typing import get_args
from unittest.mock import AsyncMock, MagicMock

import pytest
from helpers import DriverError, FakeLLM, error_links, new_graph, run, unique_ns
Expand All @@ -26,6 +27,7 @@
)
from selfgraph._install import plan_install
from selfgraph._serde import decode_entity
from selfgraph.cli import main
from selfgraph.errors import (
HINTS,
WARNING_HINTS,
Expand All @@ -37,10 +39,11 @@
internal_error,
)
from selfgraph.llm.base import _fatal
from selfgraph.mcp import server as mcp_server
from selfgraph.mcp.server import run_cypher
from selfgraph.models import as_input
from selfgraph.resolution import ResolutionDecision
from selfgraph.runtime import GraphSettings, check_settings
from selfgraph.runtime import GraphSettings, check_settings, settings_from_env
from selfgraph.stores.kuzu import _kuzu_error
from selfgraph.stores.pg_hydradb import PgHydraDBStore

Expand Down Expand Up @@ -187,6 +190,57 @@ def _sections(start, end):
return {m.group(1): " ".join(m.group(2).split()) for m in found}


def _hydradb_server(monkeypatch, agent):
driver = MagicMock()
driver.close = AsyncMock()
result = MagicMock()
result.consume = AsyncMock(
return_value=types.SimpleNamespace(server=types.SimpleNamespace(agent=agent), counters=None)
)
driver.session.return_value.__aenter__.return_value.run = AsyncMock(return_value=result)
monkeypatch.setattr("selfgraph.stores.hydradb.bolt_driver", lambda *_args, **_kwargs: driver)
monkeypatch.setenv("SELFGRAPH_STORE", "hydradb")
monkeypatch.setenv("SELFGRAPH_URI", CLOSED_PORT)
monkeypatch.setenv("SELFGRAPH_AUTH", "local-test-token")


def test_unsupported_hydradb_version_reaches_api_cli_and_mcp(monkeypatch, capsys):
_hydradb_server(monkeypatch, "Neo4j/5.26.0 compatible - SlateDBGraph/0.4.0")
message = "HydraDB 0.4.0 is unsupported; SelfGraph requires HydraDB 0.5.0 or newer"
code = "unsupported_store_version"
with pytest.raises(StoreError, match=re.escape(message)) as caught:
run(SelfGraph.from_env().initialize())
assert caught.value.code == code

assert main(["entity", "list"]) == 1
err = capsys.readouterr().err
assert f"error[{code}]: {message}" in err
assert caught.value.hint in err

async def call():
await mcp_server.configure(settings_from_env())
try:
return await mcp_server.build_server().call_tool("get_schema", {})
finally:
await mcp_server.configure()

result = run(call())
assert result.is_error
assert result.structured_content == {**caught.value.to_dict(), "tool": "get_schema"}


def test_hydradb_quickstart_python_snippet(monkeypatch, capsys):
quickstart = (ROOT / "docs" / "quickstart.md").read_text().split("## Run HydraDB locally")[1]
snippet = quickstart.split("```python\n")[1].split("```")[0]
for version in ("0.5.0", "0.10.0", "0.5.0+build", "unknown"):
_hydradb_server(monkeypatch, f"Neo4j/5.26.0 compatible - SlateDBGraph/{version}")
exec(compile(snippet, "docs/quickstart.md", "exec"), {})
assert capsys.readouterr().out == "Connected to HydraDB\n"
_hydradb_server(monkeypatch, "Neo4j/5.26.0 compatible - SlateDBGraph/0.5.0-rc.1")
with pytest.raises(StoreError, match="0.5.0-rc.1"):
exec(compile(snippet, "docs/quickstart.md", "exec"), {})


def test_every_code_is_documented_and_its_hint_is_the_first_paragraph_of_its_section():
assert _sections("Codes", "Messages") == HINTS
assert get_args(ErrorCode) == tuple(HINTS)
Expand All @@ -195,6 +249,9 @@ def test_every_code_is_documented_and_its_hint_is_the_first_paragraph_of_its_sec


def test_every_code_comes_back_from_a_real_call(monkeypatch, tmp_path):
with monkeypatch.context() as hydra:
_hydradb_server(hydra, "Neo4j/5.26.0 compatible - SlateDBGraph/0.4.0")
unsupported = _code(SelfGraph.from_env().initialize)
g = new_graph(namespace=unique_ns("codes"))
run(g.insert.facts(PEOPLE))
run(g.entities.create("Augusta", "Person", aliases=["Augusta Ada"]))
Expand All @@ -208,7 +265,10 @@ def test_every_code_comes_back_from_a_real_call(monkeypatch, tmp_path):
)
merge_id, moved = merged.merges[0].id, merged.relations[0].id
run(g.relations.certify(moved, by="test"))
codes = {"relation_certified": _code(lambda: g.entities.unmerge(merge_id))}
codes = {
"relation_certified": _code(lambda: g.entities.unmerge(merge_id)),
"unsupported_store_version": unsupported,
}
run(g.relations.uncertify(moved))
run(g.entities.unmerge(merge_id))
schema = {"relations": [{"type": "WORKS_AT", "from": {"types": ["Person"], "max_count": 1}}]}
Expand Down
Loading
Loading