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
14 changes: 14 additions & 0 deletions docs/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

12 changes: 12 additions & 0 deletions docs/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/retrieval.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 1 addition & 1 deletion docs/trust.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
6 changes: 4 additions & 2 deletions src/selfgraph/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand All @@ -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
Expand Down
46 changes: 46 additions & 0 deletions src/selfgraph/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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."
Expand Down Expand Up @@ -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.

Expand Down
18 changes: 17 additions & 1 deletion src/selfgraph/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1151,17 +1151,20 @@ 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.
"""
data = handler(self)
if self.evidence is None:
data.pop("evidence", None)
if not self.truncated:
data.pop("truncated", None)
return data


Expand Down Expand Up @@ -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):
Expand Down
Loading
Loading