Most graph databases ask you to make a quiet compromise on day one: some things in your domain are first-class citizens, and others are not.

In RDF, a statement (a triple) has no identity of its own unless you reify it into four separate triples or quote it using RDF-star. Named graphs give you a fourth position for grouping or provenance, but not a fifth. In property graphs (such as Neo4j), edges can carry key-value properties, yet an edge cannot be the subject or target of another edge. In TypeDB, relations and roles are carefully typed, but the connection between a role and its player—or the ownership of an attribute—has no independent identity.

For simple, flat, node-and-edge workloads, these compromises are easy to ignore. But the moment an application needs to reason about its own statements—Who asserted that Alice owns the car? Under which schema is that ownership valid? Which stored queries depend on the type owns?—the underlying model pushes back. Developers are forced to invent encoding workarounds, bolt on external schema languages, and manage queries as opaque strings outside the database.

Metastrudel, a working paper and mechanized Lean 4 / Rust prototype, takes a different route. Instead of patching reification, schemas, and query languages onto an existing graph model, it rebuilds the stack around a single typed metagraph and a homoiconic language.

1. Why Existing Graph Languages Hit a Wall

The fragmentation in today’s graph ecosystem comes down to three structural gaps that no amount of syntactic sugar can fully hide:

  1. 1.

    Second-class connections: When edges, role-player links, or attribute ownerships lack first-class identity, you cannot attach provenance, bitemporal intervals, or metadata directly to them. Every time you need to talk about a relationship, you have to promote it into a synthetic intermediate node, polluting your domain model.

  2. 2.

    Schemas and queries as outsiders: Almost everywhere, schemas live in a separate DDL language outside the data they constrain, and queries live in application code outside the store. You cannot query your own schema as ordinary data, nor can you ask the database which stored queries touch a specific type.

  3. 3.

    The dependent-typing dilemma: In type theory, a dependent type is a type indexed by a term. In a database, full value-dependent typing—allowing types to depend on arbitrary predicates over the graph—makes write-time checking undecidable and commit latency unpredictable. Yet without some form of dependency, schemas cannot be generic (such as parameterizing a Team signature over an Agent type) or constrain scalar values cleanly.

To close these gaps without turning the database into an untyped soup of identifiers, we need a language and data model where elements, links, contexts, schemas, and queries all inhabit the same graph, governed by a decidable type discipline.

2. The Metastrudel Kernel: Two Shapes, One Graph

Metastrudel starts from a minimalist two-shape kernel. Every stored item is an Element record:

An element takes one of two shapes:

  • Atom (link = ⊥): Pure identity. Everything said about an atom is expressed through links.

  • Link (link = (s, o)): A directed connection from a subject element ID s to a Term o, which is either an element reference ref(x) or a primitive value val(v).

Because a link’s subject s is an element ID, links can be the subjects of other links. Roles, attributes, and context memberships are not separate kernel constructs—they are simply link types. Every subject chain, however deep, must terminate at an atom.

Primitive values—Bool, Int, Dec, Str, Bytes, Time, Duration, and Iri—have no identity of their own and appear only as link objects. Structured values (such as Money) are modeled as content-addressed atoms with attribute links.

3. Contexts, Provenance, and Three-Layer Stratification

If links can point to links and schemas live inside the graph, what prevents circularity and infinite regress? Metastrudel solves this with two structural rules:

Contexts as Frames of Provenance and Membership

Every element has exactly one immutable home context: the context in which it was asserted (who said it). Homes never change, so provenance is permanent, and they form a tree rooted at the prelude context Root (which is its own home).

An element x is a member of context M if M is its home, or if a live Membership link connects M to x. Moving an element between contexts never mutates the element; it simply asserts or retracts a Membership link. Membership is non-transitive, and Root is not a global view (the global view is a query scope, All, not a context).

Fixed Three-Layer Stratification

Every element belongs to exactly one of three named layers:

  1. 1.

    Meta: A fixed bootstrap prelude of 37 elements with reserved IDs (Root, base types, Membership, sub_of, refines, domain, range, card, key, conforms_to, extends, succeeds, the eight primitives, and five refinement-predicate link types). Meta is axiomatic: the kernel implements it, nothing types it, and no client link may have a Meta element as its subject.

  2. 2.

    Schema: Atoms whose declared type is Type, LinkType, Role, Attribute, Signature, or Parameter (along with links whose subjects are in Schema). Stored queries also live here.

  3. 3.

    Data: Atoms whose declared type is Node, Edge, Context, or a Schema-layer element.

Outside Meta, an element’s declared type must always live in a strictly higher layer than the element it classifies. Because type parameters range over Schema types only, three fixed layers suffice—avoiding the complexity of universe polymorphism in v1.

4. Bitemporality and Content Addressing

