Skip to main content

Crate purrdf

Crate purrdf 

Source
Expand description

Umbrella Rust API for PurRDF.

This crate is the user-facing facade and the single dependency a downstream needs: it re-exports the RDF 1.2 implementation surface from purrdf_rdf at the root, and carries every other published crate under a stable module, so anything a consumer legitimately imports is reachable from purrdf alone — never by reaching into a sub-crate.

ModuleSub-crate(s)
(root)purrdf_rdf — core types, codecs, GTS/text adapters
gtspurrdf_gts (container engine) + the purrdf_rdf GTS adapter
sparqlpurrdf_sparql_eval + purrdf_sparql_algebra + purrdf_sparql_results
shapespurrdf_shapes (SHACL)
shexpurrdf_shex (ShEx 2.1)
entailpurrdf_entail (RDFS / OWL-RL / OWL-Direct / RIF entailment)
validatepurrdf_validate (SARIF 2.1.0 reporting boundary)
slicepurrdf_slice
vizpurrdf_rdf::viz
xsdpurrdf_xsd
iripurrdf_iri
eventspurrdf_events

Consumer-config types are surfaced at the root (SliceVocab, Namespaces, StatementMetadataVocab) and unified behind a single OntologyProfile a downstream builds once (see profile).

§Example

Every step below goes through the purrdf facade alone — a downstream never reaches into a sub-crate:

use purrdf::prelude::*;

// Parse RDF 1.2 Turtle into a frozen dataset through the umbrella facade.
let turtle = r#"
    @prefix ex: <https://example.org/> .
    ex:cat ex:says "meow" .
"#;
let dataset = purrdf::parse_dataset(turtle.as_bytes(), "text/turtle", None)
    .expect("valid Turtle");
let view: &RdfDataset = &dataset;
assert_eq!(view.quad_count(), 1);

// The zero-dependency IRI leaf is reachable under a stable module.
let iri = purrdf::iri::parse("https://example.org/cat").expect("valid IRI");
assert_eq!(iri.as_str(), "https://example.org/cat");

// Parse a ShEx 2.1 schema and name a SPARQL results serialization — both
// from the same facade.
let schema = purrdf::shex::parse_shexc(
    "PREFIX ex: <https://example.org/>\nex:Cat { ex:says . }",
    None,
)
.expect("valid ShExC");
assert!(!format!("{:?}", purrdf::sparql::SparqlResultsFormat::Json).is_empty());
let _ = schema;

Re-exports§

pub use profile::OntologyProfile;
pub use profile::ReifierVocab;
pub use reasoning::QueryEntailment;
pub use reasoning::ReasoningError;
pub use reasoning::query_with_entailment;

Modules§

