graphlava

Chapter 9

Fold, unfold and reasoning

A metagraph is useful when you can move between levels: see a meeting as one thing, then open it; see an episode as one node, then read what is in it; derive a new fact from several. This chapter does both with reads, writes and Datalog rules.

Fold and unfold, again

The two operations from chapter 3, in the sense used in Metagraph for AI Agents (Goertzel's paper treats fold and unfold more generally, as recursion schemes over metagraphs): fold collapses a subgraph into one vertex, unfold opens a vertex into its subgraph. In a statement graph there are three things that fold, and each already has an unfold.

Folded vertexWhat it stands forUnfold in graphlava
hyperedge e1its role triples and literal attributes?e a :Meeting ; :agent ?a ; :target ?t ; :when ?w, roles from one record, :when from its property record
graph :session7its statementsGRAPH! :session7 { ?s ?p ?o }
graph :aliceMemoryits statements and nested graphsGRAPH :aliceMemory { ?s ?p ?o }, the whole scope

The difference between GRAPH! and GRAPH is the difference between unfolding one level and unfolding all the way down.

Folding is a write that copies nothing

Folding graphs

The cleanest fold works on whole graphs. Say the agent wants one view of everything about pricing. The episodes already exist; folding them is one nesting statement each:

(:session7,  :in, :pricingProject)
(:session12, :in, :pricingProject)
(:pricingProject, :summary, "Pricing talks with Bob, November 2026")

Nothing is copied. Every statement in both sessions is now in the scope of :pricingProject, and the episodes stay where they were. The fold has its own description, so the agent can reason at the folded level ("there is a pricing project") without reading the parts. Unfolding it is one scoped query:

SELECT ?s ?p ?o WHERE { GRAPH :pricingProject { ?s ?p ?o } }

Undoing the fold deletes the two nesting statements. The in_star closure is updated in the same transaction. It stores a set of pairs, not path counts (ADR 0029): removing a link recomputes the ancestors below it, so a session that is still reachable another way keeps its other ancestors.

Folding single statements

To fold a few statements out of a larger graph, give each an extra membership in the new graph: one gmem entry per statement, no copy, and the statement keeps its ID and annotations. Since ADR 0024 this is plain SPARQL: inserting an existing triple into another graph adds a membership instead of a second statement.

# fold every statement tagged as being about pricing into :pricingFacts
INSERT { GRAPH :pricingFacts { ?s ?p ?o } }
WHERE  { << ?s ?p ?o ~ ?id >> . ?id :topic :pricing }

Unfolding back is a DELETE inside GRAPH :pricingFacts: it removes only that membership, and the statements stay in their own episodes.

Datalog sees the metagraph

graphlava's Datalog uses Nemo's syntax, and it sees the same relations SPARQL sees. Besides :p(?x, ?y) as shorthand for a triple, a program can use the store relations directly:

RelationColumnsMetagraph kind
triple(?s, ?p, ?o, ?id)a statement and its IDedges as vertices
prop(?n, ?p, ?v, ?id)an inline property; ID or 0 if not promotedliteral annotations
role(?e, ?r, ?n)a hyperedge role fillerhyperedges
in(?x, ?g)direct membershipcontainers
in_star(?x, ?g)membership in the scopenested containers

The running example's rule

@prefix : <http://example.org/> .
colleague(?x, ?y) :- :worksAt(?x, ?o), :worksAt(?y, ?o), ?x != ?y .
?- colleague(:alice, ?who) .

With :alice bound, the magic-sets rewrite starts the evaluation from Alice's employers only, instead of computing every colleague pair and filtering.

Rules over every layer

# a fact counts as known if it has a confidence above 0.8
known(?s, ?o) :- triple(?s, :worksAt, ?o, ?id), prop(?id, :confidence, ?c, ?pid), ?c > 0.8 .

# who met whom, read straight from hyperedge roles
met(?a, ?b) :- role(?e, :agent, ?a), role(?e, :target, ?b) .

# only facts that sit somewhere in Alice's memory
remembered(?s, ?o) :- triple(?s, :worksAt, ?o, ?id), in_star(?id, :aliceMemory) .

# how many meetings each person called
called(?a, #count(?e)) :- role(?e, :agent, ?a) .

# people Alice met but has no colleague link with (stratified negation)
outside(?b) :- met(:alice, ?b), ~colleague(:alice, ?b) .

Each rule mixes structure from different chapters: annotations (chapter 6), hyperedges (chapter 5), containers (chapter 7). Negation and aggregation must be stratified: a rule may not depend on its own negation or aggregate through a cycle. A program that breaks this is rejected with the cycle named.

From SPARQL

A SPARQL query can call rules through a local service. Variables bound outside are passed in, so magic sets apply here too:

PREFIX : <http://example.org/>
SELECT ?who WHERE {
  SERVICE <meta:datalog> {
    """ colleague(?x, ?y) :- :worksAt(?x, ?o), :worksAt(?y, ?o), ?x != ?y . """
    :alice :colleague ?who
  }
}

The service sees the same snapshot as the outer query. Inline rules are compiled for this query only; rules stored with define (chapter 8) can be called by their head IRI without the program text.

On demand or materialized

ModeHow it runsWhen
@on_demand (default)per query: magic sets from bound arguments, then semi-naive evaluation to a fixpoint; nothing storedv0; any predicate
@materializedkept current at commit: counting for non-recursive rules, Backward/Forward for recursive ones (a fact that may lose support is checked for another derivation before it is deleted), under a per-transaction budgetv1; only over stable, node-valued predicates

The restriction on @materialized comes from the workload. Agent memory overwrites values constantly, and maintaining a rule over a hot predicate could stall every write. So a rule over inline properties, or over a predicate with a high overwrite rate, is rejected for materialization unless forced. If maintenance goes over budget in a transaction, the rule is marked stale, the commit goes through, queries fall back to on-demand evaluation, and a background job rebuilds it. A stale rule gives correct answers, more slowly.

One rule is materialized from v0: in_star, the graph closure behind every scoped query. Whether built-in rules are exempt from the v0 on-demand-only limit is an open question, with "exempt" recommended.

Derived facts are statements, lazily

A derived fact, such as colleague(:alice, :bob), is visible as a statement but is not stored in the base orderings. Materialized results live in a separate derived table. Like the other virtual statements, a derived fact gets a statement ID only when something annotates it (ADR 0009). The agent can then say how it uses the conclusion, "Bob is a colleague, and I told Carol so", without derived data ever mixing with what was written directly.

Base facts can also be asserted from a program; the recommended marker is @assert, and the exact syntax is still open.

In graphlava. Hyperedges, graphs and scopes are folds that come with their unfold. Graph-level folding is a nesting write that copies nothing. Datalog reads statements with IDs, properties, roles, membership and scope as relations. Rules run on demand by default; materialized rules (v1) are limited to stable predicates and run under a budget.

Takeaways

Contents