Runnable API Workflows

These examples live in the library docstrings: use Python help() in an installed environment or read them here. Each example includes its imports and input construction; persistence examples use disposable directories and close their handles. They are executed by tests/test_public_workflow_docstrings.py in fresh namespaces, with real backends when the declared extras are installed.

Start with the Components, Interfaces, and Applications component map to select an application path. The API Reference page contains runnable class/method examples for GraphDB, Arrow ingestion, historical read views, stored-rule maintenance, all three KV backends, JSON serialization, SamplerSnapshot / SamplerEngine, and SVG visualization. Install the indicated backend/Arrow extra before running those examples (Installation).

The workflows below need no database except the explicitly marked adapters. They illustrate the difference between an in-memory result, saved reasoning state, and claims deliberately published to storage.

New to logical reasoning? Read Facts, Rules, and Explanations first: it defines facts, rules, closure and witnesses before the first executable example. Concepts and Terminology provides short definitions and optional background links.

Compile an ontology and evaluate facts

Use this for rule-based classification from a shared semantic model. Supported constructs and axiom origins are described in Ontology reasoning.

gestaltdb.ontology.compiler.compile_ontology(ontology)[source]

Compile semantic axioms into a program with exact axiom origins.

Examples

Classify an employee and retain a bounded witness for the conclusion:

 1>>> from gestaltdb.ontology import Ontology, SubClassOf, compile_ontology
 2>>> from gestaltdb.reasoning.engine import DatalogEngine
 3>>> from gestaltdb.reasoning.model import Fact, ReasoningLimits
 4>>> from gestaltdb.ontology.model import TYPE_PREDICATE
 5>>> compiled = compile_ontology(Ontology("people", [SubClassOf("Employee", "Person")]))
 6>>> result = DatalogEngine().evaluate(compiled.program,
 7...     [Fact("alice", TYPE_PREDICATE, "Employee")],
 8...     limits=ReasoningLimits(), collect_proofs=True)
 9>>> conclusion = Fact("alice", TYPE_PREDICATE, "Person")
10>>> assert conclusion in result
11>>> assert not result.explain(conclusion).truncated

Compilation needs no database and does not evaluate facts or modify a rule catalog. compiled.origins connects rules to source axioms; the ontology guide documents the selected fragment and explicit graph/claim adapters.

Parameters:

ontology (Ontology)

Return type:

CompiledOntology

Binary and typed inference

The binary engine can collect bounded witnesses. The typed engine adds n-ary relations and strict literal filters. See Typed Datalog: literals, filters, aggregates and Scoped closed-world negation for aggregation and closed-world absence semantics. Packaged retrieval mirrors these paths without a database: datalog for standalone rules, temporal_reasoning for validity-interval closure.

class gestaltdb.reasoning.engine.DatalogEngine[source]

Stateless, deterministic positive-Datalog evaluator.

A closure is the input facts together with their rule-derived consequences. A witness is one recorded derivation: the rule and concrete premises that explain a conclusion. It is not every independent support or a certificate that the supplied assertions are true. See the documentation’s facts/rules introduction and glossary for examples and terminology.

Only complete closures are returned. Limits apply to each invocation; failure does not poison later runs. Proof collection is opt-in and bounded independently: truncating a witness trace never truncates logical closure.

Examples

Infer a relationship from a positive rule, without a database:

1>>> from gestaltdb.reasoning.engine import DatalogEngine
2>>> from gestaltdb.reasoning.model import Atom, Fact, Program, Rule, Variable, ReasoningLimits
3>>> x, y = Variable("x"), Variable("y")
4>>> program = Program([Rule("parent-is-ancestor", [Atom(x, "parent", y)], Atom(x, "ancestor", y))])
5>>> result = DatalogEngine().evaluate(program, [Fact("alice", "parent", "bob")],
6...     limits=ReasoningLimits(), collect_proofs=True)
7>>> conclusion = Fact("alice", "ancestor", "bob")
8>>> assert conclusion in result
9>>> assert not result.explain(conclusion).truncated

For n-ary relations, strict literals, and filters use GenericEngine.

class gestaltdb.reasoning.typed.GenericEngine[source]

Stateless positive typed-Datalog evaluator with filter pruning.

Each synchronous round joins at least one delta relation. Filters are checked incrementally as their variables bind, pruning before deeper traversal. Only complete closures are returned; limits and cancellation behave like the binary engine. Proof collection is opt-in and bounded: truncating a witness trace never truncates the logical closure.