backend
Narrow purrdf backend traits (P2d).
bundle
The self-describing bundle resource layer (S3).
capture_support
Shared corpus-classification helpers for the native golden-capture binary ( Task 2/8).
content_store
Content-addressed blob store for the self-describing bundle (S3).
dataset_io
RDF text/bytes ingress into the frozen RdfDataset IR.
dataset_view
The static, allocation-free read view over an RDF dataset (purrdf P2, ). See docs/design/purrdf-backend-contract.md.
describe
Per-subject subgraph extraction — the Symmetric Concise Bounded Description (SCBD) of a resource.
diagnostic
Structured diagnostics: severity, source/GTS locations, conversion losses, and the RdfDiagnostic record callers translate to their reporting layer.
entail
Native, wasm-clean entailment (purrdf_entail): RDFS / OWL-RL forward materialization plus the OWL-Direct and RIF entry points, over the frozen IR.
events
The zero-dependency streaming RDF event model.
fno
Native FnO (W3C Function Ontology) typed model + serializer.
gts
GTS: the container engine (purrdf_gts) plus the RDF-level GTS adapter from purrdf_rdf (read_graph, flattened_dataset_from_bytes, …).
gts_certify
GTS streamable-compaction certificates (GTS-SPEC §10.1/§10.2, Task 5).
gts_compose
The pyo3-free GTS snapshot compose core (P6).
gts_view
Rust-owned read-side view over a folded GTS graph.
gts_write
Write a frozen RdfDataset into a deterministic GTS byte stream.
ir
The immutable, value-interned RDF 1.2 dataset IR (C1).
iri
IRI parsing, resolution, and CURIE expansion/contraction.
lookaside
Structured non-triple material (RdfLookaside) that travels with an RDF store: typed sidecar resources, metadata entries, segment/blob records, suppressions, opaque nodes, and signature records.
loss
The machine-readable RDF↔GTS loss ledger (C0).
model
The owned RDF 1.2 value model: terms, literals (including base-direction literals), triples, quads, reifiers, and statement annotations.
native_codecs
Native RDF text codecs (S3).
native_quads
Native RdfQuadRdfDataset conversions.
prelude
The common umbrella surface, for use purrdf::prelude::*;.
profile
One consumer-config shape for every namespace-bound emitter.
provenance
Generic provenance sidecar for the immutable RDF 1.2 dataset (S2).
reasoning
Entailment-aware SPARQL orchestration over the native PurRDF engines.
shapes
SHACL shape support.
shex
ShEx 2.1 schema parsing, serialization, and validation.
slice
Native slice catalog and dataset-wrapper support.
sparql
SPARQL 1.1/1.2: parser + algebra (purrdf_sparql_algebra), evaluator (purrdf_sparql_eval), and results serialization (purrdf_sparql_results).
sssom
Native SSSOM (Simple Standard for Sharing Ontology Mappings) codec.
statements
Native OWL axiom-annotation ↔ RDF 1.2 statement codec — the lead writer.
store
Dataset/import capability flags (RdfStoreCapabilities).
turtle
Native RDF 1.2 Turtle emitter for crate::store stores.
turtle_normalize
A canonical, review-friendly Turtle serializer over the purrdf IR.
turtle_render
The canonical, review-friendly Turtle renderer over the purrdf IR — the oxigraph-free half of the on-disk normalizer.
ustar
Shared USTAR (tar) codec — byte-deterministic writer + reader.
validate
The SARIF 2.1.0 reporting boundary (purrdf_validate): validate a shapes+data pair to a source-traced, byte-deterministic SARIF log.
viz
Statement-centric RDF 1.2 visualization projection and SVG export support.
xsd
XSD datatype value spaces and operations.

Macros§

smallvec
Creates a SmallVec containing the arguments.

Structs§

