Knowledge-graph contracts for GraphRAG
Dependency-free schema, statements, lexical graph, CSV import, extraction provenance, duplicate resolution, bounded retrieval, topology anchors, and evaluation helpers for graph-backed RAG.
recohut_kit.graphs holds dependency-free knowledge-graph contracts. Integrations are explicit imports elsewhere in the kit. The package root re-exports nothing: you import submodules such as recohut_kit.graphs.schema or recohut_kit.graphs.retrieval directly. Most of the code is plain Python that builds parameterised Cypher statements, validates structured graph data, and scores duplicates or walk reachability without calling a model. Embedding vectors appear as caller-supplied tuples; nothing in this package invokes an embedding or generation provider.
The layer owns typed graph schemas, safe Cypher identifiers, statement records with bound parameters, a lexical document-and-chunk layer, CSV import plans, schema-guided extraction records and write statements, conservative duplicate proposal and merge intent statements, bounded vector and entity expansion and typed path queries, named exploration and validation queries, entity-topology text for anchor retrieval, portable harness summaries and reach sweeps, plus smaller contract modules under recohut_kit.graphs.plans and recohut_kit.graphs.operations. It does not open a database driver, run Neo4j, perform live embedding, execute planned Cypher, or authenticate human resume decisions. Those boundaries live in integration packages that consume these contracts.
Purpose
A graph represents relationships, not just a list of objects. Use this package when you need to preserve which entities are connected and query those relationships explicitly.
GraphRAG needs a stable seam between application configuration (node labels, relationship types, business IDs) and anything that talks to a graph database or a model. This package defines that seam: identifiers are validated before they appear in statement text, while values always travel as parameters. GraphSchema.render returns schema text, and GraphSchema.validate checks extraction-shaped entities and relationships. lexical_statements and friends emit Neo4j 5.26-oriented DDL and MERGE patterns for documents, chunks, and vector indexes. ImportPlan stores the CSV mapping and conversions; read_plan reports bad rows before import_statements builds writes. prime selects known entities to seed extraction under token and candidate budgets. entity_statements turns an ExtractionResponse into a statement batch with provenance. The Neo4j entity store validates the extraction and checks the source chunk. The database adapter executes the generated statements in one transaction. resolution_candidates only marks pairs for review; merging is a separate explicit operation. vector_statement, expansion_statement, entity_expansion_statement, and path_statement encode retrieval policies as statements. topology_texts builds deterministic per-entity text for topology-index anchors when chunks do not share the question’s wording. evaluation summarises repeated harness scores and reports what a bounded in-process walk could reach, without fabricating scores.
What stays outside: managed Neo4j stores and retrievers, structured extraction clients that call a model, exploration runners that execute queries, and LangGraph streaming or resume hosts. The plans subpackage adds constrained query-plan templates, small domain schemas, and incident mapping records; plans.plans classifies Cypher via recohut_kit.graphrag.cypher. The operations subpackage defines fork, replay, stream-mode, and resume verdict records with no runtime import side effects.
Public API
The package root (recohut_kit.graphs) is a marker only. Import from recohut_kit.graphs.<module> using the module shown for each row.
Core graph layer
| Name | Module | Kind | What it does |
|---|---|---|---|
identifier | schema | function | Admits simple Cypher identifiers; rejects executable fragments |
Statement | schema | dataclass | Parameterised statement text plus parameters |
Database | schema | protocol | run and write for adapters |
NodeType, RelationshipType | schema | dataclass | Declared labels, endpoints, and allowed properties |
GraphSchema | schema | class | Renders schema text; validates entities and relationships |
DocumentNode, ChunkNode | lexical | dataclass | Lexical document version and chunk records |
lexical_statements | lexical | function | Constraints and chunk vector index DDL for a schema |
document_statements | lexical | function | MERGE document and chunks with parameterised rows |
sibling_statement | lexical | function | NEXT_CHUNK links between ordered chunks |
similarity_statement | lexical | function | Per-chunk SIMILAR_TO links via vector index |
ImportPlan | imports | dataclass | Node or relationship CSV mapping plan |
ConversionFailure, ImportReceipt | imports | dataclass | Row conversion failure and import result records |
read_plan | imports | function | Reads CSV through a plan; returns rows and failures |
import_statements | imports | function | MERGE structured nodes or relationships from rows |
Entity, Relationship | extraction | dataclass | Extraction entity and relationship records |
ExtractionResponse, ExtractionSchema | extraction | dataclass | Response bundle and schema plus default instructions |
Candidate, PrimingPolicy, Primed | extraction | dataclass | Priming inputs, policy, and result |
normalise, prime | extraction | function | NFKC name normalisation; lexical-then-vector priming |
ExtractionRun, ExtractionReceipt | extraction | dataclass | Run identity via fingerprint; extraction receipt fields |
entity_statements | extraction | function | Builds statements for entities, relationships, and a processed marker |
ResolutionPolicy, ResolutionCandidate | resolution | dataclass | Duplicate scoring policy and proposed pair |
duplicate_score, resolution_candidates | resolution | function | Pair similarity; candidate pairs under budgets |
merge_statement, rewire_statement | resolution | function | Audit merge query; edge rewire pattern for a type |
VectorRetrieval, EntityExpansion, PathRetrieval | retrieval | dataclass | Retrieval policy records with validation |
vector_statement, expansion_statement, entity_expansion_statement, path_statement | retrieval | function | Parameterised retrieval statements |
Retrieval, RetrievalReceipt, Edge, Retriever | retrieval | dataclass / protocol | Retrieval result shape and protocol |
bounded_walk, Walk, WalkedTriple | retrieval | function / dataclass | In-process hop-limited graph walk |
Query, ValidationReceipt | queries | dataclass | Named query with parameters; validation run receipt |
EXPLORATION, VALIDATION | queries | constants | Bundled exploration and validation Query tuples |
TopologyText | topology | dataclass | Per-entity topology summary text |
edge_sentence, topology_texts | topology | function | One fact sentence; capped facts per entity |
topology_index_statement, topology_embedding_statement, topology_anchor_statement | topology | function | Topology vector index, embedding write, anchor query |
TOPOLOGY_INDEX | topology | constant | Name of the entity topology vector index |
ReferenceQuestion, HarnessResult | evaluation | dataclass | Evaluation question spec; one harness trial row |
summarise | evaluation | function | Mean and variance of scores per retriever and question |
ReachObservation, reach_sweep, reach_summary | evaluation | class / function | Walk reachability observations and summary rows |
Query plans
| Name | Module | Kind | What it does |
|---|---|---|---|
canonical_label, SmallSchema, ConsistencyReport | plans.schema | function / class | Label aliasing; compact schema; consistency report |
licensing_schema, incident_schema | plans.schema | function | Packaged small schemas |
Intent, QueryPlan, InvestigationPlan, PlanRefusal, Template, BoundQuery | plans.plans | dataclass | Query-plan records and binding product |
nearest_intents, validate_plan, bind | plans.plans | function | Intent matching; plan validation; template bind |
licensing_templates, investigation_templates, review_extension | plans.plans | function | Template libraries and extension review |
PlainFacts, ValidatedExtraction, validate_extraction, score_extraction | plans.extraction | class / function | Plan-side extraction validation and scoring |
AlertRecord, IncidentExport, map_incidents | plans.incidents | dataclass / function | Incident export mapping to ExtractionResponse |
ApproachDecision, score_decisions, FitCheck, CypherLanguageMatrix, CypherSqlMapping | plans.decision | dataclass / function | score_decisions scores approach decisions, and the other four names are dataclasses |
CheckpointState, inspect, PitfallItem, PitfallChecklist | plans.checkpoints | class / function | Checkpoint inspection contracts |
StoreDescription, GraphStore | plans.store | dataclass / protocol | Store description and graph store protocol |
Runtime operation contracts
| Name | Module | Kind | What it does |
|---|---|---|---|
ForkRecord, ReplayRecord, ForkComparison, compare_forks | operations.lineage | dataclass / function | Fork and replay comparison records |
InterruptRequest, Approve, Reject, ApproveWithModification, validate | operations.resume | dataclass / function | Typed resume decisions and validation |
StreamMode, StreamModeCatalogue, StreamReceipt, FrameReceipt | operations.streams | dataclass | Stream mode catalogue and receipts |
How it composes
Within the kit, composition is narrow and explicit. schema imports JsonValue, imports imports as_json_value, and extraction imports JsonValue and fingerprint; lexical, resolution, and topology do not import recohut_kit.json. Internal edges use relative imports between graphs modules (lexical → schema, resolution → extraction and schema, topology → extraction, retrieval, schema, and so on). recohut_kit.graphs.plans.schema and recohut_kit.graphs.plans.extraction build on graphs.extraction and graphs.schema. recohut_kit.graphs.plans.plans additionally imports recohut_kit.graphrag.cypher.classify_cypher. recohut_kit.graphs.operations.lineage and recohut_kit.graphs.operations.resume use recohut_kit.json; operations.streams imports nothing else from the kit.
Module docstrings name downstream consumers (for example Neo4j GraphRAG stores, retrieval, exploration, evaluation, LangGraph operations, and other graph modules). Those integrations import these contracts; this package does not import them back. The root docstring says it uses nothing else in the kit and is not imported by other kit modules.
Minimal usage example
The tests build a small GraphSchema, reject unsafe identifiers, and validate a well-typed extraction payload before any driver runs. That pattern shows how configuration becomes checkable structure.
from recohut_kit.graphs.extraction import Entity, Relationship
from recohut_kit.graphs.schema import GraphSchema, NodeType, RelationshipType, identifier
schema = GraphSchema(
(NodeType("Person"), NodeType("Project"), NodeType("Technology")),
(
RelationshipType("WORKED_ON", "Person", "Project"),
RelationshipType("USES", "Project", "Technology"),
),
)
assert "Person -WORKED_ON-> Project" in schema.render()
identifier("Person") # raises ValueError on strings like "Person) DELETE n"
schema.validate(
(
Entity("EMP012", "Person", "Maren Kestrel", ("Marren Kestrel",)),
Entity("PRJ009", "Project", "Intake"),
),
(Relationship("EMP012", "PRJ009", "WORKED_ON"),),
)This shows declared node and relationship types, a valid identifier, and a passing GraphSchema.validate call on a well-typed extraction.
Limits and gotchas
- Parameters, not interpolation. Document and chunk IDs, merge endpoints, and import rows must pass as statement parameters. Tests assert attacker-shaped IDs do not appear raw in Cypher text.
- Identifier gate. Only simple
[A-Za-z_][A-Za-z0-9_]*names are admitted for labels, types, and plan columns wired into statements. - Schema fail-fast. Unknown labels, undeclared properties, reversed relationship endpoints, and duplicate entity IDs raise
ValueErroronGraphSchema.validate. - Chunk embeddings. Chunks require nonempty text, finite embeddings, and a nonzero vector;
ChunkNoderejects all-zero vectors. - Import plans. Exactly one of
labelorrelationshipmust be set; relationship CSV plans requiresource_labelandtarget_label. - Priming budgets.
primeprefers lexical matches over vector neighbours, deduplicates by entity id, and truncates whenmax_candidatesormax_tokens(counted with yourcount_tokenscallable, including separators) is exceeded. Unmatched lexical entities are excluded when only lexical evidence would apply. - Extraction provenance.
entity_statementsrequires every relationship endpoint to appear in the response entities.ExtractionRun.identityfingerprints prompt version, model name, and schema digest, and does not include the run id. - Resolution is conservative.
resolution_candidatesreturns scored id pairs withreviewtrue; it does not merge those pairs.merge_statementreturns an audit read of keep and drop properties and labels; a native writer performs the merge. Shared surnames alone cap similarity forPerson. Optionaldigit_guardprevents matching names whose digit runs differ. Large entity sets must respectmax_pairs. - Retrieval bounds.
EntityExpansionrequires an explicit positive weight per allowed relationship type. Path patterns must chain connected hops (at most four). Walk simulation caps hops and triple counts; order of input relationships does not changebounded_walkresults. - Topology text. Facts per entity are sorted and capped; excess facts set
truncatedonTopologyText. Embedding the text is the caller’s job. - Evaluation records.
ReferenceQuestionrequires either a reference string or a ground-truthQuery.HarnessResultscores must lie in[0, 5].reach_sweepreports reachability only, not answer quality. - No root re-exports. Import the submodule you need; do not expect names on
recohut_kit.graphsitself.
Verification
The example checks schema rendering and validates extraction records against the declared types. See Verify the examples.
How is this page?
Last updated on