diff --git a/docs/backends.md b/docs/backends.md index 88281059..bdafc636 100644 --- a/docs/backends.md +++ b/docs/backends.md @@ -270,5 +270,19 @@ after acquiring a lock. Stores whose lock is a no-op declare `lock_refreshes_reads = False` (`lockRefreshesReads = false`); other stores keep the read after locking. +A store that cannot list every entity may implement `seed_candidates(ns, terms)` +(`seedCandidates` in TypeScript). It returns the stored properties of the entities +whose names hold one of the query words. `retrieve` and `search` then rank only +those candidates with BM25, instead of reading every entity page. + +A store that cuts an edge read short, for example at an engine limit, calls +`selfgraph.retrieval.mark_partial()` (`markPartial` in TypeScript) during the read. +Only `match_edges` may come back partial: node reads by id still return every +node that exists. +The `retrieve`, `neighbors`, `find_path`, and impact result of that call then has +`truncated` set to true. `retrieve` and `find_path` leave `truncated` out of their +output when it is false. + For FalkorDB's optional native RESP parser, install `selfgraph[falkordb-fast]`. The regular `falkordb` extra remains available without it. + diff --git a/docs/errors.md b/docs/errors.md index 750aefa6..ffb5886e 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -287,6 +287,18 @@ The database named in the connection settings does not exist on the server. Corr The server does not match the configured store backend. Check which engine is running at the configured host and port, then correct the `store` setting or server address before reconnecting. +#### `read_only_store` + +This store reads tables that the application owns, so it refuses every write. Change the rows through the application; the next read sees them. + +#### `unsupported_read` + +This store reads rows only by id, by a name match, or by a walk from known rows. Use retrieve, entities.get, neighbors, or find_path instead of a call that lists every row or runs Cypher. + +#### `graph_unavailable` + +The pg_hydradb graph is not registered, is paused, or this login cannot read its tables. Do what the message says, or ask the database owner to register the graph, refresh it, or grant SELECT. + #### `write_too_large` A single node or edge row is larger than HydraDB accepts in one message. Split diff --git a/docs/retrieval.md b/docs/retrieval.md index 14c2f80a..bb836986 100644 --- a/docs/retrieval.md +++ b/docs/retrieval.md @@ -464,6 +464,10 @@ Both reads share these rules: each relation as the version valid then, as `retrieve` does (see [As of a point in time](#as-of-a-point-in-time)). - A deleted entity is never reached, so a walk never passes through one. +- A store can cut a read short at an engine limit (see + [optional store primitives](backends.md#optional-store-primitives)). The + `neighbors`, `find_path`, and `retrieve` result then has `truncated` set to + true, so the answer is known to be partial. - A start or end entity that does not exist raises `NotFoundError`. A `depth` or `max_depth` outside 1 to 4, an unknown `direction`, an empty `types` list, or a `limit` below 1 raises `ValidationError`. diff --git a/docs/trust.md b/docs/trust.md index ed70dff0..ec6f83ae 100644 --- a/docs/trust.md +++ b/docs/trust.md @@ -26,7 +26,7 @@ report = await graph.readiness() | Field | Holds | |-------|-------| | `ready` | True when the store is reachable and the namespace has at least one entity. | -| `reachable`, `error` | Whether the store answered, and its error when it did not. An unreachable store is reported, not raised. | +| `reachable`, `error` | Whether the store answered, and its error when it did not. An unreachable store is reported, not raised. A store that refuses to read every item (`unsupported_read`) is reported ready and reachable, with that error and no counts. | | `store`, `namespace`, `has_schema` | The store class, the namespace, and whether a schema is set. | | `counts` | Entities, current relations, current preferences, decisions, and sources, then `entity_types` and `relation_types`: each type with its count of entities and of current relations, in type order. A placeholder counts under its type. | | `lint` | Each problem found, as `{code, count, sample}`, with up to five ids in id order. | diff --git a/src/selfgraph/client.py b/src/selfgraph/client.py index e477f106..1eb220b9 100644 --- a/src/selfgraph/client.py +++ b/src/selfgraph/client.py @@ -750,7 +750,8 @@ async def readiness(self) -> Readiness: and lint (orphan entities, relations without evidence, decisions with a retired step, off-schema types, unresolved placeholders). - An unreachable store is reported, not raised. This reads every item in the namespace and writes nothing. + An unreachable store is reported, not raised. This reads every item in the namespace and writes nothing. A store + that refuses to read every item (unsupported_read) is reported ready and reachable, with no counts. @return (Readiness): ready, reachable, any connection error, the counts, and the lint issues. """ @@ -763,7 +764,8 @@ async def readiness(self) -> Readiness: reader = await self._reader() counts, issues = await inspect(reader, self.namespace, self._schema) except StoreError as exc: - return Readiness(ready=False, reachable=False, error=str(exc), **fields) + scans = exc.code == "unsupported_read" + return Readiness(ready=scans, reachable=scans, error=str(exc), **fields) return Readiness(ready=counts["entities"] > 0, reachable=True, counts=counts, lint=issues, **fields) @_store_call diff --git a/src/selfgraph/errors.py b/src/selfgraph/errors.py index e5f97b5e..d1bf6b93 100644 --- a/src/selfgraph/errors.py +++ b/src/selfgraph/errors.py @@ -58,6 +58,9 @@ "store_auth_failed", "database_not_found", "wrong_engine", + "read_only_store", + "unsupported_read", + "graph_unavailable", "write_too_large", "write_conflict", "store_busy", @@ -202,6 +205,18 @@ "The server does not match the configured store backend. Check which engine is running at the " "configured host and port, then correct the `store` setting or server address before reconnecting." ), + "read_only_store": ( + "This store reads tables that the application owns, so it refuses every write. Change the rows through " + "the application; the next read sees them." + ), + "unsupported_read": ( + "This store reads rows only by id, by a name match, or by a walk from known rows. Use retrieve, " + "entities.get, neighbors, or find_path instead of a call that lists every row or runs Cypher." + ), + "graph_unavailable": ( + "The pg_hydradb graph is not registered, is paused, or this login cannot read its tables. Do what the " + "message says, or ask the database owner to register the graph, refresh it, or grant SELECT." + ), "write_too_large": ( "A single node or edge row is larger than HydraDB accepts in one message. Split large property values " "or text. Do not cut data without asking the user." @@ -470,6 +485,37 @@ def needs_llm(what: str) -> ValidationError: return ValidationError(f"{what} needs an LLM: {LLM_HINT}", code="llm_required") +def read_only_store(call: str) -> StoreError: + """The error for a write on a store that reads tables it does not own. + + @param call (str): the refused primitive, such as "upsert_node". + @return (StoreError): the error, with code read_only_store. + """ + return StoreError(f"the postgres store is read-only and refuses {call}", code="read_only_store") + + +def unsupported_read(what: str) -> StoreError: + """The error for a read that a store which reads only by id, name, or walk cannot serve. + + @param what (str): the refused read, such as "list every entity". + @return (StoreError): the error, with code unsupported_read. + """ + return StoreError( + f"the postgres store cannot {what}; it reads rows only by id, by name, or by a walk from known rows", + code="unsupported_read", + ) + + +def graph_unavailable(graph: str, reason: str) -> StoreError: + """The error for a pg_hydradb graph that is missing, paused, or unreadable. + + @param graph (str): the graph name. + @param reason (str): what is wrong and how to fix it. + @return (StoreError): the error, with code graph_unavailable. + """ + return StoreError(f"pg_hydradb graph {graph!r} {reason}", code="graph_unavailable", field="graph") + + def internal_error(exc: BaseException, *uris: str | None) -> InternalError: """Wrap an unexpected error that reached a boundary as a coded InternalError with every URI's credentials masked. diff --git a/src/selfgraph/models.py b/src/selfgraph/models.py index 518228e5..080acf1b 100644 --- a/src/selfgraph/models.py +++ b/src/selfgraph/models.py @@ -1151,10 +1151,11 @@ class RetrievalResult(BaseModel): tiers: dict[str, str] = Field(default_factory=dict) hubs: list[str] = Field(default_factory=list) evidence: list[ContextEvidence] | None = None + truncated: bool = False @model_serializer(mode="wrap") def _omit_unnumbered(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: - """Serialize the result, leaving out evidence when the context was not numbered. + """Serialize the result, leaving out evidence when the context was not numbered and truncated when false. @param handler (SerializerFunctionWrapHandler): pydantic's default serializer. @return (dict[str, Any]): the serialized result. @@ -1162,6 +1163,8 @@ def _omit_unnumbered(self, handler: SerializerFunctionWrapHandler) -> dict[str, data = handler(self) if self.evidence is None: data.pop("evidence", None) + if not self.truncated: + data.pop("truncated", None) return data @@ -1242,6 +1245,19 @@ class PathResult(BaseModel): end: Entity found: bool steps: list[PathStep] = Field(default_factory=list) + truncated: bool = False + + @model_serializer(mode="wrap") + def _omit_complete(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: + """Serialize the path, leaving out truncated unless a store cut a read short. + + @param handler (SerializerFunctionWrapHandler): pydantic's default serializer. + @return (dict[str, Any]): the serialized path. + """ + data = handler(self) + if not self.truncated: + data.pop("truncated", None) + return data class TermCoverage(BaseModel): diff --git a/src/selfgraph/retrieval.py b/src/selfgraph/retrieval.py index 4e24ce4b..b168bb7a 100644 --- a/src/selfgraph/retrieval.py +++ b/src/selfgraph/retrieval.py @@ -7,7 +7,8 @@ import re from collections import deque from collections.abc import Awaitable, Callable, Collection, Iterable -from functools import partial +from contextvars import ContextVar +from functools import partial, wraps from typing import TYPE_CHECKING from . import _ops @@ -62,7 +63,9 @@ from .client import SelfGraph from .schema import Schema -__all__ = ["answerability", "check_answerable", "find_path", "neighbors", "retrieve", "search"] +__all__ = ["answerability", "check_answerable", "find_path", "mark_partial", "neighbors", "retrieve", "search"] + +_PARTIAL: ContextVar[list[bool] | None] = ContextVar("selfgraph_partial", default=None) _STOPWORDS = frozenset( { @@ -175,6 +178,39 @@ MAX_DEPTH = 4 +def mark_partial() -> None: + """Record that a store cut an edge read short, so the retrieve, neighbors, impact, or find_path running it says so. + + @return (None): nothing. + """ + flags = _PARTIAL.get() + if flags is not None: + flags.append(True) + + +def _flags_partial(fn): + """Set truncated on a read's result when a store marked one of its reads partial. + + @param fn (Callable): the read, returning a result with a truncated field. + @return (Callable): the wrapped read. + """ + + @wraps(fn) + async def read(*args, **kwargs): + """Run the read with a fresh partial flag.""" + flags: list[bool] = [] + token = _PARTIAL.set(flags) + try: + result = await fn(*args, **kwargs) + finally: + _PARTIAL.reset(token) + if flags: + result.truncated = True + return result + + return read + + def _fold(text: str) -> str: """Normalize text to NFC and casefold it, so query and stored text compare in one form. @@ -521,7 +557,8 @@ async def _scan_seeds( first_docs: list[tuple[str, list[str]]] | None = None pages_read = 0 query_stems: set[str] | None = None - async for page in _entity_pages(graph, ns, as_of, valid, keep): + terms = query_tokens | exact + async for page in _entity_pages(graph, ns, as_of, valid, keep, terms): stats, docs = _seed_corpus(page, query_tokens, stats, retain=kept is not None) pages_read += 1 if pages_read == 1: @@ -537,7 +574,7 @@ async def scored(): if pages_read == 1: yield first, first_docs elif kept is None: - async for page in _entity_pages(graph, ns, as_of, valid, keep): + async for page in _entity_pages(graph, ns, as_of, valid, keep, terms): yield page, None elif kept[0]: yield [entity for entity, _ in kept[0]], [doc for _, doc in kept[0]] @@ -550,18 +587,28 @@ async def scored(): return best -async def _entity_pages(graph: SelfGraph, ns: str, as_of: AsOf | None, valid: list[Preference] | None, keep=None): +async def _entity_pages( + graph: SelfGraph, ns: str, as_of: AsOf | None, valid: list[Preference] | None, keep=None, terms=None +): """Stream every entity in id-ordered pages, keeping only those visible at as_of when it is set. + A store with a seed_candidates(ns, terms) read gives the one page of entities whose names hold a query word. + @param graph (SelfGraph): the open graph. @param ns (str): the namespace to read. @param as_of (AsOf | None): keep only the entities visible at this time, or None for all. @param valid (list[Preference] | None): the preference versions valid at as_of. @param keep (Callable[[Entity], bool] | None): keep only the entities it accepts, or None for all. + @param terms (set[str] | None): the query words, for a store that reads seed candidates by name. @return (AsyncIterator[list[Entity]]): the pages. """ - fetch = partial(_ops.list_entities, graph.store, ns, type=None, name=None, skip=0) - async for page in _ops._keyset(lambda after, limit: fetch(limit=limit, after=after), page=_SEED_PAGE): + seek = getattr(graph.store, "seed_candidates", None) + if seek is not None: + pages = _one_page(sorted(map(decode_entity, await seek(ns, sorted(terms or ()))), key=lambda e: e.id)) + else: + fetch = partial(_ops.list_entities, graph.store, ns, type=None, name=None, skip=0) + pages = _ops._keyset(lambda after, limit: fetch(limit=limit, after=after), page=_SEED_PAGE) + async for page in pages: if keep is not None: page = [e for e in page if keep(e)] if as_of is not None: @@ -570,6 +617,16 @@ async def _entity_pages(graph: SelfGraph, ns: str, as_of: AsOf | None, valid: li yield page +async def _one_page(page: list[Entity]): + """Yield one page when it holds anything. + + @param page (list[Entity]): the page. + @return (AsyncIterator[list[Entity]]): the page, or nothing. + """ + if page: + yield page + + def _cosine(a: list[float], b: list[float]) -> float: """The cosine similarity of two vectors, 0 when either has no length. @@ -616,7 +673,7 @@ async def _embedding_seeds( embedder, cache = graph._embedder, graph._embeddings (target,) = await embedder.embed([query]) best: list[tuple[Entity, float]] = [] - async for page in _entity_pages(graph, ns, as_of, valid, keep): + async for page in _entity_pages(graph, ns, as_of, valid, keep, _tokens(query) | _short_tokens(query)): texts = {e.id: _entity_text(e) for e in page} found = {e.id: cache[(ns, e.id)][1] for e in page if cache.get((ns, e.id), ("", []))[0] == texts[e.id]} stale = [e.id for e in page if e.id not in found] @@ -1327,10 +1384,13 @@ async def _id_seeds(graph: SelfGraph, ns: str, entity_ids: list[str]) -> list[tu async def _empty_reason(store, ns: str, fallback: str) -> str: """Explain empty reads. @param ns (str): namespace. @param fallback (str): reason. @return (str): reason.""" + if getattr(store, "seed_candidates", None) is not None: + return fallback counts = await asyncio.gather(*(store.match_nodes(ns, label, limit=1) for label in (L_ENTITY, L_SOURCE, L_TRACE))) return fallback if any(counts) else "empty_graph" +@_flags_partial async def retrieve( graph: SelfGraph, query: str | None, @@ -1741,6 +1801,7 @@ async def _walk( return entities, dist, walked, via, truncated +@_flags_partial async def neighbors( graph: SelfGraph, entity_id: str, @@ -1776,6 +1837,7 @@ async def neighbors( ) +@_flags_partial async def impact( graph: SelfGraph, entity_id: str, @@ -1810,28 +1872,30 @@ async def impact( def _trace( source: str, reached: tuple[dict[str, int], dict[str, int]], - hops: list[int], relations: dict[str, Relation], direction: str, ) -> list[tuple[Relation, str, str]]: """Pick the shortest path two meeting searches found, taking the lowest entity id, then relation id, at each step. + The path runs through the entities both searches reached with the least total distance, so it holds even when a + store cut one side's read short and the two searches met before their last levels. + @param source (str): the start entity id. @param reached (tuple[dict[str, int], dict[str, int]]): each entity's distance from the start and from the end. - @param hops (list[int]): how many levels the search from each end walked. @param relations (dict[str, Relation]): every relation the searches followed, by id. @param direction (str): the way the path travels: "out", "in", or "both". @return (list[tuple[Relation, str, str]]): each step's relation, "out" or "in", and the entity it reaches. """ forward, backward = reached - middle, length = hops[0], hops[0] + hops[1] + length, middle = min((d + backward[n], -d) for n, d in forward.items() if n in backward) + middle = -middle travel: dict[str, list[tuple[str, str, Relation, str]]] = {} for rel in relations.values(): if direction != "in": travel.setdefault(rel.from_entity, []).append((rel.to_entity, rel.id, rel, "out")) if direction != "out": travel.setdefault(rel.to_entity, []).append((rel.from_entity, rel.id, rel, "in")) - on_path = [{n for n, d in forward.items() if d == middle and backward.get(n) == hops[1]}] + on_path = [{n for n, d in forward.items() if d == middle and backward.get(n) == length - middle}] for i in range(middle - 1, -1, -1): after = on_path[0] on_path.insert(0, {n for n, d in forward.items() if d == i and any(o in after for o, *_ in travel.get(n, ()))}) @@ -1890,10 +1954,11 @@ async def _shortest( following.append(nxt) frontier[side] = following if any(n in other for n in following): - return _trace(source, reached, hops, relations, direction) + return _trace(source, reached, relations, direction) return None +@_flags_partial async def find_path( graph: SelfGraph, from_id: str, diff --git a/tests/test_errors.py b/tests/test_errors.py index 2f2ba2bb..58ce1ad0 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -32,7 +32,10 @@ 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 @@ -274,6 +277,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")), "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"), diff --git a/tests/test_store_read_hooks.py b/tests/test_store_read_hooks.py new file mode 100644 index 00000000..b481d586 --- /dev/null +++ b/tests/test_store_read_hooks.py @@ -0,0 +1,104 @@ +from helpers import fresh_graph, run + +from selfgraph import SelfGraph +from selfgraph.errors import unsupported_read +from selfgraph.retrieval import mark_partial + +FACTS = { + "entities": [ + {"type": "Person", "name": "Ann"}, + {"type": "Company", "name": "Acme"}, + {"type": "Company", "name": "Acme Labs"}, + ], + "relations": [{"from_entity": "person:ann", "type": "WORKS_AT", "to_entity": "company:acme"}], +} + + +class _Hooked: + def __init__(self, store, candidates=None, partial=False): + self._store, self._candidates, self._partial, self.asked = store, candidates, partial, [] + + def __getattr__(self, name): + return getattr(self._store, name) + + async def seed_candidates(self, ns, terms): + self.asked.append(sorted(terms)) + return [await self._store.get_node(ns, "Entity", eid) for eid in self._candidates] + + async def match_edges(self, ns, **kwargs): + if self._partial: + mark_partial() + return await self._store.match_edges(ns, **kwargs) + + +def _graph(**hooks): + base = fresh_graph("hooks") + run(base.insert.facts(FACTS)) + store = _Hooked(base.store, **hooks) + return SelfGraph(store, namespace=base.namespace), store + + +def test_a_store_with_seed_candidates_seeds_only_from_them(): + g, store = _graph(candidates=["company:acme-labs"]) + result = run(g.retrieve("who works at Acme")) + assert [s.id for s in result.seeds] == ["company:acme-labs"] + assert store.asked == [["acme", "works"]] + assert run(g.retrieve("nobody here")).reason == "no_seeds_matched" + + +def test_a_read_a_store_cut_short_marks_each_walk_result_truncated(): + g, _ = _graph(partial=True) + retrieved = run(g.retrieve(entity_ids=["person:ann"])) + assert retrieved.truncated and retrieved.model_dump()["truncated"] is True + assert run(g.neighbors("person:ann")).truncated + path = run(g.find_path("person:ann", "company:acme")) + assert path.found and path.truncated + + +def test_a_complete_read_leaves_truncated_out_of_the_retrieve_and_path_output(): + g, _ = _graph(candidates=["person:ann"]) + assert "truncated" not in run(g.retrieve("Ann")).model_dump() + assert "truncated" not in run(g.find_path("person:ann", "company:acme")).model_dump() + assert run(g.neighbors("person:ann")).truncated is False + + +class _CutHub(_Hooked): + async def match_edges(self, ns, **kwargs): + rows = await self._store.match_edges(ns, **kwargs) + if "company:acme" in (kwargs.get("to_in") or ()): + mark_partial() + return [r for r in rows if r["from_id"] != "person:bob"] + return rows + + +def test_find_path_holds_when_a_cut_read_lets_the_searches_meet_early(): + base = fresh_graph("hooks") + people = ["ann", "bob", "carl", "dave"] + run( + base.insert.facts( + { + "entities": [{"type": "Company", "name": "Acme"}, *({"type": "Person", "name": p} for p in people)], + "relations": [ + {"from_entity": f"person:{p}", "type": "WORKS_AT", "to_entity": "company:acme"} for p in people + ], + } + ) + ) + g = SelfGraph(_CutHub(base.store), namespace=base.namespace) + path = run(g.find_path("person:ann", "person:bob")) + assert path.found and path.truncated + assert [(s.direction, s.entity.id) for s in path.steps] == [("out", "company:acme"), ("in", "person:bob")] + + +class _NoScans(_Hooked): + async def match_nodes(self, ns, label, **kwargs): + if "any_of" not in kwargs: + raise unsupported_read("list every entity") + return await self._store.match_nodes(ns, label, **kwargs) + + +def test_readiness_reports_a_store_that_refuses_full_scans_as_reachable(): + base = fresh_graph("hooks") + ready = run(SelfGraph(_NoScans(base.store), namespace=base.namespace).readiness()) + assert (ready.ready, ready.reachable, ready.counts) == (True, True, {}) + assert ready.error.startswith("the postgres store cannot list every entity") diff --git a/typescript/src/client.ts b/typescript/src/client.ts index 31a7b4c2..51771e6e 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -475,7 +475,7 @@ export class SelfGraph { /** * Report whether the graph can answer: the store is reachable and the namespace holds entities, with counts and lint (orphan entities, relations without evidence, decisions with a retired step, off-schema types, unresolved placeholders). * - * An unreachable store is reported, not thrown. This reads every item in the namespace and writes nothing. + * An unreachable store is reported, not thrown. This reads every item in the namespace and writes nothing. A store that refuses to read every item (unsupported_read) is reported ready and reachable, with no counts. * * @return (Readiness): ready, reachable, any connection error, the counts, and the lint issues. */ @@ -488,10 +488,11 @@ export class SelfGraph { [counts, lint] = await this.graph.read((store, ns) => inspect(store, ns, this.schema)); } catch (exc) { if (!(exc instanceof StoreError)) throw exc; + const scans = exc.code === "unsupported_read"; return { - ready: false, + ready: scans, ...base, - reachable: false, + reachable: scans, error: exc.message, has_schema: hasSchema, counts: {}, diff --git a/typescript/src/errors.ts b/typescript/src/errors.ts index 1c3b0cef..1298ce87 100644 --- a/typescript/src/errors.ts +++ b/typescript/src/errors.ts @@ -67,6 +67,12 @@ export const HINTS = { "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: "The server does not match the configured store backend. Check which engine is running at the configured host and port, then correct the `store` setting or server address before reconnecting.", + read_only_store: + "This store reads tables that the application owns, so it refuses every write. Change the rows through the application; the next read sees them.", + unsupported_read: + "This store reads rows only by id, by a name match, or by a walk from known rows. Use retrieve, entities.get, neighbors, or find_path instead of a call that lists every row or runs Cypher.", + graph_unavailable: + "The pg_hydradb graph is not registered, is paused, or this login cannot read its tables. Do what the message says, or ask the database owner to register the graph, refresh it, or grant SELECT.", write_too_large: "A single node or edge row is larger than HydraDB accepts in one message. Split large property values or text. Do not cut data without asking the user.", write_conflict: @@ -303,6 +309,40 @@ export const OTHER_ENGINE_HINT = 'pass store: "neo4j" (or store: "memgraph")'; export const DECAY_HINT = "run maintenance.decay({ dry_run: false }) first"; export const KEY_SOURCES = "api_key in the llm config (or SELFGRAPH_LLM_API_KEY)"; +/** + * The error for a write on a store that reads tables it does not own. + * + * @param call (string): the refused primitive, such as "upsertNode". + * @return (StoreError): the error, with code read_only_store. + */ +export function readOnlyStore(call: string): StoreError { + return new StoreError(`the postgres store is read-only and refuses ${call}`, { code: "read_only_store" }); +} + +/** + * The error for a read that a store which reads only by id, name, or walk cannot serve. + * + * @param what (string): the refused read, such as "list every entity". + * @return (StoreError): the error, with code unsupported_read. + */ +export function unsupportedRead(what: string): StoreError { + return new StoreError( + `the postgres store cannot ${what}; it reads rows only by id, by name, or by a walk from known rows`, + { code: "unsupported_read" }, + ); +} + +/** + * The error for a pg_hydradb graph that is missing, paused, or unreadable. + * + * @param graph (string): the graph name. + * @param reason (string): what is wrong and how to fix it. + * @return (StoreError): the error, with code graph_unavailable. + */ +export function graphUnavailable(graph: string, reason: string): StoreError { + return new StoreError(`pg_hydradb graph ${pyRepr(graph)} ${reason}`, { code: "graph_unavailable", field: "graph" }); +} + /** * The error for a feature that needs an LLM when none is configured. * diff --git a/typescript/src/index.ts b/typescript/src/index.ts index e82df330..56f130dd 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -197,6 +197,7 @@ export type { SearchOptions, Strategy, } from "./retrieval.js"; +export { markPartial } from "./retrieval.js"; export { DEFAULT_SETTINGS, type GraphSettings, STORES, settingsFromEnv, version } from "./runtime.js"; export { type ContradictionMode, diff --git a/typescript/src/models.ts b/typescript/src/models.ts index 8faa3542..f92992fc 100644 --- a/typescript/src/models.ts +++ b/typescript/src/models.ts @@ -758,6 +758,7 @@ export interface RetrievalResult { tiers: Record; hubs: string[]; evidence?: ContextEvidence[]; + truncated?: boolean; } export interface UnsupportedSentence { @@ -837,6 +838,7 @@ export interface PathResult { end: Entity; found: boolean; steps: PathStep[]; + truncated?: boolean; } export interface TermCoverage { diff --git a/typescript/src/protocols.ts b/typescript/src/protocols.ts index 083d5cff..25aae511 100644 --- a/typescript/src/protocols.ts +++ b/typescript/src/protocols.ts @@ -213,6 +213,14 @@ export interface GraphPrimitives { * @return (Props[]): the matching entities' properties. */ entitiesMatching?(ns: string, keys: Iterable): Promise; + /** + * Read the entities whose names hold one of some query words, for a store that cannot list every entity. + * + * @param ns (string): the namespace. + * @param terms (readonly string[]): the query words, sorted. + * @return (Props[]): the candidate entities' properties, which retrieve and search rank with BM25. + */ + seedCandidates?(ns: string, terms: readonly string[]): Promise; /** * Report which of some node ids exist under one label, for a store that seeks many ids in one read. * @param ns (string): the namespace. diff --git a/typescript/src/retrieval.ts b/typescript/src/retrieval.ts index dd64949a..c21b2d5d 100644 --- a/typescript/src/retrieval.ts +++ b/typescript/src/retrieval.ts @@ -1,3 +1,4 @@ +import { AsyncLocalStorage } from "node:async_hooks"; import { type GraphAccess, rerankTier, seedTier } from "./access.js"; import { loadTokenizer } from "./chunking.js"; import { NotFoundError, ValidationError } from "./errors.js"; @@ -47,8 +48,33 @@ import { definitionIndex, expandTokens, groundedTerms, schemaForms, stem } from import type { RerankTier, SeedTier } from "./tiers.js"; import { checkOptions, keysOf, requireBool, requireInt, requireList, typeName } from "./validate.js"; +const PARTIAL = new AsyncLocalStorage(); + +/** + * Record that a store cut an edge read short, so the retrieve, neighbors, impact, or findPath running it says so. + * + * @return (void): nothing. + */ +export function markPartial(): void { + PARTIAL.getStore()?.push(true); +} + +/** + * Run a read with a fresh partial flag, and set truncated on its result when a store marked one of its reads partial. + * + * @param read (() => Promise): the read, returning a result with a truncated field. + * @return (Promise): the result. + */ +async function flagsPartial(read: () => Promise): Promise { + const flags: boolean[] = []; + const result = await PARTIAL.run(flags, read); + if (flags.length) result.truncated = true; + return result; +} + /** Explain an empty read. @param store (GraphPrimitives): reader. @param ns (string): namespace. @param fallback (string): populated reason. @return (Promise): reason. */ async function emptyReason(store: GraphPrimitives, ns: string, fallback: string): Promise { + if (store.seedCandidates) return fallback; const counts = await Promise.all( [L_ENTITY, L_SOURCE, L_TRACE].map((label) => store.matchNodes(ns, label, { limit: 1 })), ); @@ -471,7 +497,8 @@ async function scanSeeds( let firstDocs: EntityDoc[] | null = null; let pagesRead = 0; let queryStems: Set = new Set(); - for await (const page of entityPages(store, ns, asOf, valid, keep)) { + const terms = new Set([...queryTokens, ...exact]); + for await (const page of entityPages(store, ns, asOf, valid, keep, terms)) { let docs: EntityDoc[] | null; [stats, docs] = seedCorpus(page, queryTokens, stats, kept !== null); pagesRead += 1; @@ -488,7 +515,8 @@ async function scanSeeds( const retained = kept; async function* scored(): AsyncGenerator<[Entity[], EntityDoc[] | null]> { if (pagesRead === 1) yield [first, firstDocs]; - else if (retained === null) for await (const page of entityPages(store, ns, asOf, valid, keep)) yield [page, null]; + else if (retained === null) + for await (const page of entityPages(store, ns, asOf, valid, keep, terms)) yield [page, null]; else if (retained[0].length) yield [retained[0].map(([entity]) => entity), retained[0].map(([, doc]) => doc)]; } let best: Array<[Entity, number]> = []; @@ -502,11 +530,14 @@ async function scanSeeds( /** * Stream every entity in id-ordered pages, keeping only those visible at asOf when it is set. * + * A store with a seedCandidates(ns, terms) read gives the one page of entities whose names hold a query word. + * * @param store (GraphPrimitives): the graph reader. * @param ns (string): the namespace to read. * @param asOf (AsOf | null): keep only the entities visible at this time, or null for all. * @param valid (Preference[] | null): the preference versions valid at asOf. * @param keep (((e: Entity) => boolean) | null): keep only the entities it accepts, or null for all. + * @param terms (Set | null): the query words, for a store that reads seed candidates by name. * @return (AsyncGenerator): the pages. */ async function* entityPages( @@ -515,11 +546,16 @@ async function* entityPages( asOf: ops.AsOf | null, valid: Preference[] | null, keep: ((e: Entity) => boolean) | null = null, + terms: Set | null = null, ): AsyncGenerator { - for await (let page of ops.keyset( - (after, limit) => ops.listEntities(store, ns, { skip: 0, limit, after }), - SEED_PAGE, - )) { + const pages = store.seedCandidates + ? onePage( + (await store.seedCandidates(ns, [...(terms ?? [])].sort(comparePy))) + .map(decodeEntity) + .sort((a, b) => comparePy(a.id, b.id)), + ) + : ops.keyset((after, limit) => ops.listEntities(store, ns, { skip: 0, limit, after }), SEED_PAGE); + for await (let page of pages) { if (keep !== null) page = page.filter(keep); if (asOf === null || valid === null) { yield page; @@ -530,6 +566,16 @@ async function* entityPages( } } +/** + * Yield one page when it holds anything. + * + * @param page (Entity[]): the page. + * @return (AsyncGenerator): the page, or nothing. + */ +async function* onePage(page: Entity[]): AsyncGenerator { + if (page.length) yield page; +} + /** * The cosine similarity of two vectors, 0 when either has no length. * @@ -594,7 +640,8 @@ async function embeddingSeeds( const [target] = await embed(embedder, [query]); const key = (eid: string): string => JSON.stringify([ns, eid]); let best: Array<[Entity, number]> = []; - for await (const page of entityPages(store, ns, asOf, valid, keep)) { + const terms = new Set([...tokens(query), ...shortTokens(query)]); + for await (const page of entityPages(store, ns, asOf, valid, keep, terms)) { const texts = new Map(page.map((e) => [e.id, entityText(e)])); const found = new Map(); for (const e of page) { @@ -1472,7 +1519,7 @@ export async function retrieve( if (value < least) throw new ValidationError(`${name} must be >= ${least}, got ${value}`, { field: name }); } const opts = { entityIds, strategy, depth, k, maxNodes, budgetTokens, asOf, seeds, skipHubs, numbered, rerank }; - return graph.read((store, ns) => run(graph, store, ns, query, opts)); + return flagsPartial(() => graph.read((store, ns) => run(graph, store, ns, query, opts))); } interface RunOptions { @@ -2036,17 +2083,19 @@ export async function listNeighbors( requireInt("limit", limit); if (limit < 1) throw new ValidationError(`limit must be >= 1, got ${limit}`, { field: "limit" }); const asOf = ops.parseAsOf(options.as_of, options.known_at); - return graph.read(async (store, ns) => { - const start = await endpoint(store, ns, eid); - const { entities, dist, walked, truncated } = await walk(store, ns, start, depth, direction, types, limit, asOf); - const [first, ...rest] = entities; - return { - start: first!, - neighbors: rest.map((entity) => ({ entity, distance: dist.get(entity.id)! })), - relations: within(walked.values(), dist).sort((a, b) => comparePy(a.id, b.id)), - truncated, - }; - }); + return flagsPartial(() => + graph.read(async (store, ns) => { + const start = await endpoint(store, ns, eid); + const { entities, dist, walked, truncated } = await walk(store, ns, start, depth, direction, types, limit, asOf); + const [first, ...rest] = entities; + return { + start: first!, + neighbors: rest.map((entity) => ({ entity, distance: dist.get(entity.id)! })), + relations: within(walked.values(), dist).sort((a, b) => comparePy(a.id, b.id)), + truncated, + }; + }), + ); } export const IMPACT_TYPES = ["CALLS", "CONSTRUCTS"] as const; @@ -2100,24 +2149,28 @@ export async function codeImpact( requireInt("limit", limit); if (limit < 1) throw new ValidationError(`limit must be >= 1, got ${limit}`, { field: "limit" }); const asOf = ops.parseAsOf(options.as_of, options.known_at); - return graph.read(async (store, ns) => { - const start = await endpoint(store, ns, eid); - const { entities, dist, via, truncated } = await walk(store, ns, start, maxDepth, direction, types, limit, asOf); - const [first, ...rest] = entities; - return { - start: first!, - reached: rest.map((entity) => ({ entity, distance: dist.get(entity.id)!, via: via.get(entity.id)! })), - truncated, - }; - }); + return flagsPartial(() => + graph.read(async (store, ns) => { + const start = await endpoint(store, ns, eid); + const { entities, dist, via, truncated } = await walk(store, ns, start, maxDepth, direction, types, limit, asOf); + const [first, ...rest] = entities; + return { + start: first!, + reached: rest.map((entity) => ({ entity, distance: dist.get(entity.id)!, via: via.get(entity.id)! })), + truncated, + }; + }), + ); } /** * Pick the shortest path two meeting searches found, taking the lowest entity id, then relation id, at each step. * + * The path runs through the entities both searches reached with the least total distance, so it holds even when a + * store cut one side's read short and the two searches met before their last levels. + * * @param source (string): the start entity id. * @param reached ([Map, Map]): each entity's distance from the start and from the end. - * @param hops ([number, number]): how many levels the search from each end walked. * @param relations (Map): every relation the searches followed, by id. * @param direction (Direction): the way the path travels: "out", "in", or "both". * @return (Step[]): each step's relation, "out" or "in", and the entity it reaches. @@ -2125,13 +2178,15 @@ export async function codeImpact( function trace( source: string, reached: [Map, Map], - hops: [number, number], relations: Map, direction: Direction, ): Step[] { const [forward, backward] = reached; - const middle = hops[0]; - const length = hops[0] + hops[1]; + let [length, middle] = [Number.POSITIVE_INFINITY, 0]; + for (const [n, d] of forward) { + const total = d + (backward.get(n) ?? Number.POSITIVE_INFINITY); + if (total < length || (total === length && d > middle)) [length, middle] = [total, d]; + } const travel = new Map>(); const add = (from: string, to: string, rel: Relation, way: "out" | "in") => { const list = travel.get(from) ?? []; @@ -2143,7 +2198,7 @@ function trace( if (direction !== "out") add(rel.to_entity, rel.from_entity, rel, "in"); } const atLevel = (d: number) => [...forward].filter(([, x]) => x === d).map(([n]) => n); - const onPath = new Map([[middle, new Set(atLevel(middle).filter((n) => backward.get(n) === hops[1]))]]); + const onPath = new Map([[middle, new Set(atLevel(middle).filter((n) => backward.get(n) === length - middle))]]); for (let i = middle - 1; i >= 0; i--) { const after = onPath.get(i + 1) ?? new Set(); onPath.set(i, new Set(atLevel(i).filter((n) => (travel.get(n) ?? []).some(([o]) => after.has(o))))); @@ -2212,7 +2267,7 @@ async function shortest( } } frontier[side] = following; - if (following.some((n) => other.has(n))) return trace(source, reached, hops, relations, direction); + if (following.some((n) => other.has(n))) return trace(source, reached, relations, direction); } return null; } @@ -2240,30 +2295,32 @@ export async function findPath( const direction = options.direction ?? PATH_DEFAULTS.direction; const types = followed(direction, options.types ?? null, graph.schema); const asOf = ops.parseAsOf(options.as_of, options.known_at); - return graph.read(async (store, ns) => { - const start = await endpoint(store, ns, source); - const end = await endpoint(store, ns, target); - const path = await shortest(store, ns, start.id, end.id, maxDepth, direction, types, asOf); - const known = new Map([ - [start.id, start], - [end.id, end], - ]); - await load( - store, - ns, - known, - (path ?? []).map(([, , eid]) => eid), - ); - let entities = [...known.values()]; - if (asOf?.known) entities = await ops.withKnownSources(store, ns, entities, asOf.known); - const found = new Map(entities.map((e) => [e.id, e])); - return { - start: found.get(start.id)!, - end: found.get(end.id)!, - found: path !== null, - steps: (path ?? []).map(([relation, way, eid]) => ({ relation, direction: way, entity: found.get(eid)! })), - }; - }); + return flagsPartial(() => + graph.read(async (store, ns) => { + const start = await endpoint(store, ns, source); + const end = await endpoint(store, ns, target); + const path = await shortest(store, ns, start.id, end.id, maxDepth, direction, types, asOf); + const known = new Map([ + [start.id, start], + [end.id, end], + ]); + await load( + store, + ns, + known, + (path ?? []).map(([, , eid]) => eid), + ); + let entities = [...known.values()]; + if (asOf?.known) entities = await ops.withKnownSources(store, ns, entities, asOf.known); + const found = new Map(entities.map((e) => [e.id, e])); + return { + start: found.get(start.id)!, + end: found.get(end.id)!, + found: path !== null, + steps: (path ?? []).map(([relation, way, eid]) => ({ relation, direction: way, entity: found.get(eid)! })), + }; + }), + ); } /** diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 4d31efca..9a0a53a2 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -54,11 +54,14 @@ HINTS, SelfGraphError, connection_reason, + graph_unavailable, internal_error, mask_uri, + read_only_store, redact_uri, redact_uris, surface_hint, + unsupported_read, ) from selfgraph.extraction.chunking import chunk_markdown, chunk_text, count_tokens from selfgraph.extraction.extractor import ( @@ -2193,6 +2196,9 @@ async def choice_errors(graph): "rel_create_dangling": await error_of(graph.relations.create("person:jane-doe", "KNOWS", "person:ghost")), "list_bad_cursor": await error_of(graph.entities.list(cursor="nope")), "store_refused": await error_of(SelfGraph(store=Neo4jStore("bolt://127.0.0.1:1")).entities.list()), + "read_only_store": await error_of(_raise_later(read_only_store("upsert_node"))), + "unsupported_read": await error_of(_raise_later(unsupported_read("list every entity"))), + "graph_unavailable": await error_of(_raise_later(graph_unavailable("it's", "is not registered"))), "list_limit_zero": await error_of(graph.entities.list(limit=0)), "list_limit_text": await error_of(graph.entities.list(limit="5")), "list_limit_float_non_integer": await error_of(graph.entities.list(limit=5.5)), diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index dbb275ac..891fab54 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -27,12 +27,15 @@ import { resolve } from "../../src/code/resolve.js"; import { diffTimeline } from "../../src/diff.js"; import { connectionReason, + graphUnavailable, HINTS, internalError, maskUri, + readOnlyStore, redactUri, redactUris, surfaceHint, + unsupportedRead, } from "../../src/errors.js"; import { assembleExtraction, @@ -2618,6 +2621,15 @@ async function choiceErrors(graph: SelfGraph): Promise graph.relations.create("person:jane-doe", "KNOWS", "person:ghost")), list_bad_cursor: await errorOf(() => graph.entities.list({ cursor: "nope" })), store_refused: await errorOf(() => new SelfGraph(new Neo4jStore("bolt://127.0.0.1:1")).entities.list()), + read_only_store: await errorOf(async () => { + throw readOnlyStore("upsert_node"); + }), + unsupported_read: await errorOf(async () => { + throw unsupportedRead("list every entity"); + }), + graph_unavailable: await errorOf(async () => { + throw graphUnavailable("it's", "is not registered"); + }), list_limit_zero: await errorOf(() => graph.entities.list({ limit: 0 })), list_limit_text: await errorOf(() => graph.entities.list({ limit: "5" } as never)), list_limit_float_non_integer: await errorOf(() => graph.entities.list({ limit: 5.5 })), diff --git a/typescript/test/errors.test.ts b/typescript/test/errors.test.ts index 0e87adf8..cc429b96 100644 --- a/typescript/test/errors.test.ts +++ b/typescript/test/errors.test.ts @@ -10,9 +10,12 @@ import { z } from "zod"; import { connectionReason, escapeControls, + graphUnavailable, HINTS, internalError, + readOnlyStore, SelfGraphError, + unsupportedRead, WARNING_HINTS, } from "../src/errors.js"; import { @@ -216,6 +219,9 @@ describe("error codes", () => { store_auth_failed: () => mapError(noToken, "Neo.ClientError.Security.Unauthorized", ""), database_not_found: () => mapError(hydradb, "", "database does not exist"), wrong_engine: () => mapError(hydradb, "", "unsupported protocol version"), + read_only_store: () => raise(readOnlyStore("upsertNode")), + unsupported_read: () => raise(unsupportedRead("count every row")), + graph_unavailable: () => raise(graphUnavailable("work", "cannot be read by this login")), write_too_large: () => hydradb.upsertNode("n", "Entity", "x", { id: "x", blob: "x".repeat(3_000_000) }), write_conflict: () => mapError(hydradb, "", "transaction conflict"), store_busy: () => busy.runCypher("RETURN 1"), diff --git a/typescript/test/storeReadHooks.test.ts b/typescript/test/storeReadHooks.test.ts new file mode 100644 index 00000000..47a27fc9 --- /dev/null +++ b/typescript/test/storeReadHooks.test.ts @@ -0,0 +1,132 @@ +import { expect, it } from "vitest"; + +import { unsupportedRead } from "../src/errors.js"; +import { type GraphStore, markPartial, SelfGraph } from "../src/index.js"; +import { forEachStore, freshGraphs, type StoreSpec } from "./helpers.js"; + +const FACTS = { + entities: [ + { type: "Person", name: "Ann" }, + { type: "Company", name: "Acme" }, + { type: "Company", name: "Acme Labs" }, + ], + relations: [{ from_entity: "person:ann", type: "WORKS_AT", to_entity: "company:acme" }], +}; + +/** + * Wrap a store with a seedCandidates read over some ids, or a matchEdges that marks every read partial. + * + * @param store (GraphStore): the store to wrap. + * @param hooks ({ candidates?: string[]; partial?: boolean }): the candidate ids, and whether reads are partial. + * @return ({ store: GraphStore; asked: string[][] }): the wrapped store and the terms each seed read got. + */ +function hooked(store: GraphStore, hooks: { candidates?: string[]; partial?: boolean }) { + const asked: string[][] = []; + const extra: Record = { + matchEdges: async (...args: Parameters) => { + if (hooks.partial) markPartial(); + return store.matchEdges(...args); + }, + }; + if (hooks.candidates) { + extra.seedCandidates = async (ns: string, terms: readonly string[]) => { + asked.push([...terms]); + return Promise.all(hooks.candidates!.map(async (id) => (await store.getNode(ns, "Entity", id))!)); + }; + } + const wrapped = new Proxy(store, { + get: (target, prop, receiver) => { + if (typeof prop === "string" && prop in extra) return extra[prop]; + const value = Reflect.get(target, prop, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + return { store: wrapped, asked }; +} + +function suite(spec: StoreSpec): void { + const fresh = freshGraphs(spec, "hooks"); + + async function graph(hooks: { candidates?: string[]; partial?: boolean }) { + const base = fresh(); + await base.insert.facts(FACTS); + const { store, asked } = hooked(base.store, hooks); + return { g: new SelfGraph(store, { namespace: base.namespace }), asked }; + } + + it("a store with seedCandidates seeds only from them", async () => { + const { g, asked } = await graph({ candidates: ["company:acme-labs"] }); + const result = await g.retrieve("who works at Acme"); + expect(result.seeds.map((s) => s.id)).toEqual(["company:acme-labs"]); + expect(asked).toEqual([["acme", "works"]]); + expect((await g.retrieve("nobody here")).reason).toBe("no_seeds_matched"); + }); + + it("a read a store cut short marks each walk result truncated", async () => { + const { g } = await graph({ partial: true }); + expect((await g.retrieve(null, { entity_ids: ["person:ann"] })).truncated).toBe(true); + expect((await g.neighbors("person:ann")).truncated).toBe(true); + const path = await g.findPath("person:ann", "company:acme"); + expect([path.found, path.truncated]).toEqual([true, true]); + }); + + it("a complete read leaves truncated out of the retrieve and path output", async () => { + const { g, asked } = await graph({ candidates: ["person:ann"] }); + expect("truncated" in (await g.retrieve("Ann"))).toBe(false); + expect(asked).toEqual([["ann"]]); + expect("truncated" in (await g.findPath("person:ann", "company:acme"))).toBe(false); + expect((await g.neighbors("person:ann")).truncated).toBe(false); + }); + + it("findPath holds when a cut read lets the searches meet early", async () => { + const base = fresh(); + const people = ["ann", "bob", "carl", "dave"]; + await base.insert.facts({ + entities: [{ type: "Company", name: "Acme" }, ...people.map((p) => ({ type: "Person", name: p }))], + relations: people.map((p) => ({ from_entity: `person:${p}`, type: "WORKS_AT", to_entity: "company:acme" })), + }); + const inner = base.store; + const cut = new Proxy(inner, { + get: (target, prop, receiver) => { + if (prop === "matchEdges") { + return async (...args: Parameters) => { + const rows = await inner.matchEdges(...args); + if (!args[1].to_in?.includes("company:acme")) return rows; + markPartial(); + return rows.filter((r) => r.from_id !== "person:bob"); + }; + } + const value = Reflect.get(target, prop, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + const path = await new SelfGraph(cut, { namespace: base.namespace }).findPath("person:ann", "person:bob"); + expect([path.found, path.truncated]).toEqual([true, true]); + expect(path.steps.map((s) => [s.direction, s.entity.id])).toEqual([ + ["out", "company:acme"], + ["in", "person:bob"], + ]); + }); + + it("readiness reports a store that refuses full scans as reachable", async () => { + const base = fresh(); + const inner = base.store; + const noScans = new Proxy(inner, { + get: (target, prop, receiver) => { + if (prop === "matchNodes") { + return async (...args: Parameters) => { + if (!args[2]?.any_of) throw unsupportedRead("list every entity"); + return inner.matchNodes(...args); + }; + } + const value = Reflect.get(target, prop, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + const ready = await new SelfGraph(noScans, { namespace: base.namespace }).readiness(); + expect([ready.ready, ready.reachable, ready.counts]).toEqual([true, true, {}]); + expect(ready.error?.startsWith("the postgres store cannot list every entity")).toBe(true); + }); +} + +await forEachStore("store read hooks", suite);