ArtifactId
Opaque id for a packaged artifact within a unit (module file, shapes file, mapping, query, …). Runtime-only (S0.5).
ArtifactIndex
Index of ArtifactRecords with lookup by ArtifactId, by logical path, and by UnitId.
ArtifactInterner
Interner for ArtifactIds — maps a logical artifact path to a dense numeric id. The path is a string the caller controls (e.g. a repo-relative file path or a content-addressed digest); the kernel does not interpret it.
ArtifactRecord
One packaged artifact: a content-addressed reference into the ContentStore, with no inline payload bytes.
AssertionOccurrence
One physical assertion: the pair (unit, artifact) that asserted the quad identified by quad (a QuadHandle into the associated RdfDataset).
Attribution
A structured attribution: which compilation unit played which role in producing a finding, derivation, or SHACL result (S0.3 / §9).
BlankScope
Blank-node scope. Participates in the interning key (C0.2): two blank nodes from different scopes are distinct even with the same label; two blank nodes in the same scope with the same label are the same node. 0 = default/global scope; > 0 = a per-segment scope assigned by the streaming importer.
BudgetExceeded
The n-degree search’s call/permutation budget (RDFC_CALL_LIMIT) was exhausted before the dataset canonicalized — a pathologically symmetric blank graph (adversarial input, not a legitimate large dataset: a non-symmetric graph of any size stays well under budget). Returned by try_canonicalize/try_canonicalize_with instead of the panic that canonicalize/canonicalize_with raise for trusted callers.
Canonicalized
The result of canonicalizing a dataset.
ContentDigest
A content id: the SHA-256 digest of a blob’s bytes.
ContentStore
A content-addressed blob store: bytes keyed by their SHA-256 ContentDigest.
DatasetDiff
A structural diff between two datasets, for test diagnostics. Counts only; the blank-aware verdict is datasets_isomorphic.
DatasetProvenance
The provenance sidecar for one RdfDataset.
DatasetSink
An RdfEventSink that folds a permissive ingestion event stream into a frozen RdfDataset, tolerant of forward references (two-phase; see the module docs).
FnFunction
One fno:Function node (always typed fno:Function; any additional rdf:type IRIs — e.g. the consumer’s projection-function class for the projection catalog — come from FnFunction::kind_types).
FnImpl
One fno:Implementation node (one per profile .rq).
FnMapping
One fno:Mapping node linking a function to one profile’s implementation.
FnOutput
The fno:Output node of a function.
FnParam
One globally-deduped fno:Parameter node.
FnParamMapping
One fnom:PropertyParameterMapping (a parameter ↦ a SPARQL variable).
FnReturnMapping
One fnom:DefaultReturnMapping (the function output ↦ a SPARQL variable).
FnoCatalog
The fully-resolved FnO catalog the purrdf-slice emitter assembles and serializes here.
FrozenDatasetSource
An RdfEventSource that replays an already-frozen RdfDataset into any RdfEventSink: a term event per term in TermId order (declares-before- reference), then quad / reifier / annotation events.
GtsBundle
The frozen RDF 1.2 hot graph plus its out-of-band envelope.
GtsCodecBackend
The native codec backend: a codec-only RdfParserBackend + RdfSerializer over the purrdf-gts text codecs. Holds no state and references no oxigraph Store.
HandleEntry
A typed handle: a pipeline-side payload H paired with the PINNED ContentDigest of the named graph it projects.
LossEntry
One enumerated, intentional conversion loss between two representations.
LossLedger
An ordered, deterministic set of LossEntry for one conversion direction (or the combined matrix).
MutableDataset
A copy-on-write mutable RDF dataset (purrdf P5). Branches cheaply off a shared frozen base; records mutations as an append delta + a suppression set; and compacts back to a frozen RdfDataset via freeze.
Namespaces
The caller-supplied namespace table driving ALL IRI compaction, $defs keying, and @type discrimination — for BOTH the schema emitter (compile) and the instance projector (crate::instance).
OriginSetId
Opaque id for an interned set of origins. Two quads with the same set of (UnitId, ArtifactId) pairs share an OriginSetId. Runtime-only (S0.5).
OriginSetInterner
Interner for OriginSetIds — maps a canonical sorted set of (UnitId, ArtifactId) pairs to a dense numeric id.
ParseOptions
Runtime options for parse_dataset_with.
PipelineBundle
The pipeline carrier: the frozen hot graph plus its out-of-band material and a typed-handle lane.
QuadHandle
A handle identifying a pushed quad by its dense (deduplicated) ordinal, used to attach a source location sparsely. Like TermId, it is local to one frozen dataset and is not persistent or merge-stable.
QuadIds
A small Copy quad row in term ids, for ID-native consumers. g == None is the default graph.
QuadPatternCursor
An owned, row-materialization-free cursor over one indexed quad pattern.
QuadRef
A borrowed, resolved quad view: each position is a TermRef borrowing into the dataset’s term table. No allocation, no clone per quad.
QuadValues
An owned, dataset-independent quad value — the argument type of DatasetMut::insert/remove/contains.
RdfAnnotation
RDF 1.2 statement annotation.
RdfBlobOrigin
Where a blob’s payload bytes can be fetched from.
RdfBlobRecord
A content-addressed reference to a blob that travels with an RDF store.
RdfBundle
The self-describing, repo-free bundle: dataset + provenance + unit catalog + artifact index + the actual blob bytes.
RdfDataset
The immutable, frozen RDF 1.2 dataset. Constructed only via RdfDatasetBuilder::freeze.
RdfDatasetBuilder
The fallible builder that interns terms, accumulates structure, and freezes into an immutable Arc<RdfDataset>.
RdfDiagnostic
Structured RDF diagnostic. Callers translate this to their reporting layer.
RdfEnvelope
Out-of-band material that travels with an RdfDataset but is not part of the hot graph (C0.6).
RdfLiteral
An RDF literal, including RDF 1.2 language direction when available.
RdfLocation
Concrete or logical location attached to an RDF diagnostic.
RdfLookaside
Structured non-triple material that travels with an RDF store.
RdfLookasideResource
A typed sidecar resource such as SHACL, ShEx, docs, logic, schemas, or queries.
RdfLoss
A conversion loss recorded by an RDF adapter.
RdfMetadataEntry
A scoped key/value metadata entry carried alongside the triples.
RdfOpaqueNodeRecord
A frame preserved as an opaque node: its content was not decoded, only its identity and public envelope survive.
RdfParseRequest
RDF parser request. Formats are named by media type or local format id at the contract boundary so the core trait does not leak an oxigraph enum.
RdfQuad
Owned RDF 1.2 quad with optional adapter/source context.
RdfReifier
RDF 1.2 reifier binding.
RdfSegmentRecord
Per-segment facts recorded from the source GTS file.
RdfSerializeRequest
RDF serializer request. Formats are media types/local ids for the same reason as RdfParseRequest: the core trait must not expose an oxigraph enum.
RdfSignatureRecord
A frame signature record.
RdfStoreCapabilities
Capability flags exposed by an RDF dataset/import boundary.
RdfSuppressionRecord
A suppress directive (GTS §11) carried through verbatim; decode its targets with RdfLookaside::suppression_targets.
RdfTriple
Owned RDF 1.2 triple. The model keeps triple-term subjects representable; downstream adapters decide whether a target store can encode them.
SegmentUnitMap
A set-valued mapping between GTS segments and compilation units (S0.7).
SerializeOutcome
Outcome of serializing an RdfDataset to a concrete RDF format through the native codecs (universal transcoder helper, ported onto the native path).
SliceVocab
The caller’s slice-framework vocabulary: a namespace all term IRIs are derived from by concatenation ({ns}{localName}), plus the CURIE prefix name used when emitting prefixed names.
SmallVec
A Vec-like container that can store a small number of elements inline.
SpanTable
Opt-in mapping from a data-graph subject to the source Position where it was first asserted, plus the ordered list of every recorded (subject, position).
SparqlRequest
SPARQL operation request.
SssomDiagnostic
A single validation diagnostic, mirroring the sssom-py golden record shape {severity, type, message, instance, check}. code carries the golden’s type string; check carries the originating check name.
SssomMapping
A single SSSOM mapping (one TSV data row).
SssomMappingSet
A parsed SSSOM mapping set: header metadata + its mappings.
SssomMeta
The SSSOM metadata header.
StatementMetadataVocab
The CALLER-SUPPLIED statement-metadata reification vocabulary the JSON-LD-star downcast emits.
TermId
Opaque term identity, LOCAL to one frozen RdfDataset. Deliberately NOT Serialize/Deserialize, not merge-stable, not meaningful across datasets (C0.8). Any consumer needing a durable identifier MUST resolve the term to its RDF value rather than retaining a TermId.
UnitCatalog
Maps each UnitId to its UnitMetadata.
UnitId
Opaque id for a compilation/source unit (file set, import, generated graph, or runtime data input). Runtime-only: MUST NOT enter persistent serialization, cache keys, or derivation hashes (S0.5).
UnitInterner
Interner for UnitIds — maps a logical unit name to a dense numeric id.
UnitMetadata
Metadata describing one compilation unit (the kernel-generic projection of a slice / root ontology / import / generated graph / runtime input).