Examples

Classify adults using kind-strict literal comparisons:

1>>> from gestaltdb.reasoning.model import ReasoningLimits, Variable
2>>> from gestaltdb.reasoning.terms import Literal
3>>> from gestaltdb.reasoning.typed import Comparison, GenericEngine, GenericProgram, GenericRule, TypedAtom, TypedFact
4>>> x, age = Variable("x"), Variable("age")
5>>> rule = GenericRule("adult", [TypedAtom("age", [x, age])],
6...     [Comparison(">=", age, Literal("integer", 18))], TypedAtom("adult", [x]))
7>>> facts = [TypedFact("age", ["alice", Literal("integer", 30)])]
8>>> result = GenericEngine().evaluate(GenericProgram([rule]), facts, limits=ReasoningLimits())
9>>> assert TypedFact("adult", ["alice"]) in result.facts

Use evaluate_stratified for declared closed-world absence. Aggregates have a separate single-pass stratum; see the typed-reasoning guide for its constructor restrictions and the distinction from positive maintenance.

evaluate_stratified(program, facts, *, limits, collect_negation_trace=False, collect_proofs=False, cancel=None)[source]

Fixpoint per positive component in stratum order, then aggregates.

Negated atoms anti-join against completed lower strata only; the trace records the first present blocker per failed binding when requested, bounded by max_proof_nodes. iterations counts executed component rounds; the aggregate stratum adds one round when aggregates exist, matching evaluate accounting on positive programs. Successful derivations record absence checks naming the closed scope when collect_proofs is set; proof truncation never truncates the closure.

Examples

Select unblocked candidates in an explicitly closed predicate:

 1>>> from gestaltdb.reasoning.model import ReasoningLimits, Variable
 2>>> from gestaltdb.reasoning.typed import GenericEngine, GenericProgram, GenericRule, TypedAtom, TypedFact
 3>>> x = Variable("x")
 4>>> rule = GenericRule("free", [TypedAtom("candidate", [x])], [],
 5...     TypedAtom("free", [x]), negated=[TypedAtom("blocked", [x])])
 6>>> program = GenericProgram([rule], closed=["blocked"])
 7>>> facts = [TypedFact("candidate", ["a"]), TypedFact("candidate", ["b"]), TypedFact("blocked", ["b"])]
 8>>> run = GenericEngine().evaluate_stratified(program, facts, limits=ReasoningLimits())
 9>>> assert TypedFact("free", ["a"]) in run.result.facts
10>>> assert TypedFact("free", ["b"]) not in run.result.facts

Here blocked is an absence check, not an explicit negative assertion.

Parameters:
  • program (GenericProgram)

  • facts (Iterable[TypedFact | Evidence])

  • limits (ReasoningLimits)

  • collect_negation_trace (bool)

  • collect_proofs (bool)

  • cancel (Callable[[], bool] | None)

Return type:

StratifiedRun

gestaltdb.reasoning.adapters.execution.execute_closure(program, facts, *, executor_request=ExecutorRequest(profile='positive-binary-entity-v1', mode='closure', preferred='default', polars_available=False), admission_request=None, generation=None, plan=None, context=None, limits, collect_proofs=False, polars_max_intermediate_rows=None, cancel=None)[source]

Evaluate one binary closure through an explicitly decided executor.

The decision is verified, not assumed: select_executor resolves the executor, and a bound generation is admitted with exact dictionary, mode and executor compatibility. Prepared-plan execution requires the caller to supply the matching PreparedProgram; Polars execution requires an explicit InputContext and a truly available runtime. Omitting the preference keeps the indexed reference even when Polars is installed. polars_max_intermediate_rows explicitly configures the prototype’s physical row bound (default 100,000), separately from logical identity and cumulative limits.max_candidate_rows. Non-Polars requests reject it.

Examples

Run the default indexed executor with closure telemetry:

1>>> from gestaltdb.reasoning.adapters.execution import execute_closure
2>>> from gestaltdb.reasoning.model import Atom, Fact, Program, Rule, Variable, ReasoningLimits
3>>> x, y = Variable("x"), Variable("y")
4>>> program = Program([Rule("r", [Atom(x, "parent", y)], Atom(x, "ancestor", y))])
5>>> outcome = execute_closure(program, [Fact("alice", "parent", "bob")], limits=ReasoningLimits())
6>>> assert Fact("alice", "ancestor", "bob") in outcome.result.facts
7>>> assert outcome.telemetry.executor == "indexed-python-v1"

