diff --git a/README.md b/README.md index 10094ce8..ca6c4cf8 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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", "")) +HydraDBStore("bolt://127.0.0.1:7687", auth=("neo4j", "")) ``` See [backends](https://github.com/hydra-db/selfgraph/blob/main/docs/backends.md) to configure from settings or add your own store. diff --git a/docs/backends.md b/docs/backends.md index 7ddb4803..f8a34f42 100644 --- a/docs/backends.md +++ b/docs/backends.md @@ -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", "")) +HydraDBStore("bolt://127.0.0.1:7687", auth=("neo4j", "")) ``` | Store | Target | Extra | @@ -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. @@ -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:") +SelfGraph.connect(store="hydradb", uri="bolt://127.0.0.1:7687", auth="neo4j:") SelfGraph.connect(store="kuzu", uri="graph.kuzu") SelfGraph.connect(store="neo4j", uri="bolt://localhost:7687", auth="neo4j:password") ``` diff --git a/docs/errors.md b/docs/errors.md index e957767b..1e1cfd57 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -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. @@ -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 diff --git a/docs/install.md b/docs/install.md index c76af559..96fe2fb7 100644 --- a/docs/install.md +++ b/docs/install.md @@ -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. diff --git a/docs/quickstart.md b/docs/quickstart.md index d5e0742d..605df9e8 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -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(); +} +``` diff --git a/skill/references/runtime.md b/skill/references/runtime.md index fc36819a..06151447 100644 --- a/skill/references/runtime.md +++ b/skill/references/runtime.md @@ -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 diff --git a/src/selfgraph/_install.py b/src/selfgraph/_install.py index d9bc876b..b2d46de1 100644 --- a/src/selfgraph/_install.py +++ b/src/selfgraph/_install.py @@ -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. diff --git a/src/selfgraph/cli.py b/src/selfgraph/cli.py index 05517405..7e5610b5 100644 --- a/src/selfgraph/cli.py +++ b/src/selfgraph/cli.py @@ -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 @@ -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"] @@ -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() @@ -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 @@ -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)) diff --git a/src/selfgraph/errors.py b/src/selfgraph/errors.py index b40620b3..3249a906 100644 --- a/src/selfgraph/errors.py +++ b/src/selfgraph/errors.py @@ -57,6 +57,7 @@ "store_unreachable", "store_locked", "store_auth_failed", + "unsupported_store_version", "database_not_found", "wrong_engine", "read_only_store", @@ -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." diff --git a/src/selfgraph/stores/hydradb.py b/src/selfgraph/stores/hydradb.py index 370bd7e9..83d5efef 100644 --- a/src/selfgraph/stores/hydradb.py +++ b/src/selfgraph/stores/hydradb.py @@ -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: @@ -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.""" diff --git a/tests/test_errors.py b/tests/test_errors.py index bca67d03..4ef1d540 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -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 @@ -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, @@ -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 @@ -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) @@ -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"])) @@ -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}}]} diff --git a/tests/test_install.py b/tests/test_install.py index 3a1c3b6d..6492066a 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -174,6 +174,19 @@ def snapshot(*roots): return {str(p): p.read_bytes() for root in roots for p in sorted(root.rglob("*")) if p.is_file()} +def test_warns_for_hydradb_without_a_token(capsys, dirs, monkeypatch): + project, _ = dirs + args = (_install.AGENTS[0], "--uri", "bolt://127.0.0.1:7687") + code, _, err = install(capsys, *args) + assert code == 0 + assert err == ["warning: HydraDB needs a token. Set SELFGRAPH_AUTH in the environment that starts the MCP server."] + monkeypatch.setenv("SELFGRAPH_AUTH", "local-test-token") + assert install(capsys, *args)[2] == [] + assert "local-test-token" not in (project / ".mcp.json").read_text() + monkeypatch.delenv("SELFGRAPH_AUTH") + assert install(capsys, *args, "--remove")[2] == [] + + def test_writes_each_agents_file_shape(capsys, dirs): project, home = dirs code, out, _ = install(capsys, "claude", "cursor", "vscode", "gemini", "windsurf", "codex") diff --git a/typescript/README.md b/typescript/README.md index 962e4012..7813b97a 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -76,7 +76,7 @@ Close the graph when you are done: an open server connection keeps Node running. ## Backends -HydraDB requires version 0.5.0 or later. +HydraDB requires version 0.5.0 or later. See [Run HydraDB locally](https://github.com/hydra-db/selfgraph/blob/main/docs/quickstart.md#run-hydradb-locally). ```ts import { CypherStore, FalkorDBStore, HydraDBStore, KuzuStore, Neo4jStore } from "@hydradb/selfgraph"; @@ -85,7 +85,7 @@ new Neo4jStore("bolt://localhost:7687", { auth: ["neo4j", "password"] }); new CypherStore("bolt://localhost:7687", { auth: ["user", "password"] }); // Memgraph and other Bolt engines new FalkorDBStore("localhost", 6379); new KuzuStore("graph.kuzu"); // embedded -new HydraDBStore("bolt://127.0.0.1:17687", { auth: ["neo4j", ""] }); +new HydraDBStore("bolt://127.0.0.1:7687", { auth: ["neo4j", ""] }); ``` See [backends](https://github.com/hydra-db/selfgraph/blob/main/docs/backends.md) to configure from settings or add your own store. diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index c99e96c4..74cae9bc 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -24,6 +24,7 @@ import { applyChanges, applyHooks, HOOK_COMMAND, + HYDRADB_INSTALL_WARNING, installLlm, llmServerArgs, planHooks, @@ -91,6 +92,7 @@ import { version, } from "./runtime.js"; import { CONTRADICTION_MODES, type ContradictionMode, SCHEMA_MODES } from "./schema.js"; +import { parseAuth } from "./stores/bolt.js"; import { fromTables } from "./tables.js"; import { LEVELS, RERANK_TIERS, SEED_TIERS } from "./tiers.js"; import { parseTime } from "./validate.js"; @@ -418,11 +420,14 @@ function connectSettings(cmd: { optsWithGlobals(): GlobalOptions }): GraphSettin * The settings given as flags that the store does not ignore, as the strings typed. * * @param cmd (Command): the command being run. + * @param settings (GraphSettings): the effective settings, including inherited environment variables. * @return (Record): each setting key and its flag value. */ -function givenSettings(cmd: { optsWithGlobals(): GlobalOptions }): Record { +function givenSettings( + cmd: { optsWithGlobals(): GlobalOptions }, + settings = connectSettings(cmd), +): Record { const given: Record = cmd.optsWithGlobals(); - const settings = connectSettings(cmd); const keys = SETTING_KEYS.filter( (key) => typeof given[flag(key)] === "string" && settings[key as keyof GraphSettings] !== null, ); @@ -1255,16 +1260,19 @@ export function buildParser(): Command<[], GlobalOptions> { .option("--remove", "remove the selfgraph server, and the Claude Code skill") .configureHelp({ showGlobalOptions: true }) .action(async (agents: string[], o, cmd) => { + const settings = connectSettings(cmd); const changes = planInstall(agents, { user: o.global === true, remove: o.remove === true, command: SERVER_COMMAND, args: SERVER_ARGS, - settings: givenSettings(cmd), + settings: givenSettings(cmd, settings), cwd: process.cwd(), home: homedir(), }); await writeOut(`${applyChanges(changes, o.dryRun === true).join("\n")}\n`); + if (changes.length && !o.remove && storeKind(settings) === "hydradb" && !parseAuth(settings.auth)?.[1].trim()) + process.stderr.write(`warning: ${HYDRADB_INSTALL_WARNING}\n`); }); program .command("llm") diff --git a/typescript/src/errors.ts b/typescript/src/errors.ts index 925897e3..c7bd28ea 100644 --- a/typescript/src/errors.ts +++ b/typescript/src/errors.ts @@ -65,6 +65,7 @@ export const HINTS = { "Another process has the embedded database open. Stop the process holding that database, or use a different database path, then open the store again. Do not delete database files to release the lock.", store_auth_failed: "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.", wrong_engine: diff --git a/typescript/src/install.ts b/typescript/src/install.ts index 9b41e11e..308c2ca8 100644 --- a/typescript/src/install.ts +++ b/typescript/src/install.ts @@ -50,6 +50,8 @@ const AGENT_SPECS: Record = { }; export const AGENTS = Object.keys(AGENT_SPECS); +export const HYDRADB_INSTALL_WARNING = + "HydraDB needs a token. Set SELFGRAPH_AUTH in the environment that starts the MCP server."; export const SERVER_COMMAND = "npx"; export const SERVER_ARGS = ["-y", "-p", "@hydradb/selfgraph", "-p", "@modelcontextprotocol/sdk", "selfgraph", "mcp"]; export const HOOK_COMMAND = ["npx", "--no", "@hydradb/selfgraph"]; diff --git a/typescript/src/stores/hydradb.ts b/typescript/src/stores/hydradb.ts index cedd8f47..d5ebb208 100644 --- a/typescript/src/stores/hydradb.ts +++ b/typescript/src/stores/hydradb.ts @@ -51,6 +51,9 @@ const PARALLEL = 32; const queuing = new AsyncLocalStorage(); const HANDSHAKE_RETRIES = 50; const HANDSHAKE_JITTER_MS = 25; +const MIN_VERSION = [0, 5, 0] as const; +const SERVER_VERSION = + /(?:^| )SlateDBGraph\/(([0-9]{1,9})\.([0-9]{1,9})\.([0-9]{1,9})(-[0-9A-Za-z.-]+)?)(?:\+[0-9A-Za-z.-]+)?$/; const jitter = (): Promise => new Promise((resolve) => setTimeout(resolve, Math.random() * HANDSHAKE_JITTER_MS)); const MAX_MESSAGE_BYTES = 2 * 1024 * 1024; @@ -417,7 +420,7 @@ export class HydraDBStore extends AutoCommitStore implements GraphStore { /** * A store for HydraDB over Bolt, using integer surrogate keys and auto-commit writes. * - * @param uri (string): the Bolt URI, e.g. bolt://127.0.0.1:17687. + * @param uri (string): the Bolt URI of the server. * @param options (HydraDBStoreOptions): auth as [user, token] or a driver token, the database (default "default"), and driver config. */ constructor(uri: string, options: HydraDBStoreOptions = {}) { @@ -620,16 +623,36 @@ export class HydraDBStore extends AutoCommitStore implements GraphStore { } /** - * Open a first pooled connection, retrying the split handshake with jitter, then check the server accepts the credentials with one cheap read; nothing is created. + * Check connectivity, credentials, and the HydraDB version with one read. */ async initialize(): Promise { this.requireOpen(); + let agent: string | undefined; try { await withHandshakeRetry(() => this.driver.verifyConnectivity({ database: this.database })); + agent = await withHandshakeRetry(async () => { + const session = this.session(); + try { + const { summary } = await session.run("MATCH (n:_SgInit) RETURN count(*) AS n"); + return summary.server.agent; + } finally { + await session.close().catch(() => undefined); + } + }); } catch (exc) { + if (exc instanceof SelfGraphError) throw exc; throw this.error(exc); } - await this._run("MATCH (n:_SgInit) RETURN count(*) AS n"); + const version = typeof agent === "string" ? SERVER_VERSION.exec(agent) : null; + if (version === null) return; + const numbers = version.slice(2, 5).map(Number); + const firstDifference = MIN_VERSION.findIndex((minimum, index) => numbers[index] !== minimum); + if (firstDifference === -1 ? version[5] : numbers[firstDifference]! < MIN_VERSION[firstDifference]!) { + throw new StoreError( + `HydraDB ${version[1]} is unsupported; SelfGraph requires HydraDB ${MIN_VERSION.join(".")} or newer`, + { code: "unsupported_store_version" }, + ); + } } async close(): Promise { diff --git a/typescript/test/conformance.test.ts b/typescript/test/conformance.test.ts index 291c1a9a..03cdbba9 100644 --- a/typescript/test/conformance.test.ts +++ b/typescript/test/conformance.test.ts @@ -9,6 +9,7 @@ import { codeWalk, determinism, exitCodes, + hydradbVersions, kuzuOpenErrors, kuzuParamErrors, kuzuReadOnly, @@ -25,6 +26,18 @@ import { import { tempKuzu, uniqueNs } from "./helpers.js"; describe.skipIf(!PY)("cross-language conformance with the Python SDK", () => { + it("enforces the same minimum HydraDB version in both languages", async () => { + const result = await hydradbVersions(); + expect(result).toEqual(py("hydradb_versions", "-", "-")); + expect(result).toEqual([ + expect.objectContaining({ code: "unsupported_store_version" }), + expect.objectContaining({ code: "unsupported_store_version" }), + "accepted", + "accepted", + "accepted", + ]); + }); + it.skipIf(!live.get("kuzu"))("keeps scalar and rendering determinism identical in both SDKs", async () => { const result = await determinism(); expect(result).toEqual(py("determinism", "-", "-")); diff --git a/typescript/test/conformance/helpers.ts b/typescript/test/conformance/helpers.ts index c15ee7c9..cb109294 100644 --- a/typescript/test/conformance/helpers.ts +++ b/typescript/test/conformance/helpers.ts @@ -20,6 +20,7 @@ export function py( | "unmerge" | "kuzu_isolation" | "exit_codes" + | "hydradb_versions" | "code_hooks" | "code_ignore" | "code_walk" diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 39a03c0c..84a462a4 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -10,7 +10,8 @@ import unicodedata from datetime import datetime, timedelta, timezone from pathlib import Path -from unittest.mock import patch +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch from pydantic import ValidationError as PydanticValidationError from pydantic import validate_call @@ -19,6 +20,7 @@ EntityInput, EvidenceInput, Extraction, + HydraDBStore, KuzuStore, Neo4jStore, NotFoundError, @@ -5033,6 +5035,26 @@ async def embed(self, texts): ) +async def hydradb_versions(): + driver = MagicMock() + driver.close = AsyncMock() + pending = MagicMock() + driver.session.return_value.__aenter__.return_value.run = AsyncMock(return_value=pending) + fields = [] + with patch("selfgraph.stores.hydradb.bolt_driver", return_value=driver): + for version in ("0.4.0", "0.5.0-rc.1", "0.5.0", "0.10.0", "unknown"): + agent = f"Neo4j/5.26.0 compatible - SlateDBGraph/{version}" + pending.consume = AsyncMock( + return_value=SimpleNamespace(server=SimpleNamespace(agent=agent), counters=None) + ) + graph = SelfGraph(store=HydraDBStore("bolt://127.0.0.1:1", auth="token")) + try: + fields.append(await error_of(graph.initialize())) + finally: + await graph.close() + return fields + + def exit_codes() -> list: """The code the CLI would exit with for each error code, so both SDKs compare one table. @@ -5404,6 +5426,9 @@ async def main(): if cmd == "kuzu_cut_delete": json.dump(await cut_decision_deletes(), sys.stdout) return + if cmd == "hydradb_versions": + json.dump(await hydradb_versions(), sys.stdout) + return if cmd == "exit_codes": json.dump(exit_codes(), sys.stdout) return diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index 173ec64f..8cd475e4 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -15,6 +15,7 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { isDeepStrictEqual } from "node:util"; +import type { Driver } from "neo4j-driver"; import { type Chunking, chunkMarkdown, loadTokenizer } from "../../src/chunking.js"; import { exitCodeFor, kv } from "../../src/cli.js"; import { assignIds, type FileFacts, fileFacts } from "../../src/code/facts.js"; @@ -66,6 +67,7 @@ import { FalkorDBStore, fromNeo4jOntology, fromTables, + HydraDBStore, ids, KuzuStore, Neo4jStore, @@ -1906,6 +1908,26 @@ const FACTS_TYPE_CASES: unknown[] = [ export const TEXT = "Grace Hopper joined Remington Rand. Grace Hopper wrote COBOL. Zoë Ångström met Ada Lovelace in 北京."; +export async function hydradbVersions(): Promise> { + const fields = []; + for (const version of ["0.4.0", "0.5.0-rc.1", "0.5.0", "0.10.0", "unknown"]) { + const agent = `Neo4j/5.26.0 compatible - SlateDBGraph/${version}`; + const summary = { server: { agent }, counters: { updates: () => ({}) } }; + const result = Object.assign(Promise.resolve({ summary, records: [] }), { keys: async () => [] }); + const store = new HydraDBStore("bolt://127.0.0.1:1", { auth: "token" }); + const driver = (store as unknown as { driver: Driver }).driver; + await driver.close(); + Object.assign(driver, { + verifyConnectivity: async () => undefined, + session: () => ({ run: () => result, close: async () => undefined }), + close: async () => undefined, + }); + await using graph = new SelfGraph(store); + fields.push(await errorOf(() => graph.initialize())); + } + return fields; +} + /** * The exit code each error code gets, so both SDKs compare one table. * diff --git a/typescript/test/errors.test.ts b/typescript/test/errors.test.ts index d863b8b7..292230aa 100644 --- a/typescript/test/errors.test.ts +++ b/typescript/test/errors.test.ts @@ -3,8 +3,12 @@ import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterAll, describe, expect, it } from "vitest"; + +import neo4j, { type Driver } from "neo4j-driver"; +import { afterAll, describe, expect, it, vi } from "vitest"; import { z } from "zod"; + +import { main } from "../src/cli.js"; import { connectionReason, escapeControls, @@ -30,7 +34,7 @@ import { import { planInstall } from "../src/install.js"; import { Lazy } from "../src/internal/lazy.js"; import { buildLlmClient } from "../src/llm/index.js"; -import { TOOLS } from "../src/mcp.js"; +import { callTool, configure, TOOLS } from "../src/mcp.js"; import { parseOrThrow } from "../src/models.js"; import { checkSettings, settingsFromEnv } from "../src/runtime.js"; import { decodeEntity } from "../src/serde.js"; @@ -95,6 +99,79 @@ function sections(start: string, end: string): Record { return Object.fromEntries([...found].map((m) => [m[1]!, m[2]!.split(/\s+/).join(" ").trim()])); } +function stubHydraDB(server: { agent: string }) { + const summary = { server, counters: { updates: () => ({}) } }; + const result = Object.assign(Promise.resolve({ summary, records: [] }), { keys: async () => [] }); + const driver = { + verifyConnectivity: async () => undefined, + session: () => ({ run: () => result, close: async () => undefined }), + close: async () => undefined, + } as unknown as Driver; + return vi.spyOn(neo4j, "driver").mockReturnValue(driver); +} + +const HYDRA_SETTINGS = { store: "hydradb", uri: CLOSED_PORT, auth: "local-test-token" }; + +it("surfaces an unsupported HydraDB version through the API, CLI, and MCP", async () => { + const driver = stubHydraDB({ agent: "Neo4j/5.26.0 compatible - SlateDBGraph/0.4.0" }); + const stderr = vi.spyOn(process.stderr, "write").mockReturnValue(true); + const message = "HydraDB 0.4.0 is unsupported; SelfGraph requires HydraDB 0.5.0 or newer"; + const code = "unsupported_store_version"; + try { + const graph = SelfGraph.connect(HYDRA_SETTINGS); + await expect(graph.initialize()).rejects.toMatchObject({ code, message }); + await graph.close(); + const flags = ["--store", "hydradb", "--uri", CLOSED_PORT, "--auth", HYDRA_SETTINGS.auth]; + expect(await main([...flags, "entity", "list"])).toBe(1); + const diagnostic = stderr.mock.calls.flat().join(""); + expect(diagnostic).toContain(`error[${code}]: ${message}`); + expect(diagnostic).toContain(errorLinks(code).hint); + await configure(settingsFromEnv(HYDRA_SETTINGS)); + expect(await callTool("get_schema", {})).toEqual({ + isError: true, + result: expect.objectContaining({ + ...errorLinks(code), + error: message, + code, + tool: "get_schema", + retryable: false, + }), + }); + } finally { + await configure(); + stderr.mockRestore(); + driver.mockRestore(); + } +}); + +it("runs the HydraDB quickstart TypeScript snippet", async () => { + const quickstart = readFileSync(new URL("../../docs/quickstart.md", import.meta.url), "utf8"); + const snippet = quickstart.split("## Run HydraDB locally")[1]!.split("```javascript\n")[1]!.split("```")[0]!; + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; + const run = new AsyncFunction("SelfGraph", snippet.replace('import { SelfGraph } from "@hydradb/selfgraph";', "")); + vi.stubEnv("SELFGRAPH_STORE", "hydradb"); + vi.stubEnv("SELFGRAPH_URI", CLOSED_PORT); + vi.stubEnv("SELFGRAPH_AUTH", HYDRA_SETTINGS.auth); + const server = { agent: "Neo4j/5.26.0" }; + const driver = stubHydraDB(server); + try { + await run(SelfGraph); + for (const version of ["0.5.0", "0.10.0", "0.5.0+build", "unknown"]) { + server.agent = `Neo4j/5.26.0 compatible - SlateDBGraph/${version}`; + await run(SelfGraph); + } + expect(log).toHaveBeenCalledTimes(5); + expect(log).toHaveBeenLastCalledWith("Connected to HydraDB"); + server.agent = "Neo4j/5.26.0 compatible - SlateDBGraph/0.5.0-rc.1"; + await expect(run(SelfGraph)).rejects.toMatchObject({ code: "unsupported_store_version" }); + } finally { + driver.mockRestore(); + log.mockRestore(); + vi.unstubAllEnvs(); + } +}); + it.each(["list", "map"])("reports result depth as a coded error for %s", async (kind) => { const { checkResultDepth } = await import("../src/models.js"); let value: unknown = 1; @@ -119,6 +196,15 @@ describe("error codes", () => { }); it("raises every code from a real call", async () => { + const driver = stubHydraDB({ agent: "Neo4j/5.26.0 compatible - SlateDBGraph/0.4.0" }); + const hydra = SelfGraph.connect(HYDRA_SETTINGS); + let unsupported: string | null; + try { + unsupported = await codeOf(() => hydra.initialize()); + } finally { + await hydra.close(); + driver.mockRestore(); + } const g = open(); const gs = open({ schema: { relations: [{ type: "WORKS_AT", from: { types: ["Person"], max_count: 1 } }] }, @@ -137,6 +223,7 @@ describe("error codes", () => { await g.relations.certify(moved, { by: "test" }); const codes: Record = { relation_certified: await codeOf(() => g.entities.unmerge(mergeId)), + unsupported_store_version: unsupported, }; await g.relations.uncertify(moved); await g.entities.unmerge(mergeId); diff --git a/typescript/test/install.test.ts b/typescript/test/install.test.ts index da33e329..8ff41451 100644 --- a/typescript/test/install.test.ts +++ b/typescript/test/install.test.ts @@ -14,7 +14,7 @@ import { fileURLToPath } from "node:url"; import { beforeAll, describe, expect, it } from "vitest"; -import { installLlm, llmServerArgs, mergeToml, SERVER_ARGS, SERVER_COMMAND } from "../src/install.js"; +import { AGENTS, installLlm, llmServerArgs, mergeToml, SERVER_ARGS, SERVER_COMMAND } from "../src/install.js"; import { buildLlm, DEFAULT_SETTINGS, SETTING_KEYS } from "../src/runtime.js"; import { buildCli, runCli, tempDir } from "./helpers.js"; @@ -232,6 +232,21 @@ const json = (path: string): unknown => JSON.parse(readFileSync(path, "utf8")); beforeAll(buildCli); +it("warns for HydraDB without a token", () => { + const where = dirs(); + const args = ["install", AGENTS[0]!, "--uri", "bolt://127.0.0.1:7687"]; + const env = { ...NO_SETTINGS, HOME: where.home, USERPROFILE: where.home }; + const run = (auth?: string, remove = false) => + runCli(remove ? [...args, "--remove"] : args, { cwd: where.project, env: { ...env, SELFGRAPH_AUTH: auth } }); + expect(run()).toMatchObject({ + code: 0, + err: "warning: HydraDB needs a token. Set SELFGRAPH_AUTH in the environment that starts the MCP server.\n", + }); + expect(run("local-test-token")).toMatchObject({ code: 0, err: "" }); + expect(readFileSync(join(where.project, ".mcp.json"), "utf8")).not.toContain("local-test-token"); + expect(run(undefined, true)).toMatchObject({ code: 0, err: "" }); +}); + describe("selfgraph install", () => { it("writes each agent's file shape", () => { const where = dirs();