Enums§

AttributionRole
The role of a compilation unit in a structured attribution (S0.3 / §9).
BundleError
A hard error from RdfBundle::load. The loader never silently repairs; every malformed structure is a typed Err.
CanonHash
The RDFC-1.0 hash algorithm. SHA-256 is the default; SHA-384 is the spec’s alternative (RDFC-1.0 §3, exercised by W3C suite test075). EXTEND beyond oxrdf, which only offered SHA-256.
ContentStoreError
An error raised while validating or accessing a content-addressed blob.
GraphMatch
How a pattern query matches the graph slot of a quad.
GraphMatchValue
How a write-side pattern query matches the graph slot of a quad — the value-based twin of GraphMatch.
NativeRdfFormat
The RDF text serializations the native codec backend parses and serializes via the purrdf-gts codecs. This is the codec-selector enum that replaces oxigraph::io::RdfFormat’s use as a router across the workspace.
OriginKind
The kind of a compilation unit. Generic — no SliceId here; the purrdf-slice layer interprets Slice-kind units by wrapping UnitId.
PipelineBundleError
An error from attaching a typed handle to a PipelineBundle.
ProvenanceError
An error from the provenance gate.
RdfListError
A malformed RDF Collection encountered while walking rdf:first/rdf:rest.
RdfLookasideKind
Known companion/index kinds. Unknown domains remain representable.
RdfMetadataValue
A structured metadata value mirroring the CBOR data model, so GTS metadata round-trips without loss.
RdfSeverity
Severity for RDF ingestion, conversion, and adapter diagnostics.
RdfTerm
Owned RDF 1.2 term.
RdfTermKind
RDF term category.
RdfTextDirection
RDF 1.2 base direction for directional language-tagged literals.
SerializeGraph
Which graph(s) a serializer should emit.
SparqlResult
Materialized SPARQL result model independent of any concrete query engine.
TermRef
A borrowed, resolved view of a term — mirrors InternedTerm but exposes &str slices borrowed from the dataset, so resolving a term performs no allocation and no clone. Triple components are returned as ids; resolve them recursively with RdfDataset::resolve if their values are needed.
TermValue
A dataset-independent term value — the lookup key for RdfDataset::term_id_by_value (purrdf P4).