Caller-provided facts alone carry no database source-verification guarantee. See the reasoning-executors and reasoning-admission guides for contexts, prepared plans, generation pins, and explicit optional executor requests.

Parameters:
  • program (Program)

  • facts (Iterable[Fact | Evidence])

  • executor_request (ExecutorRequest)

  • admission_request (AdmissionRequest | None)

  • generation (GenerationIdentity | None)

  • plan (PreparedProgram | None)

  • context (InputContext | None)

  • limits (ReasoningLimits)

  • collect_proofs (bool)

  • polars_max_intermediate_rows (int | None)

  • cancel (Callable[[], bool] | None)

Return type:

ExecutionOutcome

Selective answers, support maintenance, and validation

Use a bound goal for a particular entity, carry supports with a maintained closure, or report semantic conflicts without changing the facts. See Goal-directed queries and demand specialization, Bounded maintenance provenance and insertion propagation, and Explicit negatives and validation reports for the corresponding contracts.

gestaltdb.reasoning.demand.answer(program, facts, goal, *, limits, cache=None, cancel=None)[source]

Evaluate the demand-specialized program and return goal-matching facts.

Unsupported combinations (negation, aggregates, closed scopes, predicate variables) fail closed here instead of silently falling back — callers that need those modes use full closure explicitly and document it.

Examples

Ask for one entity’s derived classifications using a bound goal:

1>>> from gestaltdb.reasoning.demand import BoundGoal, answer
2>>> from gestaltdb.reasoning.model import ReasoningLimits, Variable
3>>> from gestaltdb.reasoning.typed import GenericProgram, GenericRule, TypedAtom, TypedFact
4>>> x = Variable("x")
5>>> program = GenericProgram([GenericRule("r", [TypedAtom("member", [x])], [], TypedAtom("person", [x]))])
6>>> facts = [TypedFact("member", ["alice"]), TypedFact("member", ["bob"])]
7>>> result = answer(program, facts, BoundGoal("person", ("alice",)), limits=ReasoningLimits())
8>>> assert result.facts == (TypedFact("person", ["alice"]),)

This specializes a program over caller-provided facts. For selective reads directly from a pinned database view, use the explicit frontier adapter.

Parameters:
  • program (GenericProgram)

  • facts (Iterable[TypedFact])

  • goal (BoundGoal)

  • limits (ReasoningLimits)

  • cache (SpecializationCache | None)

Return type:

DemandAnswer

gestaltdb.reasoning.maintenance.rematerialize(program, base_facts, *, limits, max_supports=100000, cancel=None)[source]

Full evaluation with complete support discovery; the explicit fallback.

Every derived fact gets every support, so later incremental deletions are exact. Changed programs simply rematerialize under the new digest; the old index is never incrementally repaired across a ruleset change.

Examples

Build supports and retract the only premise of a derived fact:

 1>>> from gestaltdb.reasoning.model import ReasoningLimits, Variable
 2>>> from gestaltdb.reasoning.typed import GenericProgram, GenericRule, TypedAtom, TypedFact
 3>>> from gestaltdb.reasoning.maintenance import rematerialize, retract_facts
 4>>> x = Variable("x")
 5>>> program = GenericProgram([GenericRule("r", [TypedAtom("member", [x])], [], TypedAtom("person", [x]))])
 6>>> base = TypedFact("member", ["alice"])
 7>>> material = rematerialize(program, [base], limits=ReasoningLimits())
 8>>> assert TypedFact("person", ["alice"]) in material.facts
 9>>> changed = retract_facts(program, material.facts, [base],
10...     limits=ReasoningLimits(), index=material.index)
11>>> assert TypedFact("person", ["alice"]) not in changed.facts

Carry the returned facts and dependency index together between updates. Negation, aggregate, and equality-change combinations have separate rebuild boundaries; consult the reasoning-maintenance guide before composing them.

Parameters:
  • program (GenericProgram)

  • base_facts (Iterable[TypedFact])

  • limits (ReasoningLimits)

  • max_supports (int)

  • cancel (Callable[[], bool] | None)

Return type:

Materialization

gestaltdb.reasoning.validation.validate(facts, suite, *, max_violations=1000, cancel=None)[source]

Check a finite closure against the suite; never modifies or extends it.

