Skip to main content

cypher-guardrail

Syntax, schema and property-access validation of Cypher queries against a FalkorDB graph.

License Python Documentation

cypher-guardrail checks and validates a Cypher query before it runs, which is useful for queries written by a person or generated by an LLM. It never changes your data, and does not run your query.

💡 Used by text2cypher, which generates validated Cypher queries from natural language text with LLMs

  • Syntax: is the query valid, does it write to the graph, are its $parameters provided, do its variables carry conflicting labels?
  • Schema: do the labels, relationship types, paths (and their direction), full-text or vector indexes and user-defined functions (UDFs) it uses exist in the graph?
  • Properties: does each property it reads exist on the label it is read from? Optionally, is it compared with a value of a type it never has?
  • Performance (optional): a valid query that may be slow, such as a cartesian product, a scan of every node or a path with no upper limit.
  • Advice (optional): what to change in a valid query to make it cheaper, with the query as it could be written.
  • Structured results: every validator returns a score or a verdict plus metadata that says what is wrong, without parsing text.
  • Sync and async, and offline: validate against a saved snapshot of the schema when no database is at hand.

Installation

Python 3.11 or later.

pip install cypher-guardrail

or, with uv:

uv add cypher-guardrail

Supported FalkorDB versions

Tested on FalkorDB 4.18 (FalkorDBLite), 4.22.2 and 6.0.3.

Quickstart

from falkordb import FalkorDB
from cypher_guardrail import (
    Advisor,
    PropertiesValidator,
    SchemaValidator,
    SyntaxValidator,
)

driver = FalkorDB(host="localhost", port=6379)
graph = "my_graph"
query = "MATCH (g:Goal)-[:HAS_TARGET]->(t:Target) WHERE g.code = '1' RETURN t"

# check_performance=True (optional): also warn about a valid query that may be slow
# check_runtime=True (optional): also warn about a valid query that fails when it runs on the data
syntax = SyntaxValidator(driver, check_performance=True, check_runtime=True)
is_valid, syntax_metadata = syntax.validate(query, database_name=graph)
schema_score, schema_metadata = SchemaValidator(driver).validate(
    query, database_name=graph
)
# check_types=True (optional): also report a property compared with a value of the wrong type
properties = PropertiesValidator(driver, check_types=True)
props_score, props_metadata = properties.validate(query, database_name=graph)

kg_valid = is_valid and schema_score == 1 and props_score in (1, None)

# Without a database (optional): the text of a query is a query, its brackets match, it only reads
# from cypher_guardrail import PreflightValidator; PreflightValidator().validate(query)

# Optional: say what to change in a valid query, and show it as it could be written
for suggestion in Advisor(driver).advise(query, database_name=graph):
    print(suggestion["description"], suggestion.get("example"))

⚠️ Always check the syntax first: a syntax error makes the other two results misleading.

How the results are computed

Syntax: is_valid

True if FalkorDB accepts the query, it is read-only (read_only=True is the default), and none of its $parameters is missing. False otherwise.

Schema score

A number from 0 to 1. The query's nodes, relationships and paths are each given a share:

node share         = labels in the query that exist in the graph / labels in the query
relationship share = relationship types that exist / relationship types in the query
path share         = paths that exist, in that direction / paths in the query

schema score = average of the shares that apply
  • Only the kinds the query has take part, and they weigh the same: 1/3 each if it has nodes, relationships and paths, 1/2 each for two kinds, and the share itself for one.

  • A query with none of the three (MATCH (n) RETURN n) scores 1.

  • If the query calls a full-text or vector index procedure (db.idx.fulltext.query..., db.idx.vector.query...):

    index share  = calls whose index exists / index calls
    schema score = (score above + index share) / 2
    

Properties score

properties score = properties that exist on their label / properties the query accesses

It is None when the query accesses no property. Both a property that its label does not have and a property that exists nowhere in the graph count as incorrect. A type-mismatch warning (check_types=True) never changes the score.

KG Valid Query

A query is valid against the graph only if all three checks pass:

KG Valid Query = 1  if SyntaxValidator is_valid is True
                    and schema score = 1
                    and properties score is 1 or None
                 0  otherwise

Documentation

  • Using the validators: connecting, read-only mode, parameters, UNION, UDFs, type checks and performance warnings
  • Advisor: what to change in a valid query to make it cheaper, with the query as it could be written, and what each suggestion can change
  • Reading the metadata: every issue code and its fields
  • Snapshots: offline and hybrid validation, user-defined functions, and keeping a snapshot fresh
  • Async usage: the async twin of each validator and of the advisor, max_concurrency, and cancellation
  • How it is built: the layers and how the sync and async validators share one logic
  • Runnable examples: a quickstart, offline validation with a snapshot, and async validation (no server needed)
  • CHANGELOG

Development

uv sync            # create the environment (Python >= 3.12 also installs FalkorDBLite for the tests)
uv run pytest      # run the tests on a FalkorDB in Docker (falkordb/falkordb:6.0.3), or on FalkorDBLite when Docker is not running
uv run --group docs sphinx-build -W docs docs/_build/html   # build the documentation

The tests choose their FalkorDB with CYPHER_GUARDRAIL_TEST_BACKEND: docker (a container that testcontainers starts and removes; FALKORDB_IMAGE changes the image), server (the one at FALKORDB_HOST and FALKORDB_PORT, which the tests write graphs to), lite (FalkorDBLite) or auto (the default: server if FALKORDB_HOST is set, else docker if it answers, else lite).

.github/workflows/publish.yml publishes a release to PyPI when a version tag is pushed: set version in pyproject.toml, add the release to CHANGELOG.md, then git tag vX.Y.Z && git push origin vX.Y.Z.

Contributions are welcome: please open an issue or a pull request.

License

Apache License 2.0

Metadata

Release files for cypher-guardrail 1.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cypher-guardrail 1.7.0
File Size Uploaded Provenance Actions
cypher_guardrail-1.7.0.tar.gz 125.0 kB Without provenance Details for cypher_guardrail-1.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cypher-guardrail 1.7.0
File Interpreter ABI Platform Actions
cypher_guardrail-1.7.0-py3-none-any.whl Python 3 none any Details for cypher_guardrail-1.7.0-py3-none-any.whl

Total release size: 265.6 kB

Release files / cypher_guardrail-1.7.0.tar.gz

Download URL cypher_guardrail-1.7.0.tar.gz
Size 125.0 kB
Tags Source
SHA-256 checksum
How to use checksums
408ebae7cd32962ca2a13a6bf19f022a691824410fe936f077510128df271f26
BLAKE2b-256 checksum
How to use checksums
a4a5c1e47089c32fe8a8965114b1af72862698f296fa532a372697bf5587f9bf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / cypher_guardrail-1.7.0-py3-none-any.whl

Download URL cypher_guardrail-1.7.0-py3-none-any.whl
Size 140.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d1a751ae3de3702b3b99cd0ecb076e51c79dc8c882fba5f932c13743c3cbbd05
BLAKE2b-256 checksum
How to use checksums
f0625b514059419facfd244099b0dfe16e2c4bceb5f677c7d25b3dbf9cce88b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for cypher-guardrail 1.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page