Constants§

PROJECTION_CODECS
Projection codecs: lossy targets that select a semantic subset of the source graph (decidable fragments, rule languages, foundational profiles).
SSSOM_DEFAULT_VALIDATION_TYPES
The default check set sssom-py runs (validation_types=None), captured from sssom.validators.DEFAULT_VALIDATION_TYPES into the frozen golden. The native validator implements the two reachable-through-parse checks of this set (PrefixMapCompleteness, JsonSchema); StrictCurieFormat is unreachable because PurRDF never emits a pipe-bearing entity slot. Exposed so a consumer can report the parity surface it covers.

Traits§

DatasetMut
The write companion to DatasetView — the mutation surface a copy-on-write or backed-by-store dataset exposes (purrdf P5; backend contract C4).
DatasetView
A static, allocation-free read view over an RDF dataset (purrdf backend contract, C2/C3/C6). All methods are infallible for a frozen, validated dataset.
RdfDatasetVisitor
A receiver for the evented, ID-addressed output of a frozen RdfDataset.
RdfParserBackend
Parser ingress seam: drive RDF bytes into any event sink.
RdfSerializer
Serializer egress seam over the frozen IR.
SparqlEngine
SPARQL query/update seam. The dataset type is associated so an oxigraph-backed engine can operate on its store while a future native engine can operate on the IR/native query store.
TermFactory
Term interning seam: dataset-independent values enter a concrete term table.

Functions§