Facts stream in canonical order; violations are deterministic for identical inputs. max_violations bounds the report — hitting it sets truncated instead of failing. Cancellation raises without a report.

Examples

Report a functional-property conflict without changing the facts:

1>>> from gestaltdb.reasoning.typed import TypedFact
2>>> from gestaltdb.reasoning.validation import ValidationSuite, validate
3>>> facts = [TypedFact("manager", ["alice", "bob"]), TypedFact("manager", ["alice", "carol"])]
4>>> report = validate(facts, ValidationSuite(membership="type", functional=["manager"]))
5>>> assert not report.clean
6>>> assert report.violations[0].kind == "functional-conflict"
7>>> assert len(facts) == 2

Source labels identify generated constraints, not historical claim-version evidence. Input is buffered and sorted; max_violations limits the report rather than input memory. See the reasoning-validation guide for those bounds.

Parameters:
  • facts (Iterable[TypedFact])

  • suite (ValidationSuite)

  • max_violations (int)

Return type:

ValidationReport

Reason over validity intervals

This example computes when conclusions hold. It is separate from storing temporal history, as explained in Temporal history and service reference and Reason over complete validity ranges.

gestaltdb.reasoning.temporal_closure.evaluate_range(program, facts, *, limits, max_segments=10000, max_supports=100000, max_sweep_rows=100000, max_sweep_events=200000, max_sweep_memberships=1000000, cancel=None)[source]

Evaluate every change segment; union per-segment closures with evidence.

Each segment runs ordinary point evaluation over its uniform active inputs — stratified when the program uses negation or closed scopes — so stratified negation and nonrecursive aggregates evaluate with per-interval absence and aggregate evidence. Derivations record only what actually fired on their segment: gaps stay gaps, and empty groups infer no zero counts.

Active inputs are scheduled once with an interval event sweep instead of scanning every input at every segment: each row contributes add/remove events at its half-open bounds (multiplicity preserved for overlapping assertions), and segments tile exactly the change points change_segments would emit. Per-segment evaluation, support discovery and evidence identity are unchanged.

Examples

Derive eligibility only during the premise’s half-open validity:

 1>>> from gestaltdb.reasoning.model import ReasoningLimits, Variable
 2>>> from gestaltdb.reasoning.typed import GenericProgram, GenericRule, TypedAtom, TypedFact
 3>>> from gestaltdb.reasoning.intervals import Interval, IntervalSet
 4>>> from gestaltdb.reasoning.temporal_closure import TemporalFact, evaluate_range, verify_closure
 5>>> x = Variable("x")
 6>>> program = GenericProgram([GenericRule("r", [TypedAtom("member", [x])], [], TypedAtom("eligible", [x]))])
 7>>> base = [TemporalFact(TypedFact("member", ["alice"]), IntervalSet([Interval(0, 10)]))]
 8>>> closure = evaluate_range(program, base, limits=ReasoningLimits())
 9>>> assert TypedFact("eligible", ["alice"]) in closure.at(5)
10>>> assert TypedFact("eligible", ["alice"]) not in closure.at(10)
11>>> assert verify_closure(program, closure, limits=ReasoningLimits()).points_checked == 1

Times here are integer microseconds, not database commit IDs. Database-backed extraction and publication require the separate range adapters; see the reasoning-range-admission and reasoning-bound-range-publication guides.

Parameters:
  • program (GenericProgram)

  • facts (Iterable[TemporalFact])

  • limits (ReasoningLimits)

  • max_segments (int)

  • max_supports (int)

  • max_sweep_rows (int)

  • max_sweep_events (int)

  • max_sweep_memberships (int)

  • cancel (Callable[[], bool] | None)

Return type:

TemporalClosure

Connect a graph and resume saved state

These examples require the lmdb extra. Projection consumes explicit mappings; session advancement consumes committed evidence changes. See Current-graph ontology adapters and Resumable incremental reasoning sessions for the larger workflows.

class gestaltdb.reasoning.adapters.graph.PinnedGraphSource(view, *, mapping, limits=GraphSourceLimits(max_records=100000))[source]

Borrow a caller-managed verifiable current snapshot, never temporal claims.

Keep the read-view context open through evaluation. Closing this source does not close the view or graph. Snapshot authentication is checked before/after extraction; record limits do not bound snapshot digest cost or kernel work.

Examples