Metastrudel is strictly immutable. assert creates an element, and retract closes its transaction interval (tx); there is no in-place update. Changing a value means retracting a link and asserting a new one.

Crucially, "live" means recorded (an open transaction interval), not valid at wall-clock time. If liveness depended on valid time, a graph could silently become ill-formed between commits without any write occurring. Transaction time is assigned monotonically by the store, while valid time belongs to the client.

For identity, a type can carry key marks—links from a type to a link type declaring that those links are part of an instance's identity. Instances of key-marked types are content-addressed using BLAKE3 hashes over their home, type, and key links (recursively). Two €5 Money atoms in the same context collapse into one atom. Rather than assuming a 128-bit hash is injective, Metastrudel tags content IDs and explicitly checks for id-collision as a decidable kernel invariant.

5. Taming Dependent Types for a Database

Metastrudel’s central type-theoretic contribution is its disciplined answer to what "dependently typed" should mean for a database. Typing is always context-relative:

("Element x has type T inside context M.")

A context is open by default—judged only by kernel invariants—and becomes closed when it carries a conforms_to link to a Signature. A Signature is itself a context whose members are types, link types, parameters, and rules (domain, range, card). Crucially, rules bind only the signature that is their home, allowing two signatures to share a link type like owner while imposing different domain constraints on it.

Dependency is restricted to two decidable mechanisms:

  1. 1.

    Parameterized signatures: A signature such as Team(Agent) declares type parameters (Agent : Parameter, where Parameter < LinkType). Each conforms_to link carries bindings—links whose subject is the conforms_to link itself and whose type is the parameter—resolving Agent to a concrete type like Person inside team42.

  2. 2.

    Refinement types: Scalar types can narrow the eight closed primitives using decidable predicates: min_value, max_value, one_of, length, and pattern (a project-defined regex dialect matched via Antimirov partial derivatives).

Because there is no type-level computation and no arbitrary graph predicates on the write path, commit-time checking (FastChecker) is total and bounded. On each commit, FastChecker computes only the affected contexts and signatures touched by the delta, keeping commit cost proportional to the affected scope rather than the size of the entire database.

6. Homoiconic Queries and Dual-Engine Reasoning

If schemas and rules are Schema-layer data, queries should be too. The Metastrudel DSL uses λProlog syntax over the store’s vocabulary, with Datalog as a native fragment rather than a separate language.

Every query is stored as a content-addressed metagraph using two atom forms:

  • q:Match: A five-slot element pattern (id, home, type, subject, object) that maps directly onto a store scan.

  • q:Call: Invokes a rule-defined predicate with positional q:arg links.

Variable IDs are derived from binding position (de Bruijn-style), so α-equivalent queries hash to the same ID and deduplicate automatically. Because stored queries are data, asking "which queries touch type owns?" is an ordinary query.

Scoping in queries mirrors scoping in the type system: a scoped query M |- G is λProlog’s hypothetical implication (facts_of M => G), meaning "assume the members of M as facts, then prove G." Negation is stratified negation-as-failure over a bitemporal snapshot.

To balance expressiveness and performance, the planned query runtime routes predicates per strongly connected component (SCC) of the predicate dependency graph:

  • Datalog-fragment components run bottom-up on a native semi-naive, stratified Datalog engine.

  • Richer logic rules run top-down on lean-elpi (a λProlog implementation in Lean 4) under a budget. For rules written as LF checking predicates, lean-elpi can export proof terms checked directly by the Lean kernel, turning solver verdicts into certified verdicts without trusting the solver itself.

7. Proof-First Engineering and Current Status

What separates Metastrudel from typical database proposals is its specification discipline. Lean 4, not prose, is the normative source of truth. Every kernel and typing rule is written three times in one place:

  1. 1.

    As a Prop (what it means),

  2. 2.

    As a Bool decision function (how it is checked), and

  3. 3.

    As a *_check_iff theorem proving they agree.

Axioms.lean is kept strictly empty, and an executable reference (metastrudel-ref) generates JSON test vectors used to differentially test the Rust implementation.

At the time of the working paper, milestones M0 (Kernel) and M1 (Typing) are implemented across roughly 9,700 lines of Lean (279 theorems, zero axioms, and 4 tracked sorrys—including the locality lemma affected_complete) and 14,600 lines of Rust, validated by 264 test vectors. Milestones M2–M6 (query codec, query engine, reasoning, persistence, and certified checking) are specified as designs, and v1 targets a single-process store without distributed replication or performance benchmarks yet.

Conclusion

Metastrudel demonstrates that a metagraph database does not have to sacrifice type safety for generality. By making every connection an element, treating contexts as frames of typing, storing schemas and queries as content-addressed data, and bounding dependent typing to parameterized signatures and decidable refinements, it offers a cohesive blueprint for provenance-heavy knowledge graphs and AI agent memories—backed by a mechanized Lean 4 kernel.