canonical_flat_nquads
The RDFC-1.0 canonical N-Quads document of dataset, flattened: the RDF 1.2 statement overlay (reifier bindings + annotations) is re-materialized to plain rdf:reifies / annotation triples BEFORE canonicalizing, with no overlay re-fold.
canonical_flat_nquads_with
canonical_flat_nquads with an explicit RDFC-1.0 hash algorithm (CanonHash::Sha384 selects the SHA-384 variant). Used by the W3C RDFC-1.0 conformance gate, whose test075 vector pins SHA-384.
canonicalize
Canonicalize ds under full W3C RDFC-1.0 (SHA-256, extended for the RDF-1.2 overlay).
canonicalize_with
Canonicalize ds under full W3C RDFC-1.0 with an explicit hash algorithm (CanonHash::Sha384 is the spec’s SHA-384 variant). See canonicalize.
check_provenance
Validate the provenance sidecar against a set of expected quad handles.
classify
Resolve a media type or local format id to a NativeRdfFormat.
dataset_diff
A richer diff for test diagnostics: structural counts plus the isomorphism verdict.
dataset_from_bytes
Parse RDF bytes and freeze them into a validated RdfDataset via the native codec path.
dataset_from_quad_sources
Freeze several independently-parsed native RdfQuad streams into ONE validated RdfDataset, folding the RDF 1.2 statement layer, with blank nodes standardized apart per source.
dataset_from_quads
Freeze already-built native RdfQuads into a validated RdfDataset, folding the RDF 1.2 statement layer.
datasets_isomorphic
IR-direct structural comparison. Returns true iff the two datasets are RDF-structurally isomorphic: the same quads (under a blank-node bijection), the same reifier bindings, and the same annotations. Oxigraph is NEVER consulted.
describe
One-shot convenience: the SCBD of a single IRI subject in dataset.
emit_annotation
Emit a standalone annotation triple <reifier> <predicate> <object> ..
emit_quad
Emit a single quad as a Turtle statement line (<s> <p> <o> .).
emit_reifier
Emit a reifier binding as <reifier> rdf:reifies <<( s p o )>> ; <pred> <obj> ; … .
emit_resource
Emit a free-standing resource: <subject> a <type> ; <pred> <obj> ; … .
emit_term
Serialize an RdfTerm to its Turtle form (full <iri>, _:bnode, literal, or the RDF 1.2 non-asserting triple term <<( <s> <p> <o> )>>).
flat_dataset_from_quad_sources
Freeze several independently-parsed flat owned-RdfQuad streams into ONE dataset WITHOUT folding the RDF 1.2 statement layer (every quad — including a rdf:reifies triple-term row — stays a plain quad), with blank nodes standardized apart per source.
flat_dataset_from_quads
Freeze a flat owned-RdfQuad stream into a dataset WITHOUT folding the RDF 1.2 statement layer (every quad — including a rdf:reifies triple-term row — stays a plain quad).
flat_rdf_quads_from_dataset
Flatten a frozen RdfDataset into the source-faithful flat RdfQuad stream, for consumers that fold over RdfQuad. Base quads first, then the re-materialized rdf:reifies reifier rows and the annotation rows. The IR fold + this un-fold are exact inverses.
fno_to_ntriples
Serialize a FnoCatalog’s typed model to N-Triples text (the rdflib-parseable form the Python side re-parses).
fno_to_quads
Build the typed model’s quads in the EXACT shape emit_fno / _emit_fnom produced — the same triple set, datatypes, and language tags.
gts_to_rdf_loss_ledger
The intentional losses incurred reading GTS → the RDF 1.2 dataset IR.
import_gts_events
The authoritative GTS ingestion path: folds GTS bytes into a GtsBundle, preserving per-segment blank-node scope (C2.a).
import_gts_graph
Consume a folded GTS Graph by value, MOVING owned term strings into the interner, and return the frozen GtsBundle.
loss_matrix_json
The combined RDF↔GTS matrix as a single deterministic, sorted-by-code JSON array — the body of the generated generated/rdf-loss-matrix.json artifact.
pair_loss_ledger
Compute the static loss contract for a from → to transcoding pair.
parse_dataset
Parse RDF text bytes of media_type into a frozen RdfDataset.
parse_dataset_with
parse_dataset with a runtime option to also return a source-position side table.
rdf_to_gts_loss_ledger
The intentional losses incurred projecting the RDF 1.2 dataset IR → GTS.
rule_iri
Mint the namespaced, percent-encoded rule IRI for a rule label.
serialize_dataset
Serialize a frozen RdfDataset to RDF text of media_type, honoring the SerializeGraph selection. Returns the serialized bytes.
serialize_dataset_base_only
Serialize a frozen RdfDataset to RDF text of media_type, emitting ONLY the base quads and DROPPING the RDF 1.2 statement layer (reifier bindings + annotations).
serialize_dataset_to_format
Serialize the frozen IR to a concrete NativeRdfFormat, returning the bytes and the count of RDF-1.2 statement-layer rows dropped because the target format does not carry the star layer (the projection doctrine).
transcode_loss_matrix_json
The full transcode loss matrix as deterministic JSON.
try_canonicalize
Canonicalize ds under full W3C RDFC-1.0 (SHA-256), returning Err(BudgetExceeded) instead of panicking when the n-degree search exceeds RDFC_CALL_LIMIT.
try_canonicalize_with
Fallible, explicit-hash-algorithm form of try_canonicalize. See canonicalize_with for the panicking (trusted-caller) equivalent.

Type Aliases§

Bytes
Owned blob payload bytes. A thin alias so the by-reference doctrine reads clearly at call sites: only the kernel’s ContentStore ever owns a Bytes; everything else holds a ContentDigest.
FastHasher
The workspace fixed-key ahash hasher builder. Non-cryptographic, no runtime RNG seeding — see the module docs for the determinism policy.
FastMap
A std::collections::HashMap keyed by the workspace FastHasher.
FastSet
A std::collections::HashSet hashed by the workspace FastHasher.
HandleKey
The key identifying the named graph a typed handle backs. An IRI string is the stable, dataset-independent name of the graph the handle projects.
IdSet
A FastSet of interned TermIds — the common id-membership set.
IdVec
A small-vector of interned TermIds, inline up to 4 ids.