Classify a stored node through an explicit label mapping (requires LMDB):

 1>>> from tempfile import TemporaryDirectory
 2>>> from gestaltdb.graphdb import GraphDB, Node
 3>>> from gestaltdb.ontology import Ontology, SubClassOf, compile_ontology
 4>>> from gestaltdb.ontology.model import TYPE_PREDICATE
 5>>> from gestaltdb.reasoning.adapters.graph import GraphMapping, PinnedGraphSource
 6>>> from gestaltdb.reasoning.model import Fact, ReasoningLimits
 7>>> compiled = compile_ontology(Ontology("people", [SubClassOf("Employee", "Person")]))
 8>>> with TemporaryDirectory() as root:
 9...     graph = GraphDB.create(root + "/db", backend="lmdb", serializer="json")
10...     try:
11...         graph.put_node(Node("alice", labels=["Employee"]))
12...         with graph.current_read_view(require_verifiable=True) as view:
13...             with PinnedGraphSource(view, mapping=GraphMapping(labels=(("Employee", "Employee"),))) as source:
14...                 result = source.evaluate(compiled, limits=ReasoningLimits())
15...         assert Fact("alice", TYPE_PREDICATE, "Person") in result.result.facts
16...     finally:
17...         graph.close()

Labels, properties, and edge types participate only through the supplied mapping. See the ontology-graph and reasoning-current-admission guides for projection rules and source-bound generation reuse.

Parameters:
gestaltdb.reasoning.adapters.sessions.start_session(graph, program, catalog, *, scope, limits, max_versions=100000, cancel=None)[source]

Pin the current horizon and materialize one session from a full scan.

A session is reasoning state, not a connection: it fixes a valid-time point, world, program/catalog, and commit horizon. advance_session returns new state; it does not mutate the original or publish inferred claims.

Examples

Advance and persist a classification after new evidence (requires LMDB):

 1>>> from tempfile import TemporaryDirectory
 2>>> from gestaltdb.graphdb import GraphDB
 3>>> from gestaltdb.reasoning.model import ReasoningLimits, Variable
 4>>> from gestaltdb.reasoning.typed import GenericProgram, GenericRule, TypedAtom, TypedFact
 5>>> from gestaltdb.reasoning.adapters.claims import ClaimMapping, ClaimSelection
 6>>> from gestaltdb.reasoning.adapters.sessions import SessionScope, start_session, advance_session
 7>>> from gestaltdb.reasoning.adapters.session_generation import catalog_for_typed_program
 8>>> from gestaltdb.reasoning.adapters.session_store import save_session, load_session
 9>>> x, y = Variable("x"), Variable("y")
10>>> program = GenericProgram([GenericRule("r", [TypedAtom("member", [x, y])], [], TypedAtom("person", [x]))])
11>>> scope = SessionScope("default", 50, ClaimSelection(), ClaimMapping())
12>>> with TemporaryDirectory() as root:
13...     graph = GraphDB.create(root + "/db", backend="lmdb", serializer="json")
14...     try:
15...         _ = graph.epistemic.assert_claim(subject="alice", predicate="member", object="team",
16...             agent="registry", polarity="positive", valid=(0, 100))
17...         session = start_session(graph, program, catalog_for_typed_program(program),
18...             scope=scope, limits=ReasoningLimits())
19...         digest = save_session(session, root + "/session.json")
20...         _ = graph.epistemic.assert_claim(subject="bob", predicate="member", object="team",
21...             agent="registry", polarity="positive", valid=(0, 100))
22...         moved = advance_session(graph, session, limits=ReasoningLimits())
23...         _ = save_session(moved.session, root + "/session.json", expected_session_digest=digest)
24...         assert TypedFact("person", ["bob"]) in load_session(root + "/session.json").facts
25...     finally:
26...         graph.close()

This demonstrates persistence and exact-file-state comparison. Source-verified durable resume additionally requires caller-held generation/state pins; see the reasoning-authenticated-sessions guide for the complete trusted-pin flow.

Parameters:
  • graph (GraphDB)

  • program (GenericProgram)

  • catalog (RuleCatalog)

  • scope (SessionScope)

  • limits (ReasoningLimits)

  • max_versions (int)

  • cancel (Callable[[], bool] | None)

Return type:

ReasoningSession

Longer source-verified workflows

Some setup is important enough to keep in one complete guide instead of repeating a large example in every function’s docstring:

Those guides include runnable examples with explicit inputs and capability boundaries. Use the matching entry-point reference for parameter details.