Python

Ruleset

Ruleset class and public members in the unified Python API.

Class: Ruleset

Python · classSince v0.10.0
Ruleset
Loaded policy-set owner. Close it explicitly or with a context manager.
Creation and access

Internal constructor — do not call. Native policy resource returned by Engine loaders; do not manufacture native handles.

  • returned by
    Engine.load_inline_ruleset()

    Loads one policy directly from Datalog source text against a registered domain, without reading a manifest.

  • returned by
    Engine.load_manifest()

    Loads a policy set from a manifest file, applying its source-hash checks, domain validation and public query permissions.

Attributes
policy_countintreadonly property
Number of loaded policies; valid indices run from 0 to count minus 1.
fingerprintstrreadonly property
Identity of the whole loaded policy set, not a hash of request facts.
Methods
  • Ruleset.close()Closes the loaded policy set and its dependent Python resources when the application has finished using them.
  • Ruleset.edb()Creates an empty input buffer associated with this ruleset. Fill it with runtime facts before solving a request.
  • Ruleset.prepare()Prepares one selected policy for reuse across requests, with the chosen session options. Preparation does not yet supply facts or compute an answer.
  • Ruleset.program_counts()Read compiled predicate, policy-fact and normalized-rule counts for one policy.
  • Ruleset.reads_predicate()Checks whether the selected compiled policy reads a named predicate in its rule body, without preparing a session.
  • Ruleset.solve()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.
Protocols
  • with ruleset:Leaving the block closes this Ruleset and its sessions, results and input buffers.
Example
print("policies:", ruleset.policy_count)
print("fingerprint:", ruleset.fingerprint)
policies: 1
fingerprint: 4dca17fe86e7af4535ed3b9c718bfb545d8a748feb9ea5ea6ac3c5f541c0b514

Methods

Each method has its own signature, arguments, return behavior and stable link.

Ruleset.close

Close the ruleset when none of its sessions, results or input buffers are needed. Its children are closed first.

Python · methodSince v0.10.0
Ruleset.close
Ruleset.close() -> None
Closes the loaded policy set and its dependent Python resources when the application has finished using them.
Return value
None

Returns None after releasing the ruleset and remaining native children. Repeated closure is harmless; those children cannot subsequently be used.

Example
ruleset.close()

Ruleset.edb

Keep request facts separate from the compiled policy. Optional capacities reserve bounded input storage; they do not change solver limits.

Python · methodSince v0.10.0
Ruleset.edb
Ruleset.edb(
*,
fact_capacity: int | None = None,
text_capacity: int | None = None
) -> Edb
Creates an empty input buffer associated with this ruleset. Fill it with runtime facts before solving a request.
Arguments
fact_capacityint | None
Maximum stored input entries, before deduplication. None selects engine.limits.max_edb_facts.
text_capacityint | None
Native text-storage budget in bytes. None selects engine.limits.input_edb_text_bytes.
Return value
Edb

Returns a new, empty Edb associated with this Ruleset. Invalid capacities raise TypeError or ValueError; native creation failures raise MaelysDatalogError.

Example
edb = ruleset.edb()
edb.add_fact("owns", ["alice", "roadmap.pdf"])
print("facts:", len(edb))

Ruleset.prepare

Prepare one selected policy once, then evaluate successive complete requests. Optional explanation storage is reserved here, not during policy loading.

Python · methodSince v0.10.0
Ruleset.prepare
Ruleset.prepare(
policy_index: int = 0,
*,
required_capabilities: int = 0,
work_limit: int = 0,
explanations: ExplanationKind | int = 0,
capacities: SessionCapacities | None = None
) -> Session
Prepares one selected policy for reuse across requests, with the chosen session options. Preparation does not yet supply facts or compute an answer.
Arguments
policy_indexint
Zero-based index in this loaded policy set. Default: 0. Out-of-range indices raise IndexError.
required_capabilitiesint
Capability bitmask required of the backend, not a switch that enables language operators. Default: 0.
work_limitint
Unsigned 64-bit budget setting. Default: 0. The current reference backend rejects nonzero budgets with UNSUPPORTED.
explanationsExplanationKind | int
ExplanationKind mask for a reusable native workspace. Default: 0, no reserved explanation workspace. TRUE | FALSE shares one workspace.
capacitiesSessionCapacities | None
Optional fixed E/D/S/T quotas; None uses SDK defaults, zero requests an exact quota.
Return value
Session

