Python
Python
Use the unified Python binding built on the installed opaque C SDK.Maelys DL exposes a native Python binding for in-process use — no browser or
WASM runtime. It targets research pipelines, offline analysis, and long-running
services: Python exceptions represent errors, explicit objects represent policy
and session lifetimes, and integer terms retain the full native int64 range.
The underlying concepts — EDB facts, predicate kinds, solving and querying — are the same as in C and WASM, documented in the Concepts pages. See Bindings overview for the cross-language map.
These topic pages preserve the progression of the historical Python V1 reference: installation, loading, domains, ownership, term encoding, queries, explanations, and the API reference. They add manifest loading, prepared sessions, Why-false and explicit execution requirements.
The ordinary sequence remains: declare the domain, load a policy, collect facts, solve, and inspect the result. The CFFI extension calls the opaque C facade, never an internal engine structure.
Public Python objects
Python exposes classes and value objects rather than C handles and free functions. The links lead directly to each class card or flag reference. The complete method index below is organized by class. Each topic page lists only the reference cards defined there.
The binding also exports Status, Capability, ExplanationKind and the PRED_* flags. Predicate roles are explained in Registries, capability and explanation masks in Solving and Querying, and native failure statuses in Errors.
Explore by topic
- Registries
- Loading & manifests
- Rulesets
- Runtime EDB
- Solving
- Querying and explanations
- Errors
- Complete examples
API reference
The Detailed API group contains one canonical page for each public class or enumeration. Each class page groups its methods, signatures, argument descriptions, return behavior and compact examples. The sibling usage guides explain the programming flow.
Value-class declarations and public creation signatures come from the published binding inventory. Resource-owning classes list their methods as individual links with a short explanation. Each link opens the complete signature, arguments, return behavior and example; the creation signatures are a reference, not executable class source. The examples are fragments: engine, ruleset, edb, session and result refer to the live objects explained in the usage guides and in the complete examples. Import the named classes before using them.
Detailed API
Engine reference
| Name | Summary |
|---|---|
Engine class (1 field) | Python owner created with Engine(); it reads engine.limits and tracks loaded Ruleset objects. Closing it closes native children but does not unregister domains. Use it on the creating thread. |
Engine.limits property | Immutable snapshot of build capacities. |
engine.register_domain() method | Registers the domain’s predicate vocabulary and optional policy-source atoms before policies are loaded against it. It does not load or evaluate a policy. |
engine.load_inline_ruleset() method | Loads one policy directly from Datalog source text against a registered domain, without reading a manifest. |
engine.load_manifest() method | Loads a policy set from a manifest file, applying its source-hash checks, domain validation and public query permissions. |
engine.close() method | Closes this Python owner and its native children. It does not unregister domains from the global registry. |
with engine: protocol | Leaving the block closes this Engine, its rulesets and their native children. |
Engine() constructor | Creates the Python owner used to register domains and load rulesets. |
Guides: Registries · Full program
Predicate reference
| Name | Summary |
|---|---|
Predicate class (3 fields) | Immutable declaration of one predicate; the class methods below provide convenient constructors for common flag combinations. |
Predicate.name property | Relation name used in policy rules, facts and queries. |
Predicate.arity property | Number of terms in each fact or rule atom. |
Predicate.flags property | Integer fact-origin and optional query-permission bitmask; see the Constants cards. |
Predicate.edb() method | Constructs a declaration for a predicate whose facts come from runtime request input. Creating this value does not register it with the engine. |
Predicate.edb_query() method | Constructs a runtime-input predicate declaration with query permission, so callers may test its facts in a result. |
Predicate.idb() method | Constructs a declaration for a predicate whose facts are derived by policy rules, without enabling public queries. |
Predicate.idb_query() method | Constructs a derived-predicate declaration with query permission, so callers may inspect the relation after solving. |
Predicate.policy_fact() method | Constructs a declaration for a predicate whose ground facts may be written directly in policy source. |
Predicate.policy_fact_query() method | Constructs a policy-source fact declaration with query permission, so callers may test those facts in a result. |
Predicate() constructor | Creates an immutable predicate declaration from its name, arity and integer flags. Combine a fact origin with optional PRED_QUERY using |; engine.register_domain() validates and registers the declaration before rules are loaded. |
PRED_EDB constant | Runtime input facts supplied in the EDB for one evaluation. |
PRED_IDB constant | Facts derived by policy rules. |
PRED_QUERY constant | Permission to observe a predicate through the query API; not a fact origin by itself. |
PRED_POLICY_FACT constant | Base facts written in trusted policy source. |
Guides: Registries · Full program
Ruleset reference
| Name | Summary |
|---|---|
Ruleset class (2 fields) | Loaded policy-set owner. Close it explicitly or with a context manager. |
Ruleset.policy_count property | Number of loaded policies; valid indices run from 0 to count minus 1. |
Ruleset.fingerprint property | Identity of the whole loaded policy set, not a hash of request facts. |
ruleset.program_counts() method | Read compiled predicate, policy-fact and normalized-rule counts for one policy. |
ruleset.edb() method | Creates an empty input buffer associated with this ruleset. Fill it with runtime facts before solving a request. |
ruleset.prepare() method | Prepares one selected policy for reuse across requests, with the chosen session options. Preparation does not yet supply facts or compute an answer. |
ruleset.solve() method | Evaluates one complete input batch using a private session created for this call. Use prepare() when the same session should be reused for multiple requests. |
ruleset.close() method | Closes the loaded policy set and its dependent Python resources when the application has finished using them. |
with ruleset: protocol | Leaving the block closes this Ruleset and its sessions, results and input buffers. |
ruleset.reads_predicate() method | Checks whether the selected compiled policy reads a named predicate in its rule body, without preparing a session. |
Guides: Rulesets · Full program
Edb reference
| Name | Summary |
|---|---|
Edb class | Native input buffer for one evaluation. Close it explicitly or through its Ruleset owner; Edb is not a context manager. |
len(edb) protocol | Counts stored input entries before deduplication through Python’s len(edb) protocol. |
edb.add_fact() method | Appends one typed input fact, copying its text values into native storage. This call does not evaluate the policy. |
edb.add_facts() method | Appends a batch of input facts atomically: if validation or storage fails, none of this batch is added. Earlier successful additions are retained. |
edb.clear() method | Empties an input buffer that has not been successfully solved. Use reset() instead when starting a new request after a successful solve. |
edb.reset() method | Starts a new, empty input batch in the same buffer, including after a successful solve. It does not release the session’s previous result. |
edb.close() method | Releases native input storage. Results already produced from this buffer remain valid. |
Edb() constructor | Creates an empty input buffer associated with an open Ruleset, using optional fixed storage capacities. |
Guides: Runtime EDB · Full program
Session reference
| Name | Summary |
|---|---|
Session class (3 fields) | Reusable selected-policy owner. Only one result may remain live at a time. |
Session.capacities property | Effective fixed quotas. |
Session.fingerprint property | Selected-policy authority. |
Session.execution_fingerprint property | Selected policy plus backend and execution configuration. |
session.inputs() method | Attaches fixed-vocabulary retained input before the first successful solve. The binding allocates its aligned attachment storage. |
session.solve() method | Evaluates a complete input batch using this prepared session. Release its previous result before solving another request; facts are not implicitly inherited. Ordinary solving is unavailable while retained input is attached. |
session.close() method | Closes the prepared session, its active Python result and any attached retained input. |
with session: protocol | Leaving the block closes this Session and its active result. |
Guides: Solving · Full program
InputBase reference
| Name | Summary |
|---|---|
InputBase class (2 fields) | Immutable retained-input base: attachment incarnation and committed generation. Pass the current base to replace or apply. |
InputBase.incarnation property | Exact attachment incarnation read from this attachment. |
InputBase.generation property | Committed input generation; read a fresh base after a successful transaction. |
InputBase() constructor | Reconstructs an immutable retained-input base from its exact public integer fields. |
Guides: Solving · Full program
SessionInputs reference
| Name | Summary |
|---|---|
SessionInputs class (2 fields) | Retains dynamic facts and a fixed vocabulary on one Session. Each replace or apply requires the current InputBase and returns a leased SolveResult. Close that result before the next transaction. Python/CFFI staging still allocates. |
SessionInputs.base property | Current attachment incarnation and committed input generation. |
SessionInputs.session property | Session that owns this retained-input attachment. |
inputs.replace() method | Atomically replaces the complete retained dynamic input and solves it. The raw fact-capacity bound applies before deduplication. |
inputs.apply() method | Applies an atomic delta to retained input and solves it. Additions win when the same fact is added and removed. |
inputs.close() method | Releases this retained-input attachment and its aligned storage. |
with inputs: protocol | Leaving the block closes this retained-input attachment. |
Guides: Solving · Full program
SolveResult reference
| Name | Summary |
|---|---|
SolveResult class (2 fields) | Solved answer. Queries and raw term resolution require this result to remain open. |
SolveResult.fingerprint property | Selected-policy authority. |
SolveResult.execution_fingerprint property | Selected policy plus execution configuration. |
result.explain_true() method | Explains a derivation of the requested fact as a bounded Why-true document, using the existing solve result. |
result.explain_false() method | Investigates obstacles to deriving an absent fact and produces a bounded Why-false document. It is not an exhaustive proof of all possible obstructions. |
result.contains_fact() method | Checks whether one fully specified fact is present in the existing result. It does not solve the policy again. |
result.derived_fact_count() method | Reads how many facts were derived during this solve, without enumerating the model or deriving more facts. |
result.enumerate_predicate_facts() method | Lists a query-enabled derived relation as ordinary Python values copied from the result. |
result.enumerate_raw() method | Lists a derived relation as typed ResultTerm records, keeping symbols as IDs local to this live result. |
result.resolve_term() method | Converts a raw term from this result into its ordinary Python string, integer or boolean value. |
result.close() method | Releases this result, including any private session created by Ruleset.solve(). An explicitly prepared session remains available for another request. |
with result: protocol | Leaving the block closes this result. |
Guides: Querying · Full program
ResultTerm reference
| Name | Summary |
|---|---|
ResultTerm class (2 fields) | Immutable raw output value returned by enumerate_raw(). It retains its result owner for resolution; do not manufacture it as input. Symbol IDs are scoped to that result, not the Ruleset. |
ResultTerm.kind property | Term kind: symbol, integer or boolean. |
ResultTerm.value property | Result-local numeric symbol ID, signed integer, or boolean according to kind. |
term.resolve() method | Resolves this raw term through its owning result to obtain the corresponding Python value. |
Guides: Querying · Full program
MaelysDatalogError reference
| Name | Summary |
|---|---|
MaelysDatalogError exception (5 fields) | RuntimeError subclass raised on a failed native operation. status and code are the same integer operation status; message and hint are str; diagnostic is a Diagnostic record with its own reason code. Catch native failures separately from malformed Python arguments. |
MaelysDatalogError.code property | Alias of error.status; not the diagnostic reason code. |
MaelysDatalogError.status property | Native operation status; compare with Status members. |
MaelysDatalogError.message property | Human-readable detail. |
MaelysDatalogError.hint property | Suggested corrective action when supplied. |
MaelysDatalogError.diagnostic property | Structured native detail, including its distinct reason code and presence mask. |
Guides: Errors · Full program
Limits reference
| Name | Summary |
|---|---|
Limits class (14 fields) | Immutable capacity snapshot. Its fields describe the loaded native profile, not available remaining space. |
Limits.max_symbols property | Maximum distinct symbols in the engine symbol table. |
Limits.string_pool_bytes property | Byte capacity of the engine symbol-text pool. |
Limits.max_predicates property | Maximum declared predicates. |
Limits.max_rules property | Maximum compiled rules. |
Limits.max_arity property | Maximum number of terms in a predicate. |
Limits.max_body_literals property | Maximum body literals per rule. |
Limits.max_depth property | Maximum configured derivation depth. |
Limits.max_edb_facts property | Maximum input entries; counted before deduplication. |
Limits.max_idb_facts property | Maximum derived facts. |
Limits.max_facts_per_pred property | Maximum facts retained for one predicate. |
Limits.max_string_bytes property | Maximum UTF-8 bytes in one input string. |
Limits.input_edb_text_bytes property | Default and maximum byte capacity for owned input EDB text. |
Limits.max_policy_atoms property | Maximum declared policy-source atoms. |
Limits.max_policy_atom_bytes property | Maximum UTF-8 bytes across policy atoms, excluding NUL terminators. |
Guides: Registries · Full program
ProgramCounts reference
| Name | Summary |
|---|---|
ProgramCounts class (3 fields) | Immutable compiled counts for one selected policy, returned by Ruleset.program_counts(). |
ProgramCounts.predicates property | Declarations in the domain registry, including unused predicates. |
ProgramCounts.facts property | Facts compiled from policy source, excluding runtime EDB facts. |
ProgramCounts.rules property | Normalized rules, including expanded OR alternatives. |
Guides: Rulesets · Full program
SessionCapacities reference
| Name | Summary |
|---|---|
SessionCapacities class (4 fields) | Optional fixed native E/D/S/T quotas requested when preparing or privately solving; None selects the SDK default and zero is explicit. |
SessionCapacities.input_facts property | Maximum runtime input facts; None uses the profile default. |
SessionCapacities.derived_facts property | Maximum derived facts; None uses the profile default. |
SessionCapacities.symbols property | Maximum symbols; program-rooted symbols count too. |
SessionCapacities.text_bytes property | Maximum native text bytes including NUL storage; None uses the profile default. |
SessionCapacities() constructor | Create a capacity request for session preparation or private solving. |
Guides: Solving · Full program
Diagnostic reference
| Name | Summary |
|---|---|
Diagnostic class (30 fields) | Immutable copy of native diagnostic fields, available as error.diagnostic. The present bitmask identifies which native detail sections are supplied; zero or empty defaults must not be mistaken for observed details. |
Diagnostic.source property | Native diagnostic source identifier. |
Diagnostic.status property | Native operation status copied into the diagnostic. |
Diagnostic.code property | Diagnostic reason code, distinct from the operation status. |
Diagnostic.present property | Bitmask of supplied diagnostic detail sections. |
Diagnostic.line property | Source line when location information is supplied. |
Diagnostic.column property | Source column when location information is supplied. |
Diagnostic.phase property | Operation phase reported by the engine. |
Diagnostic.message property | Human-readable diagnostic detail. |
Diagnostic.hint property | Suggested corrective action when supplied. |
Diagnostic.file property | Source or manifest path when supplied. |
Diagnostic.predicate property | Predicate associated with the error. |
Diagnostic.arity property | Associated predicate arity. |
Diagnostic.observed_count property | Observed count for a supplied capacity diagnostic. |
Diagnostic.limit property | Capacity bound for that diagnostic. |
Diagnostic.depth property | Observed depth when depth information is supplied. |
Diagnostic.depth_limit property | Depth bound when supplied. |
Diagnostic.rule_id property | Associated rule identifier when supplied. |
Diagnostic.comparison_result property | Reported comparison result when comparison details are supplied. |
Diagnostic.expected_kind property | Expected term kind when type details are supplied. |
Diagnostic.lhs_kind property | Kind of the left comparison operand. |
Diagnostic.rhs_kind property | Kind of the right comparison operand. |
Diagnostic.comparison_op property | Native comparison operator identifier. |
Diagnostic.limit_kind property | Identifier of the capacity that was exceeded. |
Diagnostic.term_index property | Associated term position when supplied. |
Diagnostic.expected_arity property | Expected predicate arity. |
Diagnostic.observed_arity property | Observed argument count. |
Diagnostic.token property | Token associated with the error. |
Diagnostic.field property | Manifest or declaration field associated with the error. |
Diagnostic.domain property | Domain associated with the error. |
Diagnostic.limit_name property | Stable native budget name, or None when the identifier is unknown. |
Guides: Errors · Full program
Status reference
| Name | Summary |
|---|---|
Status enum (15 members) | IntEnum for native operation statuses. Successful methods return their documented Python value, not Status.OK; failures raise MaelysDatalogError whose status can be compared with these members. A false membership answer is not an error status. |
Guides: Errors · Full program
Capability reference
| Name | Summary |
|---|---|
Capability enum (12 members) | IntFlag values combined with | to require backend features at session preparation. Operators used by a compiled policy are detected automatically. AGGREGATES means count only; MIN, MAX and SUM are independent. WORK_LIMIT is unsupported by the reference backend. |
Guides: Solving · Full program
ExplanationKind reference
| Name | Summary |
|---|---|
ExplanationKind enum (2 members) | IntFlag selecting optional reusable session explanation storage. TRUE | FALSE uses one shared workspace, not two. Zero reserves none; when a workspace is selected, requesting an omitted kind is rejected without allocating a fallback. |
Guides: Solving · Full program
Constructors
Class construction is separate from domain registration or solving.
Installation
For CPython 3.10–3.14 with the GIL, install a wheel from the v0.27.0 release assets. The Maelys wheel is hosted on GitHub Releases, not PyPI. Choose the URL matching the platform:
| Platform | Release wheel |
|---|---|
| Linux ARM64, glibc 2.28+ | Download wheel |
| Linux x86_64, glibc 2.28+ | Download wheel |
| macOS ARM64 13.0+ | Download wheel |
Copy the selected URL into WHEEL_URL, then install it directly:
python3 -m venv .venv
.venv/bin/python -m pip install --only-binary=:all: "$WHEEL_URL"The wheel contains SMALL and LARGE engines; SMALL is the default. Select LARGE with MAELYS_DATALOG_PROFILE=large before the first import and use a fresh interpreter when switching profiles. No SDK or compiler is required to install the wheel. CFFI remains a runtime dependency obtained from the configured package index. PyPy, free-threaded Python, musl/Alpine, Windows and macOS Intel are not covered by these wheels.
For a source build, CFFI, setuptools, a C11 compiler and CMake 3.16+ are required. Install the native SDK first, then compile the CFFI extension against that same SDK prefix. From the v0.27.0 source checkout:
python3 -m venv build/python-venv
build/python-venv/bin/python -m pip install cffi setuptools pytest
cmake -S . -B build/cmake-small
cmake --build build/cmake-small --parallel 4
cmake --install build/cmake-small --prefix "$PWD/build/sdk-small"
build/python-venv/bin/python bindings/python/build_cffi.py \
--sdk-prefix "$PWD/build/sdk-small"
MAELYS_DATALOG_SDK_PREFIX="$PWD/build/sdk-small" \
MAELYS_DATALOG_EXPECT_PROFILE=small PYTHONPATH=bindings/python \
build/python-venv/bin/python -m pytest -q tests/pythonThe builder copies the installed shared library beside the Python extension.
--build-dir and --engine-dir belonged to the experiment and are removed;
--sdk-prefix proves that headers and library come from one installation.
For LARGE, configure a separate build with
-DMAELYS_DATALOG_PROFILE_LARGE=ON, install it to a separate prefix, rebuild
the extension and start a fresh interpreter. Inspect engine.limits and the
expected-profile check to verify which library was actually loaded.
Native library discovery
The source-built Python extension is itself a dynamic library. It depends on
libmaelys_datalog_shared (the engine), not the historical
libmaelys_py_bind shim. At import time, the operating system must find that
dependency; PYTHONPATH alone only helps Python find its package. Published
wheels instead link each profile engine statically into its isolated CFFI extension.
The CFFI builder copies the selected engine library beside the package. On Linux the resulting layout is:
bindings/python/maelys_datalog/
├── __init__.py
├── engine.py
├── _maelys_cffi....so ← compiled extension
└── libmaelys_datalog_shared.so ← copied from --sdk-prefixOn macOS the native library uses .dylib; the extension still uses Python's
platform-specific suffix. Python first finds maelys_datalog through its
module path, then the OS resolves the extension's native dependency.
$ORIGIN on Linux and @loader_path on macOS record a loader-relative
search path: look beside the extension, not in the original build directory.
Keep the extension and library together. No LD_LIBRARY_PATH is needed for
this layout; if import fails, check their origin and profile before changing
environment variables.
# check_import.py
import maelys_datalog
print("import OK")PYTHONPATH=/path/to/maelys-datalog/bindings/python python check_import.pyNative call path
The loading choices above are separate from the library layers below. Both supported choices cross the same public C boundary:
- Python APImaelys_datalog
- CFFI extensiongenerated bridge
- Opaque C facademaelys/datalog.h
- Native enginesame inference semantics
There is no handwritten maelys_py_bind layer in this path. CFFI generates a
native extension: a source build links to libmaelys_datalog_shared, while
the published wheels contain their statically linked profile engines. Opaque
handles hide implementation details, not features: engine.limits and
result.derived_fact_count() are exposed through public C getters.
Both inline source and native manifests are supported. load_inline_ruleset()
compiles one policy; load_manifest() preserves native SHA verification,
query whitelists and multi-policy selection. The generated bridge includes
<maelys/datalog.h>, <maelys/datalog_resources.h> and
<maelys/datalog_inputs.h>, never backend descriptors or private engine
structures.
One consumer header, a separate extension API
datalog.h supplies the opaque handles, capability constants, session
configuration and execution fingerprint used by this binding.
datalog_backend.h is for C developers implementing an alternative execution
backend; Python does not include it.
When you call ruleset.prepare(required_capabilities=..., work_limit=...),
the binding creates an opaque native configuration, sets those values, creates
the session and frees the temporary configuration. Session creation copies the
values, so the session does not depend on that configuration's lifetime.
Python code never supplies a backend ABI version or a C structure size.
This changes the native integration, not the Python method signatures. Unsupported requirements still fail explicitly: in particular, the reference backend rejects a nonzero work budget rather than pretending to enforce it.
Session lifecycle
with Engine() as enginePython owner of policy wrappers and an immutable snapshot of native build limits.
engine.register_domain(...)Declare the vocabulary in the process-wide registry; it is not owned by an Engine.
engine.load_inline_ruleset(...)Own an opaque compiled-policy handle, not an exposed C struct or mutable symbol table.
edb.add_fact(...) / edb.add_facts(...)Own copied input values in an opaque native EDB; additions check storage bounds without running the solver.
result = ruleset.solve(edb)Each solve creates a native session, submits one complete batch and retains the result for queries.
result.close() or leaving with Engine()Release each result before its session, then release its policy. Closing Engine closes remaining native children.
Ruleset owns an opaque compiled-policy handle — not Engine, which owns the Python wrappers and the build-limit snapshot. Multiple rulesets can be loaded and closed independently within a process. Unlike those handles, the domain registry remains shared and survives Engine closure.
Each successful ruleset.solve() creates its own opaque session and result.
The diagram above describes this convenience path. For repeated evaluation,
ruleset.prepare() returns an explicit reusable Session with one live result
at a time; see prepared sessions.
Several results can coexist. After success, the EDB cannot be mutated,
but it can be solved again to produce another independent result.
Use a new ruleset.edb() for different inputs.
result.close() frees its result and, for the convenience path, its private
session. With an explicit Session, closing the result leaves the session reusable.
session.close() closes its live result first. ruleset.close() closes all
results, sessions and EDBs before releasing the policy. The with Engine()
block closes all remaining children even on exceptions. Objects used
after their parent closes raise RuntimeError; query results must be
read while their owner remains open.
The Python Edb owns an opaque native input EDB handle. Its idempotent
close() frees that storage; it does not invalidate an already computed result.
Closing its Ruleset prevents later use. Close buffers you no longer need
to release native input memory, especially in long-running processes.
Python API walkthrough
Five owner/value layers structure this walkthrough: Engine owns Python
Rulesets and reads build limits; Ruleset owns a compiled policy set; Edb
buffers one evaluation's inputs; Session holds prepared native execution
state; SolveResult retains one solve's model. The convenience solve()
creates its Session for you. The sequence is the same as the original
reference, but insertion timing and symbol ownership change.
Threading model
The old binding used a process-wide registry lock plus per-Ruleset symbol
locks. Those locks protected particular operations; they did not make every
object safe to share. Python makes the ownership rule explicit instead:
an Engine and all its handles are confined to the thread that created it.
The wrapper checks this before entering native code, including on close().
Do not rely on the Python interpreter lock to serialize access to native objects, and do not move an Engine into a worker after creating it in the main thread. Create the Engine inside that worker. Independent workers can own independent Engines and rulesets, while domain registration and policy loading remain serialized by the wrapper's process-wide registry lock.
That lock covers calls made through this binding. It is not a cross-language synchronization protocol for arbitrary C code mutating the same registry. Creating another Engine also does not create or unregister a domain: the vocabulary remains process-wide, as described under Domain definition.
Within one owner thread, a prepared Session permits one live result. Close that result before solving again. Independent convenience solves create independent sessions and may keep several results open. These are lifecycle rules, not an invitation to use the handles concurrently on other threads.
Use context managers or explicit close(): the prototype has no GC finalizer.
A parent closes native children in result → session → EDB → policy order, and later
use of a closed child raises RuntimeError. A second close() on a wrapper
is harmless on its owner thread; it is not permission to race close with use.
Engine feature coverage
The following coverage is verified against the current code, not inferred from a roadmap. This is the single binding shipped with the current engine; its precompiled wheels are published as GitHub Release assets.
| Capability | Python |
|---|---|
| Standard language, including negation, positive disjunction and wildcard | Policy source |
Standard ground filters starts_with, ends_with, contains | Policy source; visible in native explanations |
| Manifest SHA checks, query whitelist, policy-local vocabulary | engine.load_manifest() |
| Multiple policies | ruleset.policy_count, policy_index |
| Reusable prepared state | ruleset.prepare() |
| Build limits and total derived count | engine.limits, result.derived_fact_count() |
| Resolved and result-owned raw enumeration | enumerate_predicate_facts(), enumerate_raw() |
| Why-true / Why-false | explain_true(), explain_false() |
| Policy and execution identity | Distinct fingerprint properties |
| Full native diagnostics | error.diagnostic |
| Explicit capability requirements | required_capabilities; rejection without fallback |
| Work-budget request | Exposed, but rejected by the current reference backend |
| True delta/incremental inference | Not implemented by the current engine API |
| Custom native frontend/backend/planner/filter registrations and IR builders | Separate extension SDK; no Python callback bridge here |
Opaque handles do not preclude extensions. However, registering native callbacks is a different API from using the engine's standard filters: this binding does not manufacture a dynamic loader or Python callback ABI.
Migration from the deprecated Python V1 binding
| Surface | Deprecated 0.9.1 Python V1 | Current maelys_datalog |
|---|---|---|
| Native boundary | Python-specific C shim | Public opaque C facade |
add_fact() | Native insertion | Atomic native opaque-buffer insertion |
add_facts() | Not available | Atomic native batch append; complete evaluation at solve |
| Native input errors | Usually at insertion | Storage checks at addition; policy-specific checks at solve |
| Declaring text constants for inline policies | No Python atoms parameter | register_domain(..., atoms=[...]) |
| Input symbol IDs | Ruleset-scoped intern_symbol | Not accepted; use strings |
| Raw enumeration | Available | Result-owned, lifetime-checked views |
| Why-true | explain_fact_text() | explain_true() |
| Why-false | Not wrapped | explain_false() |
| Manifest loading | Not wrapped | load_manifest() |
| Prepared-session reuse | Different legacy lifecycle | Explicit prepare() |
| Native diagnostic detail | Binding-specific errors | Immutable complete Diagnostic |
The deprecated binding's missing atoms parameter does not mean that its engine
cannot handle constants: that Python registration method simply does not expose
the vocabulary parameter. Python makes it explicit, as explained under
domain definition.
The old binding is not shipped in 0.10.0. Keeping the same import is not a complete migration: review buffering, symbol ownership, method names and lifetimes.
Lifecycle and configuration notes
Engine and domain
Engine() / engine.limits— Create a thread-confined Python owner and read the loaded native capacities.Predicate(name, arity, flags)— Declare a relation; combine kinds using PRED_EDB, PRED_IDB, PRED_QUERY and PRED_POLICY_FACT.engine.register_domain(name, predicates, atoms=())— Registers the domain’s predicate vocabulary and optional policy-source atoms before policies are loaded against it. It does not load or evaluate a policy.engine.load_inline_ruleset(domain, policy_id, source)— Loads one policy directly from Datalog source text against a registered domain, without reading a manifest.engine.load_manifest(path, allow_test_only=False, allow_undeclared_policy_atoms=False)— Loads a policy set from a manifest file, applying its source-hash checks, domain validation and public query permissions.engine.close() / with Engine()— Closes this Python owner and its native children. It does not unregister domains from the global registry.
Ruleset and EDB buffer
ruleset.policy_count / ruleset.fingerprint— Read policy-set metadata; evaluation selects a zero-based policy_index.ruleset.edb()— Creates an empty input buffer associated with this ruleset. Fill it with runtime facts before solving a request.edb.add_fact(predicate, terms)— Appends one typed input fact, copying its text values into native storage. This call does not evaluate the policy.edb.add_facts(iterable)— Appends a batch of input facts atomically: if validation or storage fails, none of this batch is added. Earlier successful additions are retained.len(edb) / edb.clear()— Count stored entries before deduplication / discard an unsolved buffer; clear is rejected after successful solve.edb.close()— Releases native input storage. Results already produced from this buffer remain valid.ruleset.solve(edb, policy_index=0, required_capabilities=0, work_limit=0)— Evaluates one complete input batch using a private session created for this call. Use prepare() when the same session should be reused for multiple requests.ruleset.prepare(policy_index=0, required_capabilities=0, work_limit=0)— Prepares one selected policy for reuse across requests, with the chosen session options. Preparation does not yet supply facts or compute an answer.ruleset.close() / with ruleset— Closes the loaded policy set and its dependent Python resources when the application has finished using them.edb.reset()— Starts a new, empty input batch in the same buffer, including after a successful solve. It does not release the session’s previous result.
Prepared Session
session.solve(edb)— Evaluates a complete input batch using this prepared session. Release its previous result before solving another request; facts are not implicitly inherited. Ordinary solving is unavailable while retained input is attached.session.fingerprint— Identity of selected policy authority.session.execution_fingerprint— Identity also binding backend, execution requirements/budget setting and size profile.Capability / required_capabilities— IntFlag values combined with | to require backend features at session preparation. Operators used by a compiled policy are detected automatically. AGGREGATES means count only; MIN, MAX and SUM are independent. WORK_LIMIT is unsupported by the reference backend.work_limit— Prepares one selected policy for reuse across requests, with the chosen session options. Preparation does not yet supply facts or compute an answer.session.close() / with session— Closes the prepared session, its active Python result and any attached retained input.ExplanationKind— IntFlag selecting optional reusable session explanation storage. TRUE | FALSE uses one shared workspace, not two. Zero reserves none; when a workspace is selected, requesting an omitted kind is rejected without allocating a fallback.
SolveResult and raw terms
result.contains_fact(predicate, terms)— Checks whether one fully specified fact is present in the existing result. It does not solve the policy again.result.enumerate_predicate_facts(predicate, arity)— Lists a query-enabled derived relation as ordinary Python values copied from the result.result.enumerate_raw(predicate, arity)— Lists a derived relation as typed ResultTerm records, keeping symbols as IDs local to this live result.term.kind / term.value— Inspect the raw kind/value. Symbol IDs are local to one result, not reusable inputs.term.resolve() / result.resolve_term(term)— Resolves this raw term through its owning result to obtain the corresponding Python value.result.explain_true(predicate, terms)— Explains a derivation of the requested fact as a bounded Why-true document, using the existing solve result.result.explain_false(predicate, terms)— Investigates obstacles to deriving an absent fact and produces a bounded Why-false document. It is not an exhaustive proof of all possible obstructions.result.derived_fact_count()— Reads how many facts were derived during this solve, without enumerating the model or deriving more facts.result.fingerprint / result.execution_fingerprint— The policy and execution identities of the owning Session.result.close() / with result— Releases this result, including any private session created by Ruleset.solve(). An explicitly prepared session remains available for another request.
Exceptions
MaelysDatalogError.status / .code— Native facade return status; code is an alias, not the diagnostic reason.error.message / error.hint— Human-readable detail, not a stable grammar to parse.error.diagnostic— Immutable source/code/phase/line/column/message/hint record. Fields are empty/zero when unavailable.TypeError / ValueError / OverflowError— Caller representation errors, distinct from native solve rejection.RuntimeError— Lifecycle misuse such as wrong thread, closed owner or reusing a Session with a live result.