Returns a new Session without solving any facts. Invalid options raise Python exceptions; unsupported backend requirements raise MaelysDatalogError. One session may retain only one live result.

Example
from maelys_datalog import ExplanationKind

with ruleset.prepare(
    explanations=ExplanationKind.TRUE | ExplanationKind.FALSE,
) as session:
    with session.solve(edb) as result:
        print(result.contains_fact("allow", ["alice", "roadmap.pdf"]))

Ruleset.program_counts

Read counts for one enabled policy without preparing a session. This is introspection of the loaded program, not a request EDB or solve result.

Python · methodSince v0.16.0
Ruleset.program_counts
Ruleset.program_counts(
policy_index: int = 0
) -> ProgramCounts
Read compiled predicate, policy-fact and normalized-rule counts for one policy.
Arguments
policy_indexint
Zero-based enabled policy index; defaults to 0.
Return value
ProgramCounts

Returns an immutable ProgramCounts. An invalid index raises IndexError, a non-integer index raises TypeError, and a closed owner raises RuntimeError.

Example
counts = ruleset.program_counts(0)
print(counts)
ProgramCounts(predicates=4, facts=0, rules=1)

Ruleset.reads_predicate

Python · methodSince v0.25.0
Ruleset.reads_predicate
Ruleset.reads_predicate(
name: str,
arity: int,
policy_index: int = 0
) -> bool
Checks whether the selected compiled policy reads a named predicate in its rule body, without preparing a session.
Arguments
namestr
Predicate name to inspect.
arityint
Number of arguments in that predicate.
policy_indexint
Zero-based index of an enabled policy; defaults to the first policy.
Return value
bool

Returns True for a body read, including a negated atom or aggregate source, and False otherwise. Rule heads and static facts do not count. Invalid integer types raise TypeError; negative values raise ValueError; an out-of-range policy index raises IndexError; a closed ruleset raises RuntimeError.

Example
reads = ruleset.reads_predicate("owns", 2)
print("reads owns/2:", "yes" if reads else "no")

Ruleset.solve

Choose this convenience method for an independent evaluation. For successive requests that share prepared memory, use Ruleset.prepare() instead.

Python · methodSince v0.10.0
Ruleset.solve
Ruleset.solve(
edb: Edb,
*,
policy_index: int = 0,
required_capabilities: int = 0,
work_limit: int = 0,
explanations: ExplanationKind | int = 0,
capacities: SessionCapacities | None = None
) -> SolveResult
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.
Arguments
edbEdb
Open input Edb belonging to this same Ruleset; the entire stored batch is evaluated.
policy_indexint
Zero-based index in this loaded policy set. Default: 0. Out-of-range indices raise IndexError.
required_capabilitiesint
Capability bitmask required of the backend, not a switch that enables language operators. Default: 0.
work_limitint
Unsigned 64-bit budget setting. Default: 0. The current reference backend rejects nonzero budgets with UNSUPPORTED.
explanationsExplanationKind | int
ExplanationKind mask for a reusable native workspace. Default: 0, no reserved explanation workspace. TRUE | FALSE shares one workspace.
capacitiesSessionCapacities | None
Optional fixed E/D/S/T quotas; None uses SDK defaults, zero requests an exact quota.
Return value
SolveResult

Returns a SolveResult owning its private session. Closing the result closes that session. A failed solve raises and publishes no partial result; successful solving freezes the Edb until reset().

Example
with ruleset.solve(edb, policy_index=0) as result:
    print(result.contains_fact("allow", ["alice", "roadmap.pdf"]))

Protocols

with ruleset:

Python · protocolSince v0.10.0
with ruleset:
Leaving the block closes this Ruleset and its sessions, results and input buffers.
Behavior

Exiting the context delegates to close(), including on exceptional exit. Cleanup does not suppress the exception.

Example
with engine.load_inline_ruleset(domain, policy_id, source) as ruleset:
    print("policies:", ruleset.policy_count)
    print("fingerprint:", ruleset.fingerprint)
policies: 1
fingerprint: 154259eb7775622e9770eedddb331661f2d7751f5afe8a49db220e2940851d8b
Explicit form

Perform the same operations with explicit cleanup in a finally block.

ruleset = engine.load_inline_ruleset(domain, policy_id, source)
try:
    print("policies:", ruleset.policy_count)
    print("fingerprint:", ruleset.fingerprint)
finally:
    ruleset.close()
policies: 1
fingerprint: 154259eb7775622e9770eedddb331661f2d7751f5afe8a49db220e2940851d8b

Usage guides