A typed record registry for Nix with extension points, strict validation, refinement contracts, identity hashing, cross-instance references, first-class mixins, introspection, and declarative methods. Built on the pure-gen module system (gen-merge — a byte-mode replacement for lib.evalModules + lib.types), with no nixpkgs.lib dependency.
gen-schema gives you what lib.types.submodule doesn't: open kind definitions that any module can extend, strict-by-default validation that catches typos immediately, refinement contracts co-located with type declarations, stable identity comparison via id_hash, cross-registry references that resolve to instances, reusable mixins with structural compatibility, and auto-generated documentation from your schema.
Dependency class: pure-gen. gen-schema runs on the pure-gen stack — gen-prelude (the pure utility base), gen-merge (the byte-mode module engine that REPLACES lib.evalModules + lib.types), gen-algebra (the pure record algebra), gen-identity (the one minting authority) and gen-graph (the containment topology — _topology, _roots, _leaves — is its computation). It carries no nixpkgs.lib dependency; the constructor takes the five formals default.nix declares — prelude, merge, algebra, identity, graph — each auto-fetched from gen-schema's own lock (pass any explicitly to override). The module-system constructors it exports (identity hashing, strict rejection, validators) are gen-schema-owned — they relocated here from gen-algebra on 2026-06-26, leaving gen-algebra fully pure.
- Terminology
- Overview
- Gen Ecosystem
- Quick Start
- Use Cases
- Core Concepts
- Kinds
- Extension
- Base Module
- Default Propagation
- Strict Validation
- Instances
- Nested Registries
- Per-Kind Strict Override
- Identity Hashing
- Cross-Instance References
- Refs in Collections
- Custom Ref Coercion
- Deferred Coerce
- Deduplicated Sets
- Field Declarations (Values)
- Parent-Child Topology
- Schema Introspection
- Scope Graph Bridge
- Kind Inheritance
- Declarative Methods
- Collection Fields
- Computed Fields
- Introspection API
- Schema Validators
- Derive Hooks
- Documentation Generation
- Codec (Serialization)
- Refinement Contracts
- Blame
- Field Validators
- Mixins
- API Reference
- Architecture
- Demo
- Evaluator divergences (stated)
- Testing
- Theoretical Foundations
| Term | Definition |
|---|---|
| Kinds | Schema-level type declarations (deferred modules defining options and config) |
| Instances | Concrete values of a kind, evaluated through registries |
| Collections | Named multi-contributor aggregation points with a merge strategy |
| Refs | Cross-registry references between kinds (deferred or direct) |
| Edges | Parent (P) nesting and ref (I) import relationships, exposed via _edges introspection |
The mental model has two layers. A kind is a schema-level type — a deferred NixOS module declaring options, config defaults, methods, and collections. Kinds are open: any module (including one from a downstream flake input) can extend a kind by contributing more config.schema.<name> fragments, which merge through the module system. An instance is a concrete value of a kind, materialized through a registry (mkInstanceRegistry) that stamps each instance with a name, a stable id_hash, strict-key rejection, and any bound cross-instance references.
The authoring surface is small — most schemas are built from these constructors:
| Constructor | Role |
|---|---|
mkSchemaOption |
Declares the schema option (holds all kinds; carries strict, baseModule, collections, computed settings) |
mkInstanceRegistry |
Turns a kind into an attrsOf registry of instances, with refs, derive, and validator pipeline |
mkInstanceType |
The single-instance submodule type (identity + strict injected), used by registries |
declarationOf / setOf / toSet |
Cross-instance references (deferred or direct) and identity-deduplicated collections |
schemaFn |
Declarative methods on a kind, with named args auto-resolved from instance config |
mkValidator / mkFieldValidator |
Cross-field constraints that travel with a kind and fire on every registry |
refined / blame / mkMixin |
Refinement contracts, blame records, and first-class mixin fragments |
mkCodec / renderDocs |
Serialization round-trips and markdown reference generation |
Everything above the instance layer is pure schema — no validation or hashing happens at the kind level, which is what lets kinds compose via imports without duplicate-module conflicts. Instances are where the infrastructure (strict rejection, id_hash, ref binding, derive) is injected. Registries expose flat _-prefixed introspection (_kindNames, _topology, _edges, _refEdges, _roots, _leaves, _collectionKeys) that consumers read to build whatever graph format their evaluator needs.
| Library | Role |
|---|---|
| gen-prelude | Pure nixpkgs-lib-free utility base (builtins re-exports + vendored lib utils) |
| gen-algebra | Pure primitives (record, either, intensional identity) |
| gen-types | Clean-room MIT structural type checker (leaf/poly checkers; verify: v → null|err) |
| gen-merge | Byte-mode module merge engine (evalModuleTree, byte-identical to nixpkgs lib.evalModules over the priority subset) |
| gen-schema | This lib — Typed registries (kinds, instances, collections, refs); re-hosted on gen-merge |
| gen-aspects | Aspect type system (traits, classification, dispatch); re-hosted on gen-merge |
| gen-scope | HOAG scope-graph evaluator (demand-driven, _eval memoization, circular attributes) |
| gen-graph | Accessor-based graph query combinators (traversal, condensation, phaseOrder) |
| gen-select | Selector algebra (pattern matching over graph positions) |
| gen-bind | Module binding (inject external args into NixOS modules) |
| gen-dispatch | Relational rule dispatch STEP (stratified phases, conflict resolution) |
| gen-memo | The incremental plane — decides reuse, never evaluates (change propagation, AFFECTED set) |
| gen-vars | Pure-Nix vars/secrets (den-agnostic) |
# flake.nix
{
inputs.gen-schema.url = "github:sini/gen-schema";
inputs.flake-parts.url = "github:hercules-ci/flake-parts";
outputs = inputs: inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [ inputs.gen-schema.flakeModules.default ];
# Define a kind
schema.host = {
options.addr = lib.mkOption { type = lib.types.str; };
options.role = lib.mkOption { type = lib.types.str; default = "worker"; };
};
# Create a registry and instances
options.hosts = genSchema.mkInstanceRegistry {} config.schema.host;
hosts.igloo = { addr = "10.0.1.1"; role = "web"; };
hosts.iceberg = { addr = "10.0.2.1"; }; # role defaults to "worker"
# Use them
flake.fleet = {
iglooAddr = config.hosts.igloo.addr; # → "10.0.1.1"
iglooHash = config.hosts.igloo.id_hash; # → "host:<deterministic SHA-256>"
};
};
}The flake-parts module provides schema and genSchema with default settings (strict = true, no baseModule). For custom strict, baseModule, collections, or computed settings, use the programmatic API instead.
# Without flake-parts — call the library directly. The module-system `lib` is gen-merge
# (it REPLACES lib.evalModules + lib.types); gen-schema itself is `gen-schema.lib`.
# Module-system vocabulary comes from gen-merge, reached through the hub as `gen.lib.merge` —
# gen-schema does not carry a copy of it. You still never reach for nixpkgs `lib`; the promise
# is unchanged and only the path is. A verbatim copy would be a SECOND build of the same names,
# and two gen libraries at different pins would then disagree on a type's identity while
# agreeing on its name — the boundary is the eval, not the repo.
let
genSchema = gen-schema.lib;
merge = gen-merge.lib; # evalModuleTree + mkOption + types — the pure-gen module system
in
merge.evalModuleTree { } [{
options.schema = genSchema.mkSchemaOption {};
config.schema.host.options.addr = merge.mkOption { type = merge.types.str; };
}]let
# the root default.nix auto-fetches gen-prelude/gen-merge/gen-algebra/gen-identity from gen-schema's own
# flake.lock (content-addressed, in lockstep with the flake output). Pass { prelude; merge; algebra; identity; }
# to override — e.g. local checkouts.
genSchema = import ./path/to/gen-schema { };
in
# use genSchema.mkSchemaOption, genSchema.mkInstanceRegistry, etc.A base application defines its schema. Plugins extend it from external flake inputs without touching the base:
# Base app — defines the plugin kind
config.schema.plugin = {
options.enabled = lib.mkOption { type = lib.types.bool; default = true; };
options.priority = lib.mkOption { type = lib.types.int; default = 50; };
};
# Logging plugin (separate flake input) — extends the kind
config.schema.plugin.options.logLevel = lib.mkOption {
type = lib.types.enum [ "debug" "info" "warn" "error" ];
default = "info";
};
# Metrics plugin (another flake input) — extends the same kind
config.schema.plugin.options.metricsEndpoint = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
};
# Instances — validated against the merged schema from all inputs
config.plugins.logging = { logLevel = "debug"; priority = 10; };
config.plugins.metrics = { metricsEndpoint = "/metrics"; };
config.plugins.logging.badOption = "x"; # → STRICT MODE error with fix guidanceconfig.schema.service = {
options.port = lib.mkOption { type = lib.types.int; };
options.protocol = lib.mkOption { type = lib.types.str; default = "http"; };
options.healthPath = lib.mkOption { type = lib.types.str; default = "/health"; };
};
# Services can reference each other (direct ref — registry in scope)
options.services = genSchema.mkInstanceRegistry {
extraModules = [({ ... }: {
options.upstream = lib.mkOption {
type = lib.types.nullOr (genSchema.declarationOf config.services);
default = null;
description = "Upstream service this proxies to";
};
})];
} config.schema.service;
config.services.api = { port = 8080; };
config.services.gateway = { port = 443; upstream = "api"; };
# Ref resolves to the full instance — accepts string keys or instance values:
config.services.gateway.upstream.port # → 8080config.schema.namespace = {
options.labels = lib.mkOption { type = lib.types.attrsOf lib.types.str; default = {}; };
};
config.schema.deployment = {
options.replicas = lib.mkOption { type = lib.types.int; default = 1; };
options.image = lib.mkOption { type = lib.types.str; };
options.containerPort = lib.mkOption { type = lib.types.int; };
};
config.schema.service = {
options.port = lib.mkOption { type = lib.types.int; };
options.targetPort = lib.mkOption { type = lib.types.int; };
};
# Deployments reference their namespace (deferred ref on kind + binding)
config.schema.deployment.options.namespace = lib.mkOption {
type = genSchema.declarationOf "namespace";
};
options.deployments = genSchema.mkInstanceRegistry {
refs.namespace = config.namespaces;
} config.schema.deployment;
config.namespaces.production = { labels.env = "prod"; };
config.deployments.api = {
namespace = "production"; # → resolves to the namespace instance
image = "myapp:v1.2.3";
replicas = 3;
containerPort = 8080;
};
config.deployments.api.namespace.labels.env # → "prod"# Shared base for all entity types
options.schema = genSchema.mkSchemaOption {
baseModule.options.tags = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [];
};
};
config.schema.host = {
options.ip = lib.mkOption { type = lib.types.str; };
options.os = lib.mkOption { type = lib.types.str; default = "nixos"; };
methods.sshCmd = genSchema.schemaFn
{ description = "SSH command for this host"; type = lib.types.str; fn = { name, ip, ... }: "ssh root@${ip} # ${name}"; };
};
config.schema.network = {
options.cidr = lib.mkOption { type = lib.types.str; };
options.gateway = lib.mkOption { type = lib.types.str; };
};
# Hosts reference their network (deferred ref)
config.schema.host.options.network = lib.mkOption {
type = genSchema.declarationOf "network";
};
options.hosts = genSchema.mkInstanceRegistry {
refs.network = config.networks;
} config.schema.host;
options.networks = genSchema.mkInstanceRegistry {} config.schema.network;
config.networks.lan = { cidr = "10.0.1.0/24"; gateway = "10.0.1.1"; };
config.hosts.nas = {
ip = "10.0.1.10";
network = "lan";
tags = [ "storage" "backup" ];
};
config.hosts.nas.sshCmd # → "ssh [email protected] # nas"
config.hosts.nas.network.cidr # → "10.0.1.0/24"
config.hosts.nas.tags # → [ "storage" "backup" ] (from baseModule)A kind is a named record type. Declare one by setting config.schema.<name>:
config.schema.host = {
options.addr = lib.mkOption { type = lib.types.str; };
options.system = lib.mkOption { type = lib.types.str; };
options.role = lib.mkOption { type = lib.types.str; };
config.system = lib.mkDefault "x86_64-linux";
};Kinds are deferred modules — they define options and config but aren't evaluated until imported by an instance.
Kind names starting with _ are reserved for internal use (_kindNames, _topology, etc.). Declaring one evaluates — config.schema._hidden.kind reads "_hidden" — but every kind-derived read (_kindNames, _topology, _refEdges, _edges, _roots, _leaves) refuses it by name.
Any module can extend any kind. Extensions merge through deferred module merge:
# Module A declares base host options
config.schema.host.options.addr = lib.mkOption { type = str; };
# Module B (maybe from another flake input) adds monitoring fields
config.schema.host.options.metricsPort = lib.mkOption { type = int; default = 9100; };
config.schema.host.options.monitored = lib.mkOption { type = bool; default = true; };Both contributions merge cleanly. Neither module needs to know about the other.
A module injected into every kind automatically. Use it for options shared across all kinds without manual imports:
options.schema = genSchema.mkSchemaOption {
baseModule = {
options.description = lib.mkOption {
type = lib.types.str;
default = "";
description = "Human-readable description.";
};
};
};
# Every kind gets `description` for free:
config.fleet.hosts.igloo.description # → ""
config.fleet.users.tux.description # → ""baseModule is static — set at mkSchemaOption call time, not extensible by downstream modules. For extensible shared bases, use kind inheritance instead (a shared kind that others name in inherits).
Kind modules can set default config values. These flow through to every instance via deferred module merge:
config.schema.host = {
options.system = lib.mkOption { type = lib.types.str; };
config.system = lib.mkDefault "x86_64-linux";
};
config.fleet.hosts.igloo = {}; # system → "x86_64-linux"
config.fleet.hosts.mac.system = "aarch64-darwin"; # override worksThis is standard module-system priority behavior (gen-merge reproduces it byte-for-byte) — mkDefault sets a low-priority value that any explicit setting overrides.
Kinds are strict by default — undeclared keys error immediately, every one named at its path under the instance, with one fix suggestion each (a key that is not a bare Nix identifier prints quoted, so the fix parses as written):
STRICT MODE: "addrr", "net.mtuu" are not declared on host (instance at hosts.web, defined in /etc/nixos/hosts.nix).
Fix: schema.host.options.addrr = mkOption { ... };
Fix: schema.host.options.net.mtuu = mkOption { ... };
Opt out per-kind:
config.schema.host._module.freeformType = lib.types.attrsOf lib.types.anything;Or globally:
options.schema = genSchema.mkSchemaOption { strict = false; };Instances are concrete values of a kind. Create them with mkInstanceRegistry:
options.fleet.hosts = genSchema.mkInstanceRegistry {} config.schema.host;
config.fleet.hosts.igloo = {
addr = "10.0.1.1";
role = "web";
# system defaults to "x86_64-linux"
};
config.fleet.hosts.iceberg = {
addr = "10.0.2.1";
system = "aarch64-linux";
};Each instance:
- Gets a
nameoption defaulting to the attrset key - Gets
_module.args.<kind> = configfor self-reference - Gets
id_hash— a stable"<kind>:" + SHA-256for safe comparison - Inherits the kind's strict/freeform setting
Registries can nest inside instances via extraModules. This establishes parent-child relationships structurally:
# Capture the top-level schema before entering extraModules closures
let schema = config.schema;
in {
options.fleet.hosts = genSchema.mkInstanceRegistry {
extraModules = [({ config, ... }:
let hostConfig = config; # capture the host instance's config
in {
options.users = genSchema.mkInstanceRegistry {
extraModules = [
# Inject parent host into child user's module args
({ ... }: { config._module.args.host = hostConfig; })
];
} schema.user;
}
)];
} schema.host;
}
config.fleet.hosts.igloo = {
addr = "10.0.1.1";
users.tux.shell = "/bin/zsh";
users.deploy.shell = "/bin/sh";
};
# Child instances access their parent:
config.fleet.hosts.igloo.users.tux._module.args.host.addr # → "10.0.1.1"Note the scoping: schema is captured at the top level (before the extraModules closure), and hostConfig captures the host instance's config (before the nested extraModules closure). Without these captures, config inside the closures would shadow the outer config.
Cross-entity bindings (_module.args.host = hostConfig) are the consumer's responsibility via extraModules. The schema library doesn't impose nesting semantics — different consumers wire cross-entity context differently.
Individual registries can override the schema-level strict setting:
# Schema is strict by default
options.schema = genSchema.mkSchemaOption { strict = true; };
# But this specific registry allows freeform
options.fleet.configs = genSchema.mkInstanceRegistry {
strict = false;
} config.schema.config;Nix's == on module system values can diverge or infinitely recurse. id_hash gives you a cheap, stable string comparison:
# Safe entity comparison
builtins.filter (h: h.id_hash != host.id_hash) allHosts
# Set membership
lib.elem target.id_hash (map (h: h.id_hash) candidates)The identity is the kind tag joined to a digest of the identity pairs:
id_hash = "<kind>:" + sha256(<the ⟨key, value⟩ pairs plus ⟨_identity, the kind's mark⟩, as a JSON attrset>)
The kind enters the digest as one more pair, _identity, whose value is the kind's minted identity (__mint.minted), never its name. Two kinds that share a name but are different declarations — the ones kindEq calls distinct — therefore mint different identities for instances with equal values. The tag stays the kind's name, for display and for splitting on the first colon. What a relocation or a respelling of a kind preserves is the identity CONTENT: identityHashForKind oldKind newInstance == oldInstance.id_hash, over one _identityKeys set. The stamp itself follows kindEq. Migrating the deprecated imports spelling to inherits under evalSchema preserves the stamp too, because the spelling is already read as that inherits.
The stamp is defined only where the kind's mark is. The mark forces an option declaration's type and no other attribute of it (default, description, example, readOnly, apply, …), nor an option's kind-level value: written in a function module, each may read instance data (config.name, the instance's own id_hash on a non-key field) that the kind level does not have, and the function module is the sealed component that distinguishes it. Their presence enters instead, by path, as sealed components: a kind with a default and one without are distinct, and two kinds whose declarations differ only in such an attribute, or two separate constructions of one declaration carrying one, are refused by kindEq naming the open.* path. The path carries no module index, so the same content stated in another module or order is the same path; meta and every kind-level _module key but freeformType enter the same way. A kind value carried through gen-merge's types.anything is rebuilt, and comparing it with itself is then refused on nix and Determinate and true on Lix, never false. So a default reading an instance identity leaves the stamp well-founded. A component the mark does force that reads instance data has no mark, and demanding one aborts uncatchably. An instance's own non-key field reading its id_hash, and the self-referential mkInstanceRegistry config.schema.host idiom, are unaffected.
The pairs are all primitive options (str, int, bool, float) minus the declared opt-outs. internal = true is presentation only (hidden from generated docs) and does not exclude an option from identity; among primitive options identity = false is the one exclusion channel, and a non-primitive option is never a key. Two hosts with the same values hash identically. A host and a user with the same name hash differently — the tag separates them, so id_hash says what it is and the kind is recoverable by splitting on the first colon. Because the tag rides outside the digest, : is refused in a kind name; values are unconstrained, since JSON quotes and escapes them.
Order does not enter. The pairs are rendered as an attrset and attrsets carry no order, so a caller supplying keys in any order mints the same node — there is no sort for a caller to get wrong.
id_hash is marked internal = true and readOnly = true — it won't appear in NixOS option documentation generators, but is always accessible via instance.id_hash.
Method returns are never identity keys. A method is declared as a readOnly option so its return reaches config, but it is marked identity = false at that point: a method is an arbitrary function of config, so admitting its return would let a method reading an opted-out field re-admit that field, and would make declaring a method move an instance's identity.
Floats are admissible only for |v| < 2^53, strictly. Identity follows Nix's == in both directions, and above that bound == is not an equivalence relation — two distinct ints both compare equal to one float — so there is nothing for an encoding to be faithful to. A float at or beyond the bound refuses by name at mint time. Ints are unrestricted.
Recomputing the hash for kind discovery — identityHashForKind kindValue instance. A consumer holding an instance value and a candidate kind value can recompute the identity and match the carried id_hash:
# which kind does `inst` belong to? (name-agnostic — by the id_hash marker, not the registry key)
lib.findFirst (kv: genSchema.identityHashForKind kv inst == inst.id_hash) null candidateKindsIt reflects the kind's own primitive options — honoring identity = false — and routes through the same hashIdentity as mkIdentityModule, so the two cannot drift. A non-match reliably means "not this kind"; a wrong-kind false match would need a sha256 collision across different preimages.
A candidate whose identity keys the instance does not carry answers null — not this kind — so the loop above passes over it rather than aborting. null is not an identity and mints nothing; null == inst.id_hash is plain false.
A candidate whose identity key the instance does carry, at a value the mint refuses — a lambda, a path, a derivation, at any depth — still propagates the mint's named refusal, because the value domain belongs to the mint and not to this reflection. A consumer iterating over candidates of unknown shape therefore wraps the call in builtins.tryEval, which catches that refusal.
There is deliberately no value-only form. Reflecting an instance value's own primitive attributes cannot honour the commitment above: a value carries no option metadata, so it sees neither the declared type nor the opt-out, and a method's return is just a primitive attribute in config that it would admit. One substrate has one minting authority, and two derivations that can disagree is one too many.
Three-layer precedence for key selection:
- Explicit
_identity.keys— list the exact keys. Multiple modules can contribute viamkMerge. identity = false— exclude individual options from reflection.- Auto-reflection — all primitives included (default),
internalones too.
# Layer 1: explicit keys — composable across modules
# Module A:
config.schema.host.config._identity.keys = [ "name" "addr" ];
# Module B (extends the kind):
config.schema.host.config._identity.keys = [ "vpnAlias" ];
# Result: [ "name" "addr" "vpnAlias" ] — list merge via mkMerge
# Layer 2: exclude an option from reflection
options.description = lib.mkOption { type = str; } // { identity = false; };
# Layer 3: automatic (default) — all str/int/bool/float options, `internal` or notExplicit keys are validated against the identity-key set closed at the kind boundary — a name outside
it refuses. The set excludes for three different reasons (nothing declares it, what declares it is not
primitive, or it is declared primitive but excluded via identity = false or contributed on the
instance side), and the refusal names membership rather than which of the three applied,
printing the closed set alongside the excluded name. The exact wording is pinned by the
identity-refusals cells in ci/tests-error.nix — read it there rather than retyped here, since a
hand-copied error string is a second copy that decays independently of its source.
schema.declarationOf types a field whose value is a declaration: another kind's instance, written either as a reference (its identifier) or as the instance itself (Neron et al. 2015: a reference resolves to a declaration). Two modes:
Deferred ref — declare on the kind, bind at registry time:
# Kind declares referential intent
config.schema.service.options.host = lib.mkOption {
type = genSchema.declarationOf "host";
};
# Registry binds the ref to a concrete registry
options.fleet.services = genSchema.mkInstanceRegistry {
refs.host = config.fleet.hosts;
} config.schema.service;The binding is what makes the deferred form a reference: refs.<field> swaps the kind's leaf for a
bound one, which resolves. Where nothing binds it — a plain option, or a kind instantiated through
mkInstanceType alone — there is no scope to resolve the reference in, so the value is refused by
name rather than admitted raw:
gen-schema: o: `declarationOf "host"' is unbound here. A deferred declaration resolves only through a registry binding (`refs.<field>' on `mkInstanceRegistry'), so outside one its value is never resolved or checked; bind it, or name the registry directly with `declarationOf <registry>'.
The wording is pinned by the unbound-declaration-refusals cells in ci/tests-error.nix. A null
under nullOr, or an empty list, still evaluates: no element reaches the leaf.
Direct ref — resolve immediately when the registry is in scope:
options.fleet.services = genSchema.mkInstanceRegistry {
extraModules = [({ ... }: {
options.upstream = lib.mkOption {
type = lib.types.nullOr (genSchema.declarationOf config.fleet.services);
default = null;
};
})];
} config.schema.service;Both modes accept string keys or instance values:
config.fleet.services.nginx.host = "igloo"; # string key → lookup
config.fleet.services.gateway.upstream = config.fleet.services.nginx; # instance → its registry entry
config.fleet.services.nginx.host.addr # → "10.0.1.1"
config.fleet.services.gateway.upstream.port # → 80A value must be a member of the target registry: it carries a member's stamp (id_hash) and that
member's identity-key values. It resolves to the registry's entry, so both forms reach one node, and
the door serves the entry, never the value it was handed: igloo // { note = "x"; } with note a
non-identity field serves the registry's note.
Invalid references and non-member values throw at eval time, catchably:
ref field 'host' on kind 'service': reference 'nonexistent' not found in instance registry
ref field 'host' on kind 'service': expected an identifier or a declaration (an instance with name and id_hash), got set
ref field 'host' on kind 'service': declaration 'igloo' (host:…) is not a member of the instance registry (available: igloo, yurt)
ref field 'host' on kind 'service': registry member 'a' carries no _identityKeys; a declaration value resolves only against gen-schema instances (use the identifier 'a')
The non-member refusal covers the key-override idiom (igloo // { addr = "evil"; }), a same-name
member of another registry, a value of another kind, and a registry's own member after a derive
overwrote one of its identity keys (its stamp no longer matches its fields; the identifier form still
resolves).
One class is not catchable. An identity key (including name) whose value is computed through a
declaration-value resolution that must read that key aborts with infinite recursion: self-reference,
a cycle through several members, or any member's name when the resolution takes the by-name path (a
renamed or refused value). This is an in-stratum read of in-flight identity, a price the design records
and requires to be enumerated. The identifier form ("cabin") never reads identity and
is the escape.
declarationOf works inside listOf and nullOr wrappers at any nesting depth:
config.schema.service.options.replicas = lib.mkOption {
type = lib.types.listOf (genSchema.declarationOf "host");
default = [];
};
# String keys and instance values both work:
config.fleet.services.nginx.replicas = [ "igloo" "iceberg" ];
config.fleet.services.nginx.replicas = [ config.fleet.hosts.igloo "iceberg" ];
# Nullable and nested wrappers:
type = lib.types.nullOr (lib.types.listOf (genSchema.declarationOf "host"));For domain-specific resolution, pass an extended binding with a coerce function:
options.fleet.services = genSchema.mkInstanceRegistry {
refs.host = {
instances = config.fleet.hosts;
coerce = default: val:
if val == "primary" then config.fleet.hosts.igloo
else default;
};
} config.schema.service;default is a lazy thunk of the standard coercion result — only forced if you select it. In listOf context, default is a single-element list and the hook can return multiple instances (1->many expansion).
When a registry's ref field points back to itself (e.g., a trait's needs referencing other traits in the same registry), standard coerce hooks cause infinite recursion — the coerce chain accesses the registry, which triggers apply, which runs the coerce chain again.
Set deferred = true to defer coercion to the applyPipeline (after all instances are evaluated). The coerce hook receives the raw materialized instances as its first argument, breaking the cycle:
options.traits = genSchema.mkInstanceRegistry {
refs.needs = {
instances = config.traits;
deferred = true;
# 3-arg signature: registry is the raw instances (not config.traits)
coerce = registry: default: val:
if isSelector val then resolveAgainst registry val
else default;
};
} config.schema.trait;Signature difference: Non-deferred hooks take 2 args (default: val:). Deferred hooks take 3 args (registry: default: val:), where registry is the pre-apply instance attrset. gen-schema pre-applies the registry, so mkCoerceChain sees a standard 2-arg function internally.
Deferred coerce runs before validators in applyPipeline, so validators see resolved instances and can check properties like .name on referenced entries.
setOf deduplicates by id_hash, preserving first-seen order:
config.schema.group.options.members = lib.mkOption {
type = genSchema.setOf (genSchema.declarationOf "host");
default = [];
};
config.fleet.groups.web.members = [ "igloo" "iceberg" "igloo" ];
# → [ igloo iceberg ] — duplicate removed by identity hashComposes with custom coerce hooks — expansion produces duplicates, setOf removes them.
declarationOf is a type: it declares that a field points at an instance. mkFieldDeclaration is the matching
value: an inert record naming which instance, and which field of it.
fr = genSchema.mkFieldDeclaration config.fleet.hosts.igloo [ "net" "addr" ];
# → { __genSchemaFieldDeclaration = true; aspect = <igloo>; path = [ "net" "addr" ]; }
genSchema.isFieldDeclaration fr # → true
genSchema.fieldDeclarationsIn { listen = { bind = fr; }; }
# → [ { at = [ "listen" "bind" ]; aspect = <igloo>; path = [ "net" "addr" ]; } ]The target must carry id_hash — routing is by identity, and a display key is not one, so a name
string is refused at application time. fieldDeclarationsIn returns one record per declaration it finds, with at
giving the subpath (attribute keys and list indices) where the declaration sat; [ ] means the scanned value
was itself a declaration.
The two levels are complementary and both are derived, never declared:
declarationOf |
mkFieldDeclaration |
|
|---|---|---|
| what it is | an option type on a field | a value inhabiting such a field |
| lives in | the kind's schema | a default or a contributed value |
| edges | _refEdges, kind → kind |
(instance, field) → (instance, field) |
| refuses | an unresolvable key, at merge time | a non-identity target, at application time |
fieldDeclarationsIn refuses functions. A function found anywhere the scan descends throws, naming the
position, rather than being treated as a leaf:
genSchema.fieldDeclarationsIn { k = _: fr; }
# → error: gen-schema: fieldDeclarationsIn: function at scanned position k — this scan's domain is data.
# A function is refused rather than skipped, because a reference inside a closure is unreachable
# to any structural scan: its edge could never be derived, so the dependency would go missing
# silently. If this position is a computed value, express it where its reads stay visible —
# `mkFieldDeclaration <instance> <path>` for a cross-instance read, or the kind's `computed` hook for a
# value derived from collections and defs; otherwise, make the position data, or keep the
# function outside the scanned structure.That is deliberate. Nix exposes no primitive that inspects a function body, so a declaration inside a closure is invisible to any structural scan — and skipping it fails open: the edge is missing, a cycle it would have closed goes undetected, and the unresolved ref record leaks into output as data. Refusing eliminates the case instead of declaring it unanalysable, which keeps every dependence fact the scan reports a derived one. The values a ref scan is applied to are declared data, so on conforming input the refusal observes nothing.
The refusal is wider than the hazard, on purpose, and that is worth knowing before you work around it:
- a function proved to contain no reference refuses anyway — the scan does not attempt to decide what a closure reads, because no structural scan can;
- it reaches any depth of the value tree, including a function inside a foreign attrset stapled in from elsewhere;
- a raw lambda as a computed value is foreclosed. Computed values are expected to route through
constructs whose reads are graph-visible:
mkFieldDeclarationfor a cross-instance read,computedfor a value derived from collections and defs,deriveon a registry for one derived per instance.
That covers the cases seen so far, and it is the first thing to reach for. If it genuinely does not, the escape is a declared one, not a quieter scan. The sanctioned shape follows the pattern the value-injection invariant sets — by-construction as the target, a declared opt-out as the interim, with the price recorded: refusal stays the default, and a field is annotated at schema level as not scanned, its reads declared here. The burden of arguing why those reads cannot be derived attaches to that annotation at that point, which is where it can actually be discharged — a concrete case exists to argue from. Re-opening the scan silently is explicitly not sanctioned: it trades a stated refusal for an unstated hole, which is the trade this refusal exists to reverse. No such annotation ships today; if you need one, that is a design conversation, not a patch to this file.
Kinds can declare their parent kind via the parent collection. This establishes a schema-level nesting relationship:
config.schema.host = {
options.addr = lib.mkOption { type = lib.types.str; };
};
config.schema.user = {
parent = "host"; # users nest inside hosts
options.shell = lib.mkOption { type = lib.types.str; };
};The parent collection is optional — kinds without it are root kinds. The schema derives both directions:
config.schema._topology.host # → { parent = null; children = [ "user" ]; }
config.schema._topology.user # → { parent = "host"; children = []; }Declaring a parent that doesn't exist as a schema kind throws at eval time.
Every schema has flat _-prefixed options for programmatic access:
config.schema._kindNames # → [ "host" "service" "user" ]
config.schema._roots # → [ "host" ] — kinds with no parent
config.schema._leaves # → [ "user" ] — kinds with no children
# Per-kind introspection
config.schema.host.options # → full option declarations (filtered, no _module.*)
config.schema.host.refs # → { } (ref fields on this kind)
config.schema.host.strict # → true
builtins.attrNames config.schema.host.options # → [ "addr" "role" ... ]
# Unified edge view (§ Neron 2015 scope graph P + I edges)
config.schema._edges
# → [
# { from = "user"; to = "host"; type = "parent"; field = null; }
# { from = "service"; to = "host"; type = "ref"; field = "host"; }
# ]
# Ref edges only
config.schema._refEdges
# → [ { from = "service"; field = "host"; to = "host"; } ]
# Collection keys extracted from kind defs — built-ins plus this schema's own
config.schema._collectionKeys
# → [ "includes" "methods" "parent" "validators" ]_edges combines parent edges (from topology) and ref edges (from schema.declarationOf declarations) into a single typed list. Every edge has { from, to, type, field } — field is null for parent edges and the option name for ref edges.
gen-schema provides generic introspection options (_topology, _edges, _kindNames, etc.) that consumers use to build whatever graph format their evaluator needs. The bridge logic lives in consumers (e.g., den's buildScopeGraphs), not in gen-schema.
A kind inherits another kind's options by NAME. Declare the parent in inherits and build the
schema with evalSchema, which reads the parent names first, refuses a cycle by name, and then
evaluates the tree once, composing each parent's module into the child:
schema = genSchema.evalSchema { } [
{
config.schema.user = {
options.userName = lib.mkOption { type = str; };
options.shell = lib.mkOption { type = str; default = "/bin/bash"; };
};
config.schema.admin-user = {
inherits = [ "user" ]; # inherits userName, shell
options.sudoPrivileges = lib.mkOption { type = bool; default = true; };
options.sshKeys = lib.mkOption { type = listOf str; default = []; };
};
}
];Each gets its own registry. Identity hashes include the kind prefix — a user "root" and an admin "root" hash differently.
Multiple parents compose, and a kind is one value however many children reach it, whatever their
depth. Each inheritance is also an edge, type = "inherits", in _edges:
config.schema.deploy-user.inherits = [ "user" "ssh-access" "sudo-access" ];On a tree evalSchema did not build (a plain mkSchemaOption tree), a declared inherits = [ "<p>" ]
means what the spelling imports = [ config.schema.<p> ] below means there: the kind entry reads the
parent off its own tree and imports the parent's module, the one evalSchema composes. So the two
spellings compose byte-identically (options, inherits, _edges, the mark and an instance's
id_hash), and a plain tree composes the same kind evalSchema returns. A parent the tree does not
declare is refused by name, gen-schema: kind '<k>' inherits '<p>' which is not a declared kind,
as evalSchema refuses it. An entry type built outside a tree (lazyAttrsOf (mkSchemaEntryType { }))
has no tree to read a parent off, so there a declared inherits is refused by name at every read
that would compose it (options, refs, refinements, the mark, an instance, the functor, a
computed field and every field an mkType result built), while the spelling composes where it is
written.
inherits also takes a kind VALUE. A value that is the tree's own kind (inherits = [ config.schema.<p> ]:
the tree holds a kind at its name, with an equal mark, and kindEq decides true) is that kind's NAME,
recorded as "<p>" and composed exactly as the name is. Any other value is FOREIGN, another tree's kind:
it stays a VALUE entry, in inherits and in its _edges row's to, and it composes as itself through
the same applied functor, on any tree, evalSchema's included (its name graph reads names only, and a
value is already minted), or none. A foreign value is never resolved against a same-named kind of the
tree, so a consumer's own base and another tree's base stay two kinds. A foreign value that shares
the mark of the tree's same-named kind is decided by kindEq: a type-only twin is one kind (the name),
and a twin that differs at open content is refused in kindEq's words. An entry that is neither a name
nor a kind value is refused by name.
A value whose name the tree holds at an entry that reaches the declaring kind is foreign. That entry
is the declaring kind itself (base inherits another tree's base, a self-named subkind) or a kind that
inherits it (base inherits sub, and sub inherits another tree's base). Were the value that
entry, the kind would inherit itself through it, so the cycle walk below refuses it by name if it is
one; with no cycle the value is foreign, its completion stamp is read, and it is a VALUE entry. This
is decided before any mark is read, because that entry's mark is the declaring kind's own, still being
computed. The kind's own name is tested by the name, never by forcing the kind, and the descendant by
the cycle walk, which reads witnesses only to route the value: the verdict stays with the cycle walk and
the stamp. A kind on an inheritance cycle classifies no parent: the cycle walk's verdict is read before
any stamp or mark, because a cycle member's stamp read would re-enter the cycle. Three cases are
exceptions to "a value or a named refusal", enumerated and pinned (ci/tests-error.nix,
inherits-value-entry-refusals, cross-tree-cycle-refusals, witness-collision-refusals and
knob-instance-value-decides-its-kind), not closed:
-
A caller
mkTypewhose result SHAPE reads what a parent IS (the content of the desugared def'simports, or an entry of theinheritscollection) aborts uncatchably withinfinite recursion encounteredon every evaluator when the kind is on a value cycle. It is enumerated and argued by its mechanism: while the kind's key set is the caller's result key set, a caller that forces a partner's WHNF at its own makes the two WHNFs mutually dependent before any gen-schema code runs, so no guard here can catch it. The cycle is expressible and undetected, the price evaluation pays for a re-entry into a value under construction; the route that would close it is a named re-entry guard on that value, not a check gen-schema can run first. On an acyclic tree such a caller is served. Pinned bycross-tree-cycle-refusals.test-a-caller-reading-the-parent-imports-at-its-result-shape-aborts.The caller contract. A caller
mkTypereceivesdefsas the kind's raw defs (collection keys stripped), followed by AT MOST ONE nested def, present iff the kind'sinheritsis non-empty, whosevalue.importsnest one module per composed parent under its own_file, whichever of the desugar orevalSchema's pass composed it. The count and the nesting are a function of the declaration alone; the inner order is the composing resolver's, so underevalSchemathe parents it resolved by name come before the ones given as a value. Its result shape may readdefs' spine and length, each def'sfile, each def'svalueto WHNF with its key set, and theinheritsspine; every value cycle is then refused by name, as on the default arm (cross-tree-cycle-refusals, themkType-arm cells). It may not read a parent's identity; the composition reads it, behind the guard. -
A cycle every member of which reaches through a witness twin first is missed. The walk's visited set is keyed by witness, so of two twins (below) it reads the first and skips the second. A cycle reached only through the second is not seen by that walk. Where some member's own walk does reach it (
kinheritsaandb,areaches one application of a helper andbanother, and onlyb's leads back tok), that member refuses it by name, sokis refused on every evaluator asb's cycle (b -> x -> p -> k -> b). Where EVERY member lists a twin with no cycle behind it before its cycle branch (ainheritsx1thenx2,x2inheritsb;binheritsy1theny2,y2inheritsa), no walk finds the cycle and composition recurses uncatchably on all three evaluators. This abort is a permanent argued price: telling the twins apart needs node identity or a content comparison, the same question as gen-bind's released one-site-two-bodies exception. It is pinned bywitness-collision-refusals.test-a-fully-shadowed-cycle-aborts; the same shape with the cycle branch listed first is refused by name. The remedy is provenance: give each application its own_file, and the walk sees the cycle and refuses it by name (pinned bywitness-collision-refusals.test-a-fully-shadowed-cycle-with-tagged-twins-refuses). No key closes it: the walk reads parent values, not addresses, so a key that tells twins apart never repeats on a cycle that does not pass through the kind read, and a walk with no visited set pays every path through a diamond lattice. -
A kind decided by one of its own instances' VALUES (
config.schema.host = if config.reg.h1.addr == … then … else …, withrega registry or anattrsOf (mkInstanceType …)sibling over that kind) aborts uncatchably withinfinite recursion encounteredon every evaluator, on both constructs. It is enumerated and argued by its mechanism:h1.addrexists only onceh1's element has imported the kind, so the kind's definition reads a value its own construction is producing. That is the module fixpoint's own value cycle, andconfig.a = config.b; config.b = config.aaborts the same way in gen-merge with no gen-schema code in it: a cycle with nocircularmember is not detected and reaches the evaluator's call-depth abort. The route that would close it is a named re-entry guard on that value, not a check gen-schema can run first. A kind decided by a separate option, or by the registry's instance NAMES, composes (below, "The crossing is supported"). Pinned byknob-instance-value-decides-its-kind, one cell per construct.
A def that carries the resolver's _file is the resolver's only when its value is exactly one
import. unresolvedInherits skips a declared parent when some def's file is the string
evalSchema's pass writes for it AND that def's value is { imports = [ <one module> ]; } (exactly one
imports key holding exactly one entry). A def with that _file and any other value, such as extra keys,
two imports or none, is an ordinary def: its own keys compose and the parent is still imported, so the
label alone does nothing (cells schema-inheritance.test-a-forged-resolver-file-*,
test-the-resolver-file-with-* and test-a-def-under-its-own-file-*). One argued exception to "a
value or a named refusal" remains, not pinned: a def under the exact string for a declared parent whose
value is exactly one import, of any module, is taken as the resolver's and the parent is skipped, silently.
Telling it from the resolver's def needs a value a user module cannot write, and pure Nix has none (data is
copyable; function identity compares differently per evaluator). It takes a deliberate reconstruction of
a private string plus the one-import shape, never a mistyped or copied label.
One declaration applied in several trees. A helper that declares a kind, applied in two trees with
the same parent names and the same directly declared option names, gives two kinds one witness: the
witness is read before composition, and nothing it can read tells them apart (two trees one helper
built agree on every tree-level field, and a chain of such applications and a cycle through them agree
to any finite depth). Options reached through the kind entry's imports, or a function body, are not
directly declared and are not read. So a chain through such kinds meets the kind's own witness exactly
as a cycle does, and the refusal names both readings and the remedy:
gen-schema: kind 'base' reaches a kind with its own content witness through its parents (base -> base), among kinds [base]: either it inherits itself, an inheritance cycle, and a kind may inherit only kinds resolved in a strictly earlier pass; or two kinds named 'base' were declared from one source with the same parent names and the same directly declared option names, which the witness does not tell apart before composition, and giving each such module its own _fileseparates them (a module imported by path is named by the_fileits own content sets, else by its path; an importing module's_file does not reach it).
The remedy is provenance, which the witness reads as each def's file. A module takes its file
from the _file its own content sets, so a helper sets one per application
(layer = tag: parent: { _file = "layer:${tag}"; config.schema.base = { inherits = [ parent ]; … }; }),
and the chain composes while a genuine cycle through two applications with equal tags is still
refused. A module imported by PATH is named the same way: by the _file its own content sets, else by
its path (a _file on a module that merely imports it does not reach it), so a path module that sets a
per-application _file is served too, while two distinct path modules that set one _file share a
file and so a witness. Pinned by witness-collision-refusals
(ci/tests-error.nix) and kind-witness-collision (ci/tests/). Such a kind is refused before
composition too: reading an entry of its inherits, or its __kindImports, is refused, since a kind
the walk answers for classifies no parent.
An inheritance cycle is refused by name on every tree, in either spelling, but for the two
exceptions enumerated above (a caller mkType whose result shape reads what a parent is, and a cycle
every member reaches through a witness twin first). A kind that reaches
itself through its parents, declared or spelled, would import itself into itself; it is refused,
catchably, at every read that would compose it, in evalSchema's wording: the members sorted, as
evalSchema names them, so the bracket is the same whichever member is read, and then the path from
the kind read:
gen-schema: kind 'a' reaches a kind with its own content witness through its parents (a -> b -> a), among kinds [a b]: either it inherits itself, an inheritance cycle, and a kind may inherit only kinds resolved in a strictly earlier pass; or two kinds named 'a' were declared from one source ….
The walk compares witnesses, so its refusal claims only what a hit establishes: the first reading, or
the collision above.
A kind that merely reaches a cycle composes the cycle's first member, which refuses under its own
name: at any depth, through a diamond, and across trees with distinct names alike (a in one tree
inherits b of another, which inherits a), pinned by cross-tree-cycle-refusals. The walk is over parent VALUES as written, compared by a content witness (the kind's name,
where each def was written, its parents' names and its declared option names), so a parent reached
twice is a diamond, not a cycle, and another tree's kind of the same name is a different kind unless
it is the same declaration's twin (above). Each
kind value publishes the two things the walk reads: __kindCycleParents (its parents as written,
before any value is told same-tree from foreign, which forces marks a cycle could not supply) and
__kindWitness. So a cycle through a same-tree value (a.inherits = [ config.schema.b ],
b.inherits = [ config.schema.a ]) is refused by name like any other. Every kind, parentless or not, is also a module keyed by its DECLARATION NODE, so an ancestor
reached on two paths (a diamond) composes once, and kinds at two declaration nodes both compose: two
trees' same-named kinds, or one generator called at two sites, where gen-merge then refuses the
declarations that conflict. The kind value's functor record names the graph node, __moduleKey = "gen-schema-kind:<kind>#<witness>" (__kindWitness, read before composition), and publishes
gen-merge's key comparison __keyEq: its meeting is the node key, so occurrences meet only at one
declaration node; its key, the reference key gen-schema-kind:<kind>#<witness>#<separation>, is read only
where two occurrences meet, so importing a lone kind demands no mark, and a kind whose identity-bearing
collection reads an instance of itself composes. At one node, decide names the one construction
reached again by its seals (the mark only where nothing is sealed): it is one module. Two
constructions at one node are refused by name where their marks are equal (sealedCollisionEq names
the differing sealed component), so nothing is dropped silently; unequal marks both compose. A kind
whose definitions (its own or a mixin's) set a collection the schema keeps in identity is decided at
one node by its construction instead, never by its mark or seals, whose minting could read an
instance under construction: the one construction reached twice is one module, and a second
construction of it at that node is refused by name, naming the remedy (import one construction, or
declare the collection identity = false). A declaration may not carry __keyEq itself, and
gen-schema over a gen-merge that does not read __keyEq and __moduleKey off a functor record, or
key, onDistinct and conflicts off the comparison (moduleSyntax.keyEqFields), is refused by
name. The separation part is a reading of what the mark mints, taken off the definitions without
minting: the schema's construction parameters, with its base and mixins read as the definition they
resolve to (a function base applied to the kind name) and each sealed parameter read leaf by leaf as
the mark spreads it; each definition's declared option paths with their types' marks, and the other
open paths it sets; every kept collection's value as the mark reads it (one at a declared seed by that
seed's reading, bound once per schema: held because no definition or mixin of the kind sets it, or equal by ==
to a seed that is a scalar or an empty list or record, which == decides without reaching a derivation's
outPath; and one equal to a built-in collection's library seed by the collection's name, so a seed enters the
key only as a kind's value), the computed field and freeform types, and the parents' own keys. Definition order enters no part of it, as it enters no
part of the mark. Where a definition reaches a function or path module, whose
declarations no such reading sees, the separation part is the mark itself. Either way the key splits
exactly where the mark does wherever Nix == on a kept collection's value is at least as fine as the
mark's reading of it, and a cell over every one-node shape in that domain holds that. A derivation (a
value carrying type = "derivation" and outPath), which == compares by its outPath alone, has no
identity: the mint refuses it, so the mark seals it and two kinds whose values differ only off the
outPath share their mark as they share their key, at the seed and away from it. The module the functor
returns carries imports, config and the same reference key, so a
nixpkgs lib.evalModules mount of the kind value dedups one construction reached twice as gen does
and collects nothing it does not know; at one node it keeps one construction where gen refuses.
Removing a kind names its computed key. disabledModules = [ { key = (k { }).key; } ] removes
the kind k in gen-merge and in nixpkgs alike. The key embeds two digests (the declaration witness
and the mark) that are internal addressing, so never write it as a literal string. An item naming a
kind's earlier key gen-schema-kind:<kind>#<mark>, or a parentless kind's earlier positional name
<parent>:anon-<i>, no longer removes the kind in either engine.
Each kind publishes its transitive ancestors, and a subkind must keep its ancestors' classes.
__kindAncestors maps each ancestor's mark to the ancestor kind value, read off __kindImports.
On an evalSchema tree a declared parent is published as the value the tree returns for it. A mark
reached along two paths is decided as kindEq decides it: one kind is one entry, and two declarations
that share a mark and differ are refused by name, naming the kind and both paths:
gen-schema: kind 'd' reaches 'p' along d -> x -> p and along d -> y -> p: two declarations of 'p' mint one identity and are unequal only at sealed component(s) 'open.options.base.default': ….
A subkind's keySemantics must hold every key of each ancestor's, with the same category; one that
omits or re-categorises a key is refused by name, naming the kind, the key and the ancestor. An
ancestor that carries the kind's own name is foreign (one tree holds one entry per name), and both
refusals name it as the foreign kind value '<k>'. Both
refusals fire where the kind is composed (its options, refs, mark or an instance, and the map itself),
never at its WHNF, and after the cycle walk. The fold meets ancestors by NAME and reads marks only where
two constructions of one name meet; the same construction reached again is one entry, decided by its
stamp slot. Equal marks imply equal names, so every pair the marks would meet still meets, and a parent
whose collection kept in the identity reads an instance of a kind inheriting it composes. Its residue, a
parent meeting ANOTHER tree's construction of its name, reads both marks and still recurses (an open defect).
ancestorsForKind kind lists those ancestors in order (below, ancestorsForKind).
The deprecated inheritance spelling is read as inherits, with a warning, where a value test can
see it, and nowhere else (a declared exception to "a value or a named refusal"). A kind value
appearing in a kind entry's imports (or a shorthand module's require), at any depth of plain
attrset modules, as a bare non-list imports, or as the value of a path or string member or anywhere
in the tree of files it imports, records in the kind's inherits the entry inherits = [ <value> ]
would: its NAME if it is the tree's own kind, the VALUE if it is foreign (above). Entries follow any
declared parents, in walk order, once, and never repeat one already declared. The value still composes where it is
written, and that is the parent's module, the one evalSchema composes for a declared parent. So the
spelling is the same kind as the hand-written inherits that evalSchema resolves: same options, same
inherits, same _edges entry, same mark and same instance id_hash. It stays supported, and nothing
retires it automatically: retiring it is a deliberate decision. Declare inherits = [ "<parent>" ],
which composes the same kind on either tree.
Each spelled kind warns once per MODULE-TREE EVALUATION that reads its inherits: once on a plain
tree, and twice under evalSchema, whose names read and whose one evaluation each read it. The reads that fire it are the ones that force inherits: the collection itself, _edges,
the kind's mark (__mint.minted) and an instance's id_hash, whose preimages carry the collections.
A read of the kind's options only, of .kind, or of _kindNames does not warn. The warning is builtins.warn, so under abort-on-warn the evaluation
aborts at the first spelled kind read, and tryEval does not catch it; an evaluator without
builtins.warn prints it through builtins.trace.
config.schema.admin-user.imports = [ config.schema.user ];
# → evaluation warning: gen-schema: kind 'admin-user': its `imports` carries the kind value 'user', the
# deprecated spelling of kind inheritance, read as `inherits = [ "user" ]`; declare `inherits`For a foreign value the warning names it as inherits = [ <the kind value 'user'> ].
A CYCLE written in the spelling, a importing config.schema.b and b importing config.schema.a, is
refused by the cycle walk above, on a plain tree and under evalSchema alike, by the kind read,
before the spelled modules import each other: kind 'a' reaches a kind with its own content witness through its parents (a -> b -> a), among kinds [a b]: either it inherits itself, ….
Four constructions compose as before, unaliased and unwarned, because deciding them needs something
other than a value test: (1) the crossing, mkInstanceRegistry config.schema.<k> read off the tree
that declares the kind: it has no kind-entry imports element, and it is the same value as the
relocated form; (2) a function module whose body imports a kind: the test does not apply functions,
whose module arguments it does not have; (3) a kind's functor applied by hand, k.__functor k: the
result carries no mark, and evalSchema composes a parent through exactly this form, which is why its
own injection does not warn; (4) gen-aspects' __defsModule, which is not a kind value. None of them
records a name, and none is a parent to the cycle walk: a cycle closed only through one of them is not
refused by name. Where its other edges are kind values, the mark key closes it and it composes the
union of its members' options.
What the test forces, stated exactly: where the kind's inherits is read (never at the kind's WHNF), its
walk forces (1) every imports and require list of the kind entry's defs and of every attrset module
reachable from them, a top-level require list and a nested imports or require list included; (2)
every member of those lists, at every depth; (3) the __mint record of any member carrying kind and
__mint, never the digest; (4) the import of every reachable path or string member, so a path to a
file that throws, or that does not exist, raises there; and (5) the tree of files those imports reach,
each file once (a visited set keyed by the resolved path, so a cycle of files terminates). The module
system imports those files anyway, so for (4) and (5) what moves is when, not whether. It applies no
function module and reads no option, config or other attribute value of a member. The walk is kept
off the kind's WHNF because a spelled parent's own WHNF is forced by it: were it at WHNF, a spelled
cycle would force each kind's WHNF from the other's and recurse before any name could be read.
evalSchema refuses by name a parent whose kind value is not a module (an mkType result with no __functor): there is nothing to compose.
schemaFn declares functions on entity instances. Named arguments are automatically resolved from the instance's config:
config.schema.host.methods.describe = genSchema.schemaFn
{ description = "Human-readable summary"; type = lib.types.str; fn = { name, role, addr, ... }: "${name} (${role}) at ${addr}"; };
# On instances:
config.fleet.hosts.igloo.describe # → "igloo (web) at 10.0.1.1"Methods can close over values from the declaring module's scope:
# hasService captures config.fleet.services from the module;
# name comes from the host instance's config
config.schema.host.methods.hasService = genSchema.schemaFn
{ description = "Check if a service targets this host"; type = lib.types.functionTo lib.types.bool; fn = { name, ... }:
serviceName:
let services = config.fleet.services;
in services ? ${serviceName}
&& services.${serviceName}.host.name == name; };
config.fleet.hosts.igloo.hasService "nginx" # → true
config.fleet.hosts.igloo.hasService "postgres" # → falseMethods compose across modules — multiple modules can each add methods to the same kind:
# Module A
config.schema.host.methods.ping = genSchema.schemaFn
{ description = "Ping command"; type = lib.types.str; fn = { addr, ... }: "ping ${addr}"; };
# Module B (separate file, separate flake input — doesn't matter)
config.schema.host.methods.ssh = genSchema.schemaFn
{ description = "SSH command"; type = lib.types.str; fn = { name, ... }: "ssh ${name}"; };
# Both methods available on every host instance:
config.fleet.hosts.igloo.ping # → "ping 10.0.1.1"
config.fleet.hosts.igloo.ssh # → "ssh igloo"If two modules declare the same method name, the later definition wins (attrset // semantics).
Methods with arguments that don't match any config key produce a clear error:
method 'bad' on host: references config keys 'nonexistent' which are not declared on this kind
Methods must be declared via inline attrsets, not path modules. This is a constraint shared with all collection fields.
Declare custom collection fields on kinds — data extracted from definitions before module merge and exposed on the merged result:
options.schema = genSchema.mkSchemaOption {
collections = {
includes = { default = []; }; # list → merged via ++
excludes = { default = []; }; # list → merged via ++
metadata = { default = {}; }; # attrset → merged via //
priority = { default = 0; merge = _acc: val: val; }; # explicit: last-wins
};
};
config.schema.host = {
includes = [ policy-a policy-b ];
options.addr = lib.mkOption { type = str; };
};
# Read collection values directly:
config.schema.host.includes # → [ policy-a policy-b ]Merge strategy inference:
| Default type | Inferred merge | Example |
|---|---|---|
List ([]) |
acc ++ val |
includes, excludes |
Attrset ({}) |
acc // val |
metadata, methods (built-in) |
| Other | an option's default | priority = { default = 0; } |
None (no default) |
as an untyped option | roles = { }; |
Declared type |
the type's own merge | classes = { default = []; type = listOf str; } |
A non-list, non-attrset default without an explicit merge is an option's default: once a kind defines the collection, the default is one definition at mkOptionDefault, so a definition outranks it and it answers where every definition discharges, as nixpkgs drops an option's default; the definitions fold through the declared type, or as an untyped option's do where none is declared (below). A kind that never defines the collection is served the default.
A collection declaration carries only default, identity, merge and type. Any other field is refused by name wherever the collection set is read, by the shared closed-options check, naming the door the caller invoked (gen-schema.mkSchemaOption: collection 'classes': 'typo' is not an option of this door; …).
type is opt-in and states the collection's whole type, any option type, a nixpkgs one included. The collection's definitions, a mixin's contribution included, are merged by that type as an option of it merges them, so its element checks, its properties at every depth and its count of discharged elements are the type's: under type = listOf str, [ (mkIf false "a") "b" ] yields [ "b" ] and [ 1 ] is refused. A list or attrset default is still the fold's seed. It is resolved and checked through the type, then folded onto the merged definitions by its shape (++ or //) outside their priority pool, as an undeclared collection's is. Where no definition of it survives, every one discharged included, the collection is its seed alone, as an option of the type serves its default alone, whatever empty value the type states: under type = nonEmptyListOf str; default = [ "d" ];, mkIf false [ "a" ] alone yields [ "d" ]. Any other default is one definition at mkOptionDefault, so a definition outranks it and it answers where every definition discharges, as an option's default does: type = nullOr str; default = null; defined "x" yields "x". type beside a merge, type on a built-in collection (inherits, methods, parent, validators, whose containers stay lazy), and a type that is not an option type are each refused by name. A typed collection declaring no default, read where no definition of it survives, answers its type's empty value as an option of the type with no definition does: [ ] under listOf str, { } under attrsOf, null under nullOr, a submodule's own defaults; where the type states none (str, int, bool, unspecified, nonEmptyListOf), it is refused by name, naming the collection and where it was read. The type decides by its own emptyValue, never by its name. Such a collection mints the kind's mark as the same collection declaring that empty value as its default does. The mark tells { } from [ ], as Nix == does: an undefined attrsOf collection and a listOf one read as [ ] mint apart, as a { } and a [ ] definition do. A declared type is never read by the kind's identity: it enters no mark and no key, so only what it merges to does. gen-merge publishes no lazy listOf, so a declared list is strict. Omitted, the container is inferred as the table above states.
Collection keys are stripped before the deferred module merge — they never leak into the module system. Collections must be declared via inline attrsets, not path modules (path defs get the collection's default value).
methods is a built-in collection with { default = {}; }. User-declared collections are additional. __functor is reserved and cannot be used as a collection key.
Multiple modules contributing to the same collection merge according to the collection's strategy:
# Module A
config.schema.host.includes = [ policy-a ];
# Module B
config.schema.host.includes = [ policy-b policy-c ];
# Result: [ policy-a policy-b policy-c ]Properties on a collection's own definitions (mkDefault/mkForce/mkOverride, mkIf, mkMerge, mkBefore/mkAfter/mkOrder) are resolved by the module system before the strategy folds, so includes = mkDefault [ policy-a ] beside a plain includes = [ policy-b ] yields [ policy-b ], as nixpkgs would for an option. A list or attrset collection defined on a kind is a container, as a list or attrset option is: a property on a list element or an attrset key is resolved when that element is read, so includes = [ (mkIf true policy-a) ] yields [ policy-a ], and a definition of the wrong shape (includes = "x") is refused by name. An attrset key keeps //'s last-wins among the definitions that survive. An explicit merge folds whole definitions, and only their top level is resolved. An element or key whose definitions all discharge (mkIf false) is kept and refused when it is read. On an attrset, attrNames still counts that key, as nixpkgs' lazyAttrsOf does. On an undeclared list this diverges from nixpkgs (a declared type closes it, above): listOf drops the element, so [ (mkIf false a) b ] has length 2 here and 1 under listOf. A collection value a mixin contributes is one more definition of the collection, after the kind's own, resolved and refused exactly as they are. On a kind with mixins, every mixin's contribution, and baseModule's, is a definition in that one pool, so a mkForce/mkDefault ranks it against the kind's definitions and against another mixin's as it would two modules' definitions of one option: a kind's mkForce [ "k" ] beside a mixin's [ "a" ] yields [ "k" ]. This includes inherits: a parent a mixin declares is a parent of the kind, composed, cycle-checked and listed among its ancestors exactly as one the kind declares. A collection's default is one definition of the collection, resolved alone, as nixpkgs resolves an option's default: a property on an element or key is resolved, so default = [ (mkIf true "a") ] yields [ "a" ]; one mkOrder at its top is stripped; and any other property at its top (mkIf, mkMerge, mkDefault/mkForce/mkOverride) is refused by name, naming the collection and the property. On a list default nixpkgs' type check refuses such a property too; on an attrset default nixpkgs serves the raw property record (its keys are _type, condition, content), a silent value, so the named refusal is kept. The default's priorities rank nothing against a definition. A default that is neither a list nor an attrset, with no merge, is served as it is to a kind that never defines the collection; a definition of it outranks it, and the definitions fold as below for an untyped collection, so default = 5 defined 7 yields 7. A collection declaring neither a default nor a merge is an option declaring no type and no default. Its definitions fold as an untyped option's do: one definition is its own value; lists concatenate, and strings concatenate, in the order the definitions are written; bools are OR-ed; equal ints are one value, and so are equal nulls, floats and paths, and an int beside an equal float, where nixpkgs refuses them; differing scalars, or definitions of different shapes that are not equal, conflict; attrsets merge, and a key two definitions share is refused by name where its values differ, where nixpkgs keeps the later one. Read where no definition of it survives, it is refused by name, naming the collection and where it was read. A collection declaring a merge and no default has no seed: it is refused by name where no definition of it survives, or where its merge reads the seed; a merge that never reads its accumulator folds as before. A collection's default is kept beside its definitions as the fold's seed; nixpkgs drops an option default once any definition exists, so here a default = [ "base" ] with one definition [ "a" ] yields [ "base" "a" ] where nixpkgs yields [ "a" ].
Derived values computed from collection content and raw definitions:
options.schema = genSchema.mkSchemaOption {
collections = {
includes = { default = []; };
excludes = { default = []; };
};
computed = collections: defs: {
isEntity =
let
collectionKeys = lib.attrNames collections;
hasStructuralContent = lib.any (d:
let v = d.value;
stripped = if builtins.isAttrs v
then builtins.removeAttrs v collectionKeys else v;
in !builtins.isAttrs stripped || stripped != {}
) defs;
in
collections.includes != []
|| collections.excludes != []
|| hasStructuralContent;
};
};
config.schema.host.isEntity # → true (has includes)
config.schema.conf.isEntity # → false (empty — shared base only)The collections are the kind's published values, a mixin's contribution included, so a computed field and the
kind value read one value of each collection; defs are the kind's own definitions as written.
Every schema has flat _-prefixed options for programmatic access:
config.schema._kindNames # → [ "host" "service" "user" ]
config.schema._collectionKeys # → [ "includes" "methods" "parent" "validators" ]
config.schema._declarationKeys # → [ "__pureModule" "__reservedKeys" "_class" "_file" "_module" "config" "disabledModules" "freeformType" "imports" "key" "meta" "options" ]
# Per-kind introspection — available on each kind value
config.schema.host.options # → full option declarations (filtered, no _module.*)
config.schema.host.refs # → { field = { refKind = "targetKind"; type = ...; }; }
config.schema.host.strict # → true
builtins.attrNames config.schema.host.options # → [ "addr" "describe" "hasService" "metricsPort" ... ]_collectionKeys is the set gen-schema extracts from kind defs before the deferred module merge —
the built-in methods/validators/parent plus whatever collections this schema declared. It is
derived from the same expression the extraction runs on, so a consumer reads it instead of
maintaining its own copy of the list. Because it is the whole set, selection is positive and no
prefix filter is needed:
prelude.genAttrs config.schema._collectionKeys (k: config.schema.host.${k})
# → { includes = [ "policy-a" ]; methods = { }; parent = null; validators = [ ]; }Scope. That idiom reads collection values on the default entry-type path. Two caveats, both
real: a computed field sharing a collection's name wins on the kind result ({ ... } // extractedCollections // computedFields), so the idiom returns the computed value for that key, silently;
and a caller-supplied mkType that does not spread collections onto its result makes the read fail
with attribute '<k>' missing. Declaring a reserved collection key (__functor, __keyEq, __kindAncestors, __kindContextFree, __kindCycleParents,
__kindImports, __kindLineage, __kindSelf, __kindWitness, __mint, __pureModule, __reservedKeys, __sealed, __witness, _class, _file, _module, baseModule,
collections, computed, config, disabledModules, freeformType, imports, key,
keySemantics, kind, meta, mixins, mkType, options, refinements, refs, require,
specialArgs, strict — schema._reservedCollectionKeys, 38 names: gen-merge's published
moduleSyntax.structured and moduleSyntax.shorthandMeta, the names gen-schema writes onto the kind
value itself, and the schema's construction formals) is refused when _collectionKeys is read, exactly as it is refused when a
kind is merged.
The names a schema is built from — mkSchemaOption's and mkSchemaEntryType's formals
(baseModule, collections, computed, keySemantics, mixins, mkType, specialArgs,
strict) — share the top-level key position of a kind entry with config shorthand, and so do the
names gen-schema writes onto the kind value (kind, refs, refinements). Written there, such a
key used to become config for every instance while the kind value went on reading its own value at
the path just written. It now aborts, on both entry-type branches and on structured and shorthand
declarations alike:
config.schema.host.keySemantics = …; # meant to widen the class vocabulary
# → gen-schema: kind 'host': declaration key 'keySemantics' is a construction formal of this schema —
# it is fixed by the call that builds the schema option (`mkSchemaOption`, `mkSchemaEntryType`), …A construction formal is changed by a different constructor call, never by a write on a kind entry.
An instance field of the same name is untouched: write it on the instance, or as
config.keySemantics on the entry (a strict instance must declare it as an option). The refusal
covers every route into the entry. A formal at the top level of a module the entry imports
(nested imports, require, a function or path module, a whole-module mkIf) is refused at
gen-merge's collector with the same text, saying it was "written in a module this kind entry
imports" and naming the module. The defs merged imports carry entryReservation kind, the names
and their texts as plain data, on the record of a functor module wrapping each def that imports
anything, and gen-merge's __reservedKeys scope applies it over their import closure; nixpkgs
applies the functor and collects only its result, so a kind value mounted in lib.evalModules
carries no marker; a kind value in imports (the deprecated inherits spelling) is exempt by the same shape
inherits reads. That refusal fires where a module tree is evaluated: an instance read, or the
kind's options, refs and mark. A read of kind or strict still returns the construction's own
value, which is correct, because the misread value is never consumed there; the residue is stated
here so that it is never silent. A
caller's custom mkType that builds instance modules from defs applies entryReservation itself,
as gen-aspects does, or that route is outside the door. Three forgeries pass it, as forgeries
rather than honest routes: a hand-written module carrying kind and __mint.minted is exempt (the
inherits alias reads it as a kind, by ruling), and so is a function module returning that shape,
which the exemption tests after application while the alias, reading values before application,
leaves it unaliased; and a nested __reservedKeys in an imported module replaces the reservation
for its own closure. A def writing its own __reservedKeys beside an imported formal does not: the
wrapper's record is read first (imports-route-refusals.test-def-forging-its-own-reservation-still-refuses-by-name).
The pairing guard (a gen-merge whose moduleSyntax.functorRecord does not list __reservedKeys is
refused by name) sees only the gen-merge gen-schema is built with: a kind value evaluated by another,
older gen-merge in the same evaluation never reads the record, and an imported formal lands there
silently.
A key on a structured kind declaration that no reader consumes used to be discarded unread — a
typo'd roel produced an instance byte-identical to one declared without it, id_hash included. It
now aborts, naming every offending key and printing the recognised sets:
config.schema.host = {
options.role = mkOption { type = types.str; };
roel = "web"; # typo
};
# → gen-schema: kind 'host': unrecognised declaration key 'roel' (declared in <…>). This declaration
# is structured — it carries `config` or `options` — so gen-schema reads only: this schema's
# collection keys […] (published as `schema._collectionKeys`), the module keys […]
# (published as `schema._declarationKeys`), and any `_`-prefixed key. …A declaration is structured when it carries config or options
(genMerge.moduleSyntax.structuring, narrowed to those two). An unstructured one is
config shorthand: gen-merge reads every other key of it as config. Beside _declarationKeys and
_collectionKeys, one rule that is not a list: any _-prefixed key is admitted as consumer-private
metadata gen-schema must not read.
A bare top-level myPort = mkOption { … } is refused independently of structuring:
a kind entry is a module, and neither gen-merge nor nixpkgs
ever collects a top-level mkOption as a declaration, so a flat option-valued key is never a read
plane whether the surrounding declaration is structured or not. That check only fires once the
declaration carries some module-syntax key at all (genMerge.moduleSyntax.structured — imports,
freeformType, config, options, meta, key, …): a declaration carrying none of them is plain
data through and through, and an option-shaped value on one of its keys is no different from any other
value a config key may hold. A kind's refinement contracts are read off its option plane, so a refined
option declared through imports, baseModule or a function module is enforced exactly as a
module-style one is.
The guard stands down entirely for a schema built with computed or mkType. Both hand the raw
or stripped defs to a caller-supplied function — gen-aspects' mkType consumes the whole def as a
module — so the key space is unbounded and not gen-schema's to close.
Two exceptions to the _ prefix, because gen-schema writes them onto every kind value and a
declared one is discarded unread: __mint and __sealed always, and __functor on a schema built without
mkType. Both refuse by name, as they already do as collection keys.
Declare cross-field validation constraints on kinds. Validators are a built-in collection — they travel with the kind and run automatically on every registry of that kind.
config.schema.host.validators = [
(gen.mkValidator {
name = "has-addr";
pred = { addr, ... }: addr != "";
message = "host must have a non-empty addr";
})
(gen.mkValidator {
name = "valid-role";
pred = { role, ... }: lib.elem role [ "web" "db" "worker" ];
message = "role must be one of: web, db, worker";
})
];Validators compose across modules — multiple modules can contribute validators to the same kind via the collection ++ merge:
# Module A
config.schema.host.validators = [ (gen.mkValidator { name = "a"; … }) ];
# Module B
config.schema.host.validators = [ (gen.mkValidator { name = "b"; … }) ];
# Both fire on every host registryWhen validation fails, errors accumulate (not short-circuit) and include the instance name, validator name, and message:
schema validation failed:
host 'igloo': has-addr — host must have a non-empty addr
host 'iceberg': valid-role — role must be one of: web, db, worker
For standalone validation without throwing, use validateInstances:
result = genSchema.validateInstances config.schema.host config.fleet.hosts;
# → { right = instances; } or { left = [ { name; validator; message; } ]; }derive and deriveEither on mkInstanceRegistry compute values from the full evaluated registry and merge them back at high priority. The pipeline is: validate -> derive -> apply.
Plain derive — attrset in, attrset out:
options.fleet.users = genSchema.mkInstanceRegistry {
derive = users:
let uids = assignIds { min = 1000; max = 60000; } users;
in lib.mapAttrs (name: _: { uid = uids.${name}; }) users;
extraModules = [({ ... }: {
options.uid = lib.mkOption { type = lib.types.int; readOnly = true; internal = true; };
})];
} config.schema.user;
config.fleet.users.tux.uid # → 34213 (deterministic from id_hash)Derive can read id_hash and all instance config — it runs after full module system evaluation. A derived field must stay out of id_hash (derive reads it, so admitting the field would be a cycle): declare it through extraModules, which has nowhere to attach to the kind's identity-key set, as above, or on the kind with identity = false. internal = true only hides it from generated docs. Mark it readOnly = true (the derive hook is the only writer).
deriveEither — returns Either with configurable error handling:
options.fleet.services = genSchema.mkInstanceRegistry {
deriveEither = {
derive = services: someEitherPipeline services;
onError = left: lib.warn "enrichment failed" {}; # optional, default throws
};
} config.schema.service;derive and deriveEither are mutually exclusive. onError receives the left value — throw, warn, or return a fallback attrset. The default onError throws with a formatted message.
Validator errors flow through the same onError handler — a custom onError on deriveEither handles both validator failures and derive failures.
renderDocs produces markdown reference from schema metadata:
genSchema.renderDocs config.schemaOutputs a table per kind with option name, type, default, and description — including extensions from composition and methods.
mkCodec creates a standalone codec for serializing/deserializing kind instances. The codec is format-agnostic at its core, with a pluggable format layer and built-in JSON convenience.
codec = genSchema.mkCodec {
# Optional: per-field overrides
fields = {
secret = { exclude = true; };
cluster = { encode = v: v.name; decode = v: v; };
meta = {
fields = {
region = {};
internal = { exclude = true; };
};
};
};
# Optional: additional fields to exclude by name
excludeFields = [ "tags" ];
} config.schema.host;The codec returns:
{
encode # instance → attrset (strips internals, encodes refs to names)
decode # attrset → attrset (drops unknown fields, passes through known)
encodeAll # registry → attrsOf attrset
decodeAll # attrsOf attrset → attrsOf attrset
serialize # format → instance → value
deserialize # format → value → attrset
serializeAll # format → registry → value
deserializeAll # format → value → attrsOf attrset
json # { serialize, deserialize, serializeAll, deserializeAll }
}Usage:
# JSON export
jsonStr = codec.json.serialize config.hosts.igloo;
# → "{\"addr\":\"10.0.1.1\",\"role\":\"web\",\"cluster\":\"prod\"}"
# JSON import (produces registry-compatible attrset)
imported = codec.json.deserialize (builtins.readFile ./host.json);
# Custom format
toml = { encode = tomlLib.encode; decode = tomlLib.decode; };
codec.serialize toml config.hosts.igloo;Field resolution:
- Internals (
name,id_hash, methods, collections) are always excluded - Ref fields auto-encode to
v.name(scalar),map (v: v.name)(listOf/setOf), with null-guard for nullOr typesparameter registers codecs by NixOS type name — auto-wrapped throughnullOr/listOf/attrsOf/lazyAttrsOf/setOfeither/oneOffields dispatch to the matching branch's codec via.check(left-biased)- Custom
encode/decodeinfieldsoverrides auto-detection fields.x = { fields = { ... }; }recurses into submodule structurefields.x = { exclude = true; }removes a field
Round-trip: decode produces plain attrsets — ref fields return as strings. Resolution occurs when the decoded attrset enters an mkInstanceRegistry and passes through the existing ref coerce pipeline.
mkSchemaOption {
strict ? true, # strict-by-default validation on instances
baseModule ? null, # module imported into every kind
collections ? {}, # { name = { default; merge? }; } — user-defined collection fields
computed ? null, # (collections -> defs -> attrset) — derived fields on merged result
keySemantics ? {}, # { <key> = { category = <opaque string>; option? }; } — per-key category metadata (recorded, not interpreted)
}Returns lib.mkOption — use as options.schema = mkSchemaOption { ... }.
mkSchemaEntryType is also exported for advanced use — it returns the type used for schema kind values (schemaKindEntry), without wrapping in mkOption or adding introspection options. Most consumers should use mkSchemaOption. The entry type delegates the module-collecting half of its merge to deferredModule but is not one: it is built through mkOptionType and so answers the option-type protocol for itself, which is what makes a redeclared lazyAttrsOf of it rebuild a schemaKindEntry with its collection extraction intact rather than a plain deferredModule without it.
The schema option's type is schema, not a plain submodule. mkSchemaOption builds its entry type once per call and returns an option typed by schema, which delegates its check, merge and sub-options to the introspection submodule and states its merge relation with the entry type's constructionRelation payload and binOp. One construction declared twice (one value, or two calls with equal arguments) is one option, and its introspection reads as declared once; two constructions are refused by name at schema, within closuresFirst's enumerated exception. A plain submodule declared beside it is refused by name in both orders. The type carries no getSubModules/substSubModules, and the idempotence holds under gen-merge's engine only: nixpkgs lib.evalModules still refuses the second declaration (ci/tests/schema-option-redeclaration.nix).
Redeclaration: one construction merges, two are refused. The entry type, declarationOf(<kind>) and strict are built per call, so an option redeclared across modules meets two records of one name. Each states its merge relation through constructionRelation (exported, beside keySemanticsRecords): two such types merge exactly when their constructions are one construction, decided per component, and every other same-named pair is refused by name at the option. constructionRelation { minted ? {}; compared ? {}; } name self takes each minted.<k> into one mark, and each compared.<k> must be exactly { records = [ … ]; value; }: value is compared under Nix == through gen-merge's closuresFirst records value, which decides on the listed type records' closures before it can reach a cyclic record's back-edge. An entry without records is refused by name. Stated limits:
records = [ ]is an unchecked assertion that the grammar fixes no type-record position in that component. Stating it over a value that does hold a record is the silent spelling of an omission, and two knotted constructions then abort uncatchably.mkSchemaEntryTypedeclareskeySemanticsthroughkeySemanticsRecords(an entry'soption.type, the one position that grammar fixes) and every other formal withrecords = [ ].- Module content is outside
records. A module inmixins,baseModuleorspecialArgs, or a facet'smodule, that declares an option typed by a per-callmkOptionTypeaborts when two constructions are compared in the order that internsfunctorfirst, and in every order when that type carries a back-edge underdescription(gen-mergeclosuresFirst, enumerated exception). - "One construction" is one slot. A value bound once (a
let, a formal) merges on all three evaluators. A function reached by a selection written at each call (computed = fns.ctwice) is a different slot per call: refused on Nix and Determinate, merged on Lix.
mkType replaces the standard deferredModule merge with a custom entry type constructor. When null (the default), kinds produce the standard deferred module with __functor wrapping, mixin pipeline, and refinement extraction. When provided, collection extraction still runs first, but mkType controls the merged result — the __functor wrapping is skipped, and a schema built with mkType cannot take mixins: a non-empty mixins is refused by name at the kind, by a message that begins "gen-schema: a schema built with mkType cannot take mixins". The mkType result is the module an instance imports, so a mixin's module half could reach an instance only through caller code gen-schema cannot see, and its pooled collections would then disagree with the instance; the refusal is the construction in which that disagreement cannot form. Define the contribution in the mkType result, or drop mkType. options, refs and refinements are still derived, and all three come from one evaluation of the option plane an instance imports — the mkType result with the kind's strict, keySemantics and computed fields applied — so options lists what an instance of the kind declares, refs its reference fields, and a refined option the mkType result's module declares is enforced by the instance registry exactly as on the default branch. That evaluation is lazy and shared: one module evaluation per mkType kind, forced at the first read of options, refs, refinements or the kind's provenance mark, which reads the same plane. The published kind value applies the mkType result's __functor to that same module, so a functor that reads its self declares one plane at the kind and at every instance. A mkType result that is not a module functor publishes its keys beside options, which gen-merge's module reader refuses; each of those reads then refuses by name, as an instance of the kind does, naming the module <gen-schema mkType kind <kind>> and the first surplus key.
mkSchemaEntryType {
mkType ? null, # optional: { kindModule, collections, defs, kind } -> attrset
}mkType receives four arguments in an attrset:
| Argument | Description |
|---|---|
kindModule |
The resolved baseModule (after applying kind-name function, if any), or null |
collections |
Extracted collection values (methods, validators, parent, plus user-defined) |
defs |
Stripped definitions (collection keys removed) for wiring into the custom type |
kind |
The kind name (last element of the option path) |
The return value is merged with computedFields (computed wins for same-named keys — except a name in kindResultKeys, the kind-value contract lib/entry-type.nix reserves and refuses by name on both branches; computed may not use one of those at all), so topology and introspection fields remain authoritative.
The kind value always carries the inherits and parent collections, written over the mkType result (a computed field still wins), because evalSchema and _topology read them off the kind value; a result that publishes no collections still composes its declared parents under evalSchema. The declared parents reach the mkType result as ONE more of its defs, present iff inherits is non-empty, whose imports nest the import each parent desugars to (the caller contract, Kind Inheritance). On a kind the entry refuses (an inheritance cycle, or a declared parent on an entry type built outside a tree; see Kind Inheritance), every field the mkType result built and its applied __functor are read through the same refusal; kind, strict, keySemantics, inherits and parent stay readable.
mkSchemaOption {
keySemantics = {
nixos = { category = "class"; };
firewall = { category = "channel"; };
neededBy = { category = "facet"; option = lib.mkOption { type = ...; }; };
};
}keySemantics is a per-key declaration surface recorded verbatim on the emitted schema entry (introspectable via config.schema.<kind>.keySemantics, alongside options/refinements/collections). category is an opaque string — gen-schema stores and threads it but assigns it no meaning; a downstream library interprets it (gen-aspects reads it to dispatch aspect key-options over the bounded set class/channel/facet). Where a <key> supplies an option recipe, gen-schema builds it into a real option on the entry; keys with no option are left for the consumer to synthesize from the recorded category.
This is what makes gen-aspects' dependency on gen-schema load-bearing: aspect key-options are declared through this per-key surface, not a private downstream field. No class/channel/facet literal appears anywhere in gen-schema — the category vocabulary and its meaning live entirely in gen-aspects. Default {} — recorded as empty when unset.
Use case: gen-aspects provides its recursive aspectType as a custom entry type, replacing gen-schema's deferred module with its own classification and dispatch system while reusing gen-schema's collection extraction and topology.
mkSchemaOption {
mkType = { kindModule, collections, defs, kind }:
myCustomType {
inherit kind defs;
inherit (collections) validators;
};
}evalSchema {
schemaOption ? null, # a caller-built `mkSchemaOption` result; default `mkSchemaOption { inherit specialArgs; }`
specialArgs ? { }, # base module args for the kind tree
} modules # the kind tree's modules, last (options first, closed)Returns the evaluated schema (config.schema) with kind inheritance resolved. A
kind names its parents in inherits = [ "<parent>" ]; evalSchema reads the kind names and inherits
off the tree with no parent injected, then evaluates the tree once, importing into each child the
parent's module read off that same evaluation, so every reader holds one value per kind (with no
parent declared, the names read is that evaluation). Each inheritance is an _edges entry with type = "inherits". Refused by name: an undeclared
parent, an inheritance cycle, schemaOption together with specialArgs, and a parent whose kind value
has no __functor (an mkType result that is not a module). Outside evalSchema the kind entry
desugars a declared parent onto the import the imports spelling makes, reading it off the same tree,
so a plain mkSchemaOption tree composes the same kinds; an undeclared parent and an inheritance cycle
are refused by name there too. See Kind Inheritance for the deprecated imports
spelling, which the kind entry reads as inherits with a warning.
kindEq kindA kindB # → true | false, or a refusal by nametrue iff two kind values carry one identity, false if two. Where they mint one identity and are unequal
only at a sealed component, for example open-module content beyond an option's type, it
refuses by name, naming the component (…only at sealed component(s) 'open.options.<path>.<attr>'…).
An operand that is not a kind value carrying a mint-backed mark is refused by name, and so is a kind
value that is not the value its schema built: each kind value carries a completion stamp, __kindSelf, a
function returning the value the schema's merge built, declared beside it as the value's witness
(__witness = { completion = "__kindSelf"; }, which gen-algebra's conservativeEq reads too), so a
// copy (k // { options = …; }), which keeps the mark while changing what it stands for, is
refused naming the kind (…the kind value '<k>' is not the value its schema built…). The same refusal guards these doors:
the inherits value door, the ancestor fold (a kind reached through the imports spelling, at any depth),
an instance's id_hash and identityHashForKind. A door that composes reads the stamp over the content
cells only (stampImportOk), every cell but the three identity cells: the mark (__mint), the sealed
subjects (__sealed) and the ancestor map (__kindAncestors, keyed by marks). Those doors are
mkInstanceType's import of the kind and a parent read where its child composes (options, refs, an
instance's import), where formOf takes the tree's own construction by its stamp slot and the ancestor
fold meets by name. They compose no identity, so they demand none, and a collection kept in the identity
may read an instance of the kind it types or of a kind inheriting it. A copy of the content is refused
there. A copy of identity cells alone composes the construction it was taken from, and it is refused
wherever an identity is answered: an instance's id_hash, identityHashForKind, and a child's mark,
__sealed, inherits entries and __kindAncestors, each of which first reads every parent's and
ancestor's whole stamp. Two doors compose a // copy unread, enumerated here as
exceptions: a kind value imported inside
a function module, and types.submodule k. Their __functor ignores its self, so the copy composes the
original. Other doors that decide by the mark are outside this refusal (the 1a4f6 spec's §3b.1 censuses them).
A content-equal rebind (k // { }) is the constructed
content and is admitted. The stamp is decided by == against the witness, descending through slots
where == throws, so an honest kind with a throwing computed field decides alike on Nix, Determinate
and Lix. A kind value carrying no stamp or no sealed subjects is refused naming what it lacks at kindEq and
the ancestor fold's diamond; the inherits value door, the imports alias, a grandparent and
mkInstanceType ADMIT a stamp-less kind, as a producer that does not stamp builds one. A kind value
compared with itself after being carried through gen-merge's types.anything decides true on Nix,
Determinate and Lix: anything carries a value carrying __mint whole. Two independent
constructions of one kind defined twice through anything are refused as conflicting definitions,
because anything's leaf fold compares values, not identities.
ancestorsForKind kind # → [ kind ], or a refusal by nameIt returns each transitive ancestor once, as the value __kindAncestors holds at its mark, without the kind itself. The order is a linear
extension of inheritance: every kind comes before each of its ancestors, so a single-parent chain reads
nearest first and root last (last (ancestorsForKind k) is the root), and a diamond's shared ancestor
comes once, after every kind that inherits it. Where inheritance leaves two kinds unordered, the one
reached first in a depth-first walk over __kindImports comes first. That walk follows composition
order, which puts a foreign kind value ahead of a name, so inherits = [ "b" f ] with f foreign
answers [ f b ]. Both walks are gen-graph's: the first-reach key is expandPreorder, and the order is
topoOrderKahn, bound by name.
# d inherits [ "b" "c" ], b and c inherit "a"
map (k: k.kind) (genSchema.ancestorsForKind config.schema.d)
# → [ "b" "c" "a" ]It is not a precedence order. It is a lineage listing, not a method resolution order. A
hierarchy that C3 cannot linearise is answered rather than refused, and the answer is not monotone:
with a inheriting [ b c ], b inheriting [ d e ] and c inheriting [ e d ], a answers
[ b c d e ], which keeps b's order of d and e and not c's. A declared order is never
derived from a kind hierarchy, so a consumer needing an order among
kinds (which ancestor's value wins, which is most specific) declares that order itself rather than
reading it here. The door takes the kind declaration, a kind value: a kind name is a reference with no
tree to resolve it against, so it is refused by name, catchably, in identityKeysForKind's words (R1's
identifier arm is narrowed here, as at the other kind doors). Every other operand is read through the
whole stamp, as kindEq reads it, so a non-kind, a hand-built mark and a // copy of a kind value are
refused by name. Each call walks the ancestor subgraph again (it is a function, not a field), so a
consumer reading it per instance binds the result once per kind.
mkInstanceType {
extraModules ? [], # additional modules (cross-entity bindings, den-specific options)
strict ? kindValue.strict,
} kindValueReturns lib.types.submodule — the type for a single instance of a kind.
mkInstanceRegistry {
extraModules ? [],
refs ? {}, # bindings for deferred refs (see below)
strict ? kindValue.strict,
description ? "${kind} instances",
derive ? null, # { name → instance } → { name → attrset } — plain enrichment
deriveEither ? null, # { derive; onError? } — Either-based enrichment
} kindValueReturns lib.mkOption with type = attrsOf (mkInstanceType ...) and an apply pipeline that runs validators then derive.
The crossing is supported. mkInstanceRegistry { } config.schema.host, and the same call with the kind read
through a let knot over the evaluation that declares it, both compose, as the mkInstanceType sibling does. The
option's default is builtins.seq kind { }: lazy, so building the option record never reads the kind, and a
raw .default read on a registry built over a value that is not a kind is refused by name
(expected a kind value carrying a mint-backed mark) where it once returned { }. A registry nothing reads costs
nothing new, and one over a genuine kind still defaults to { }.
The kind read off the declaring tree may be decided by that tree's own config. Decided by a separate
option (config.schema.host = if config.knob then … else …), or by the registry's own instance names
(if config.reg ? h1 then …), it composes on the registry and on the sibling alike, in both spellings
(ci/tests/instance-knob.nix). The second holds because the registry's name set is its definitions',
as the sibling's is: apply states the pipeline's key set as its input's, since no stage adds or drops
a name, so a name read (attrNames, ?) never reads the kind. Every registry-level check runs at the first
read of an instance value, and five refusals fire there, by name, rather than at a name read: the kind
guard, a missing ref binding, an extra ref binding, a deriveEither left under the default onError,
and a throwing derive. A program that reads only the names of an ill-formed registry refuses
nothing, as it does on the sibling, and a failing whole-registry validator already behaved so. This
holds for a registry with at least one definition. An undefined registry's name set is its default's,
and the defaults differ: over a value that is not a kind, the registry's lazy default refuses by name
at the name read, and the sibling's caller-written { } answers [ ]. A kind decided by an
instance's VALUE aborts on both constructs, the enumerated exception above.
derive and deriveEither are mutually exclusive.
The kind-first call, mkInstanceRegistry kindValue { … }, is refused by name in two of its three
spellings. With the kind read through the module's own config, gen-merge's declaration guard
refuses it. With a kind from a closed evaluation, the door refuses it ('__functor' is not an option of this door). With the kind read through a let knot over the SAME evaluation
(eval.config.schema.host), it aborts uncatchably with infinite recursion encountered on every
evaluator. That abort is an argued exception. The option record's WHNF is in the declaration spine
eval.config waits on, and the door can tell a kind from an options set only by reading an operand.
Whichever operand it reads at that WHNF, a let knot on that operand aborts:
- reading the first operand, the door as it is, puts the abort on the kind-first order;
- reading the second puts it on the options-first order, and also refuses the supported
mkInstanceRegistry { } config.schema.hostspelling by gen-merge's declaration guard; - reading neither admits a misspelt option silently on a registry nothing reads.
A refusal would need an operand that is on no knot in either order, and no attrset-valued kind operand
can be one. The remedy is the options-first order, with the kind from a strictly earlier evalSchema
pass. Pinned by pre-l4-registry-call in ci/tests-error.nix.
refs binds deferred declarationOf fields to concrete registries. Three forms:
# Simple — registry directly:
refs.host = config.fleet.hosts;
# Extended — with custom coercion (2-arg):
refs.host = {
instances = config.fleet.hosts;
coerce = default: val: ...; # default is lazy thunk of standard result
};
# Deferred — for self-referential registries (3-arg):
refs.needs = {
instances = config.traits;
deferred = true;
coerce = registry: default: val: ...; # registry = raw pre-apply instances
};deferred = true runs coercion inside applyPipeline (after instances are materialized) instead of at option-apply time. The custom hook receives the raw instances as registry — use this instead of capturing the config value in the closure. Required when the ref field points back to the same registry being defined.
declarationOf targettarget is a string -> deferred ref (kind name, bound via refs on mkInstanceRegistry). target is an attrset -> direct ref (resolved immediately). Both modes accept string keys or instance values.
An unbound deferred ref refuses by name (see Deferred ref above). The binding rebuilds the field's type with every deferred leaf bound, through the wrappers mkCoerceChain walks — nullOr, listOf, setOf, attrsOf, lazyAttrsOf — and through refined, whose layer is rebuilt over the bound base with the same refinements, so a refinement over a deferred ref is served in a kind and still enforced there. Any other container around the ref (functionTo, uniq, …) is refused by name at the binding (ref field 'f' on kind 'k': its type wraps its declaration in functionTo', which the registry binding does not walk), never an interpreter abort. attrsOf/lazyAttrsOfcoerce each value as a scalar position, sosetOf (attrsOf (declarationOf k)) is admitted at construction and refused at its first value (dedupByHash: element missing id_hash). The guarantee covers types built through gen-schema's and gen-merge's constructors: a hand-written // { check = …; }` over a ref leaf is refused in a kind by gen-merge's dropped-check rule, because the binding's rebuilt leaf drops the check the override added. One kind's unbound and bound leaves join to the bound one in either order; two kinds are refused by gen-merge's declaration path on the differing names before the relation's own refusal is reached, which the relation keeps as defence in depth.
The former name ref is retired: it is a published throw that names declarationOf, so reaching it or applying it refuses by name, catchably. The rename follows Néron et al. 2015 (A Theory of Name Resolution): a reference resolves to a declaration, and this type's values are declarations.
The deferred ref's refKind sits inside the descriptor handed to mkOptionType, not stapled onto the finished type afterwards. mkOptionType stamps the protocol onto the record it is handed and mints a functor pointing back at that completed record, so a // { refKind = ...; } over a completed type leaves every protocol answer — typeMerge's rebuild included — describing a declarationOf without its kind. Declaring the same option twice as declarationOf "host" therefore merges to a declarationOf(host) that getRefKind still reads through any nullOr / listOf / setOf / attrsOf / lazyAttrsOf wrapper and mkCoerceChain still builds a coercion for, rather than to a bare declarationOf whose string keys reach the instance unresolved.
setOf elemTypeA list type that deduplicates by id_hash, preserving first-seen order. Only meaningful with declarationOf element types — setOf requires instance refs. Composes with custom coerce hooks: expansion produces duplicates, setOf removes them. Uses nestedTypes.elemType so getRefKind traverses through it like listOf.
Outside a registry binding, a setOf of an unbound declarationOf "<kind>" refuses at its first element, in the element's words: deduplication is by id_hash, a property of resolved declarations, so an unresolved list has nothing to deduplicate by. An empty setOf still evaluates to [ ].
setOf borrows listOf's value behaviour — the merge, the check — but is built through mkOptionType rather than as an override over a completed listOf, so it answers the option-type protocol as itself. A rebuild through substSubModules, and a typeMerge against a second declaration of the same option, both return a setOf with the isSetOf discriminator that mkCoerceChain and the codec dispatch on. A setOf and a plain listOf of the same element are different types and do not merge.
toSet instancesConverts a list of instances to a set with O(1) membership lookup via attrset backing. Deduplicates by id_hash (first-seen wins), so safe to call on any instance list. Returns:
{
member = x: ...; # O(1) membership test
toList = [ ... ]; # deduplicated list, first-seen order
length = n; # number of unique instances
}mkFieldDeclaration instance [ fieldName … ] # → { __genSchemaFieldDeclaration = true; aspect; path; }
isFieldDeclaration v # → bool
fieldDeclarationsIn v # → [ { at; aspect; path; } ]The value-level counterpart of declarationOf — see Field Declarations (Values).
mkFieldDeclaration throws unless the target carries id_hash and the path is a non-empty list of strings;
the record carries the caller's own instance, so identity in ≡ identity out.
fieldDeclarationsIn scans deeply for those records, returning one entry per hit with at giving the
subpath where it sat ([ ] = the scanned value itself). It throws on a function in any scanned
position: the scan's domain is data, and a declaration inside a closure would be silently invisible. The
marker key is exported as fieldDeclarationMarker for consumers writing their own predicate.
schemaFn { description = description; type = type; fn = fn; }Declares a method on a kind. fn receives an attrset of config values matching its named arguments. Declare via schema.<kind>.methods.<name> = schemaFn ....
genSchema.mkValidator { name = name; pred = pred; message = message; } # → { name; pred; message; }
genSchema.runValidators kind validators instances # → { right = instances; } | { left = [failure]; }
genSchema.formatErrors failures # → human-readable string
genSchema.defaultOnError left # throws with formatted errorsThe base validator constructors, gen-schema-owned (relocated from gen-algebra on 2026-06-26). mkValidator's pred receives the instance config and returns bool; declare via schema.<kind>.validators = [ (genSchema.mkValidator ...) ]. runValidators evaluates them across a registry into an Either; validateInstances (below) is the kind-driven wrapper most consumers use.
genSchema.mkIdentityModule kindValue identityKeys # NixOS module: injects id_hash + _identity.keys
genSchema.mkStrictModule kind # NixOS module: rejects undeclared keys (closed-world)The module-system constructors mkInstanceType injects into every instance (relocated from gen-algebra on 2026-06-26). mkIdentityModule derives a content-addressed id_hash from a kind's primitive options (str/int/bool/float) and its mark; _identity.keys pins the identifying fields explicitly. Its first operand is the kind value — a kind name is a reference, and the door refuses a string (and an attrset without a mark) by name when the module is applied, not only when id_hash is read. identityHashForKind takes the same operand and refuses the same way. mkStrictModule sets a freeform type that throws on any key not declared as an option.
validateInstances kindValue instancesRuns the kind's validators against instances. Returns { right = instances; } on success or { left = [ { name; validator; message; } ]; } on failure. Does not throw — returns Either for consumer-controlled handling.
mkFieldValidator {
name = "validator-name";
fields = [ "field1" "field2" ]; # optional — auto-skip kinds missing these fields
check = inst: ...; # predicate over instance config
message = "error description";
}Row-polymorphic validators with automatic field filtering. Validators with fields are automatically skipped for kinds that don't have all required fields. Validators without fields run unconditionally (backwards compatible).
filterValidators validators kindOptionNamesFilters a list of validators to only those whose fields (if declared) are all present in kindOptionNames. Used internally by mkInstanceRegistry to skip inapplicable field validators. Exported for consumers building custom validation pipelines.
renderDocs schemaReturns a markdown string with a table per kind.
mkCodec {
fields ? {}, # per-field overrides: { name = { encode?; decode?; exclude?; fields?; }; }
types ? {}, # codecs by NixOS type name — auto-wrapped through nullOr/listOf/attrsOf/lazyAttrsOf/setOf
excludeFields ? [], # additional field names to exclude from serialization
} kindValueReturns a codec record with encode/decode (attrset ↔ attrset), format-parameterized serialize/deserialize, and curried json.* convenience. See Codec (Serialization) for full usage.
The refinement, blame, and mixin constructors below are exported flat off the library value —
genSchema.refined,genSchema.refinements,genSchema.blame,genSchema.mkMixin, etc. There is nogenSchema.typesnamespace;refinedis a bare function (it lives atrefinedLib.types.refinedinternally but is re-exported flat).
Refinement contracts co-located with type declarations (§ Findler 2002, § Rondon 2008). The refinements are part of the type's membership wherever it is used — {v:B | e} has no member failing e — so a refined option in a plain mkOption, under listOf or any other container, or inside a kind refuses a violating value by name, with gen-types' refined wording: gen-merge: a definition for option `o' is not of the expected type: must be positive. The base is checked first, then the refinements in order, and the first that fails is the reason, so an earlier refinement guards a later one. Inside a kind, the instance registry also checks refinements supplied apart from a type (its refinements argument), which never replace the ones a type carries.
# Single refinement
port = mkOption {
type = genSchema.refined lib.types.int {
check = self: self > 0 && self < 65536;
message = "must be valid TCP port";
};
};
# Composed refinements (all must pass; checked in order)
port = mkOption {
type = genSchema.refined lib.types.int [
{ check = self: self > 0; message = "must be positive"; }
{ check = self: self < 65536; message = "must be < 65536"; }
];
};
# Reusable
port = mkOption { type = genSchema.refined lib.types.int genSchema.refinements.tcpPort; };A refinement is a record { check; message; lazy? }: the predicate paired with the blame it reports. Anything else
(a bare predicate, a record with no check or no message, a check that is not a function, a message that is not
a string, a lazy that is not a bool) is refused by name and catchably where it enters, at refined, at
checkRefinements' type and at mkInstanceRegistry's refinements, rather than aborting when a value is first checked.
A check is a function when Nix can apply it (gen-prelude's isApplicable): a functor whose __functor chain reaches
a function within 32 steps is served, and one that reaches none, or exhausts the bound (which the refusal names), is
refused.
Set lazy = true on a refinement to defer its check until the value is demanded (§ Chitil 2012). Inside a kind, a field is left unforced when the instance is built and checked when it is read, so reading a sibling never fails on it, in two cases: every refinement on the field is lazy, or the field carries a module set at any carried depth (its type is a submodule, or one under nullOr, attrsOf, either or any other container, but not a refined over such a container, which is refused: see below; or it is an option group with such an option beneath it). Any other field with one strict refinement is demanded at construction, and its whole conjunction, lazy refinements included, is decided then: on a flat value (an int, a str) the demanded value has nothing left to defer (Chitil §7.3, lazy contracts behave like eager contracts). On a non-flat base carrying no module set (lazyAttrsOf, listOf) a lazy predicate decided then may force parts of the value nothing else demanded. A field carrying a module set is the exception because its value is a module tree whose declarations may read back into the registry being built, and demanding it at construction would recurse uncatchably: a failing refinement on it refuses that field's read, and its siblings still read. What a type carries is read to gen-merge's type-walk bound, and a type the walk does not finish within that bound is treated as carrying a module set, because demanding a module set nested past the bound would be the same uncatchable recursion. That includes every self-referential type, which never ends: nixpkgs' types.json shape, the settings type of pkgs.formats, is checked at access although its value is flat, since no type walk can tell a cyclic type from a deep one. A lazy refinement reads:
{ check = self: self > 0; message = "must be positive"; lazy = true; }A refined type keeps its base's name — a refined int still says int in its error messages — but carries a distinct functor name, refined<int>, which is the identity two declarations of the same option are compared on. Declaring an option twice as the same refined type merges to that type with its refinements intact. Declaring it with two different refinements over bases that join merges to the meet, since a redeclared option accepts a definition only if every declared check does: the base join refined by both, each refinement owed relative to its own operand's base where the join widens one (an enum union), so the merged type rejects what either declaration rejects. Declaring it once refined and once as the bare base merges to the refined type in either order, since the bare base admits every value the refinement does: the refinement is kept, never silently dropped to the unrefined type.
A refined type's identity is gen-types' per-component construction (mkIdentity): it mints over the constructor, the base and each refinement's inert content, with each refinement's check a sealed component carried in __sealed. A check may be a lambda or a registered construction (gen-algebra mkIntensional); on any other base a registered one is compared by its declared subject, so two constructions of one registered term are one type under typeEq and one kind under kindEq, and a different argument or revision is another. The base enters by its mark, or sealed where it carries no mint or a wrapper rewrote its check, so refined int r and refined (addCheck int odd) r are two types. A refinement over a container of submodules is the exception: two separate constructions of one such refined container share no identity, because the mint cannot take a verify closure. The site is sealed, so it carries no identity and a total tagged field, and typeEq of two such constructions is a named refusal whenever an identity is demanded. That is by design, and no attestation field restores it.
Constructing a refined submodule never evaluates the submodule's module set, so a kind option typed refined (submodule …) whose module set reads back into the instance registry being built composes, as the bare submodule does: through attrsOf, with a defined element, under lazy refinements, and through the kind's refs (ci/tests/refined-submodule-knot.nix). The base is a gen submodule or a nixpkgs one, raw or imported through merge.mkOptionType: refined imports a foreign base through gen-merge's mkOptionType before copying it, and gen-merge's import door recognises any record carrying a module set in gen's spelling and never reads its nestedTypes. A strict refinement on such a field composes too, because a field carrying a module set is checked when it is read (above).
Open defect: refined over a container of a gen submodule is refused by name. refined (nullOr sub) r,
refined (listOf sub) r, refined (attrsOf sub) r, refined (either sub str) r and refined (nullOr (nullOr sub)) r, and
the nixpkgs spellings of the first four (lib.types.nullOr sub and so on) over a gen submodule sub, are not served. The
construction reaches gen-merge's mkOptionType as an unstamped copy of a container that declares a nested gen element, and
the door refuses it with nestingImportRefusal for the accepted value and the rejected one alike. Under the parity-defect rule
that is an open defect, not a price: nixpkgs' addCheck twin over the
native container serves the accepted value. Its construction is gen-merge applying a stamped container's
verify over its threaded fold, so the refinement keeps membership semantics and the nested tree is threaded. A refined
bare submodule, and a container of a refined submodule, are served (above). Pinned by ci/tests-error.nix
(refined-gen-container-open-defect, nine shapes, one accepted and one rejected value each), which goes red on the day the
construction serves the accepted value.
Built-in reusable refinements: tcpPort, nonEmpty, positive. Use with genSchema.refined to avoid repeating common predicates.
Field-level error attribution for structured contract violations (§ Findler 2002).
genSchema.blame "fieldName" "error message"
# → { __blame = true; field = "fieldName"; message = "error message"; }First-class reusable schema fragments with structural compatibility (§ Bracha 1990). The options come first, as one closed set; define, the one required operand, comes last. It receives a record-algebra record and returns a plain attrset.
monitorable = genSchema.mkMixin {
requires = [ "port" "hostname" ];
provides = [ "metrics_port" ];
# kinds = [ "service" ]; # optional kind constraint
} (parent: {
metrics_port = (record.select "port" parent) + 1000;
});Compose multiple mixins into one. Requires propagation: earlier mixins' provides satisfy later mixins' requires.
enhanced = genSchema.composeMixins [ monitorable loggable healthcheck ];
# Mixed direction: beta mixin is overridden by what came before
combined = genSchema.composeMixins [
monitorable
(genSchema.beta tlsBase) # Beta: existing fields win over tlsBase's
loggable
];Annotates a mixin for Beta direction (§ Bracha 1990) — parent controls, meaning existing fields take precedence over the mixin's contributions.
applyMixin mixin kindRecord kindNameApplies a single mixin to a record-algebra record. Validates structural compatibility (requires) and optional kind constraint (kinds). Respects Smalltalk/Beta direction.
Bridges record-algebra records to NixOS modules (§ Cardelli 1997). Publishes option types as declared, so a refined type keeps enforcing its refinements, and extracts them as the kind's refinements. Extracts collections with full shadow stacks.
emitted = genSchema.emitModule [ "validators" "methods" ] recordAlgebraRecord;
# → { module = <NixOS module, an attrset>; collections = { ... }; refinements = { ... }; }Mixins are applied over the kind's baseModule read as a record. An absent baseModule (null, the default) is the empty record, so mixins on a schema with no base are carried exactly as over baseModule = { }, and a mixin whose requires the empty base cannot meet is refused by name. A baseModule the record algebra cannot read (a function module or a path, after a kind-name function is applied) is refused by name, naming the kind and the base's type (gen-schema: kind '<kind>' declares mixins, and its baseModule is not an attrset …), on every reader of the kind. A schema built with mkType cannot take mixins (see mkType, above).
mkSchemaEntryType {
mixins = [ monitorable loggable ];
baseModule = {
port = mkOption { type = types.int; };
hostname = mkOption { type = types.str; };
};
}genSchema._internal.mkMethodsModule # methods option/config wiringNot part of the public API contract. Available for testing and advanced use.
Identity, strict, and validation primitives are gen-schema-owned — they relocated here from gen-algebra on 2026-06-26 (which is now fully pure). Import them from gen-schema.lib directly; gen-schema depends only on gen-algebra's pure record algebra.
Schema kinds (deferred modules, parent collection, ref types)
↓ imported by
Instance types (submodules with strict + identity injected)
↓ collected into
Instance registries (attrsOf instance type, ref binding via apply)
↓ referenced by ↓ introspected by
Cross-instance refs _topology, _edges, _roots, _leaves
(schema.declarationOf)
Kinds are pure schema — options, config, defaults, methods, collections. No strict validation or identity hashing at the kind level.
Instances add infrastructure — mkInstanceType injects mkStrictModule and mkIdentityModule. This separation means kind-level composition via imports works without duplicate module conflicts.
Collections are extracted before merge — collection keys on kind definitions are folded, merged, and exposed on the result. They never enter the deferred module merge.
lib/
default.nix — public API surface, wiring (imports gen-algebra's pure record algebra)
entry-type.nix — mkSchemaEntryType, mkSchemaOption (collection extraction, introspection, topology)
instance.nix — mkInstanceType, mkInstanceRegistry (strict + identity injection, refs)
id-hash.nix — mkIdentityModule (id_hash via primitive-option reflection) + identityHashForKind.
The MINT is not here: `hashIdentity` lives in gen-identity and arrives injected
strict.nix — mkStrictModule (closed-world freeform rejection)
ref.nix — schema.declarationOf (dual-mode cross-instance references, getRefKind)
methods.nix — schemaFn, mkMethodsModule (method option/config generation)
validate.nix — mkValidator, runValidators, formatErrors, defaultOnError (base) + validateInstances, mkFieldValidator, filterValidators (schema-specific)
refined.nix — refined (refinement contracts, § Findler 2002 / § Rondon 2008)
blame.nix — blame (field-level error attribution)
mixin.nix — mkMixin, composeMixins, beta, applyMixin (§ Bracha 1990)
bridge.nix — emitModule (record-algebra → NixOS module bridge, § Cardelli 1997)
docs.nix — renderDocs (markdown generation)
flakeModule.nix — flake-parts integration (provides schema option + genSchema)
Identity hashing (mkIdentityModule), strict validation (mkStrictModule), and validators (mkValidator, runValidators, formatErrors, defaultOnError) are gen-schema-owned module-system constructors — they relocated here from gen-algebra on 2026-06-26 (which is now fully pure). They are exported on the public API and consumed internally by instance.nix. Cross-instance references use schema.declarationOf (see ref.nix); the older mkRefType was retired in favor of its direct mode, which is a behavioral superset. gen-schema imports only gen-algebra's pure record algebra.
See examples/demo/ for a complete fleet management example using flake-parts + import-tree. The demo exercises all features: kinds, instances, strict validation, identity hashing, cross-instance references, schema composition, kind inheritance, declarative methods, codec serialization, and documentation generation.
cd examples/demo
nix eval --override-input gen-schema ../.. .#fleet
nix eval --override-input gen-schema ../.. .#docs --raw== compares a function by its value SLOT on upstream Nix and Determinate and by its OBJECT on
Lix (the Nix manual, Value identity optimization), so one function reaching both operands of an
identity decision through two slots splits them. Two sites cannot close that way, both on a
refinement record's check (a refinement that is not such a record is refused at formation):
lib/refined.nixmkRefinedType, a refinement record'scheckslice. Onecheckpassed by selection to two refinements (refined int { check = s.pos; message = …; }twice) is refused on Nix and Determinate andtrueon Lix. Its partner, one boundcheckin two refinements, istrueon all three, and Lix gives the two one verdict, so a closure here would move the partner with the split; upstream has no observer of closure identity to raise the split totrue. It closes when the caller'scheckmigrates to a first-order term. gen-types states the same site for its ownrefined, and the rest of the split, in its README.ci/tests-error.nixrefined-evaluator-divergencepins the split to each evaluator's own==on a literal two-slot shape, beside its partner attrue×3.lib/refined.nixmkRefinedTyperelation, the merge relation'sheldslot test. Two declarations of one option, eachrefined int fwith one function selected at each site, merge on every evaluator to the meet, so the value split is closed: each evaluator serves and refuses the same values. An introspection split remains: the merged__schema.refinementsholds 2 entries on Nix and Determinate and 1 on Lix, becauseheldcompares refinements by==over functions. The partner, one bound function in both declarations, holds 1 on all three. It closes when every refinement on both declarations carries a registered check (gen-algebramkIntensional): the relation then compares their declared subjects, so two constructions of one term are held once on all three and terms over different arguments are held as two. A list mixing a registered check with a caller lambda is compared by==alone.ci/tests-error.nixrefined-evaluator-divergencepins the split to each evaluator's own==, read at the merged declaration's refinement count, beside its partner at"int"×3.- The identity of a merge over two DIFFERENT bases. Where the base join widens an operand, each
conjoined refinement is relativised to its own operand's base, a fresh caller lambda per merge, so
two separately built merges of one pair are refused by
typeEq(the sealed-component refusal). Over one base the refinements keep their slots and the twins decidetrue.ci/tests/registered-type-identity.nixtest-a-merge-over-differing-bases-refuses-its-twin.
511 tests via nix-unit across 112 suites in ci/tests/ — both figures are command output rather
than hand-maintained prose: nix-unit --flake ./ci#tests ⇒ 511/511 successful (exit 0, 00ba0d8), and
git ls-tree --name-only HEAD ci/tests/ | grep -c '\.nix$' ⇒ 112, which is also the number of
distinct suites the runner reports. Covering kinds, extension, strict validation, instances, identity hashing, cross-instance refs (deferred/direct/self-referential coerce, listOf/setOf/nullOr wrappers), collections and computed fields, methods, mixins, refinement contracts, blame, validators, derive hooks, codec round-trips, topology/edges introspection, and docs generation.
Run the itemized suite, behind the read-roots guard:
nix develop ./ci --command ciOr build the aggregated check derivation (unguarded):
nix flake check ./cici refuses when anything under a declared read root is unknown to git — any extension or name,
_-prefixed included — and the remedy is git add or a move. The bare nix-unit --flake ./ci#tests
and nix flake check ./ci are unguarded: they read a git-filtered copy of the tree, so an untracked
cell is silently absent and the run stays green.
gen-schema runs on the pure-gen stack — gen-merge REPLACES lib.evalModules + lib.types, so gen-schema carries no nixpkgs.lib dependency.
gen-schema draws on seven papers. Four are directly implemented in the codebase; three inform the design without direct implementation.
| Feature | Paper | Where |
|---|---|---|
| Refinement contracts with blame tracking | § Findler & Felleisen -- Contracts for Higher-Order Functions (ICFP 2002) | refined.nix: predicate contracts co-located with NixOS type declarations; blame.nix: field-level error attribution with { field, message } blame records; instance.nix: the instance registry checks refinements no type carries |
| Lazy contracts with deferred validation | § Chitil -- Practical Typed Lazy Contracts (ICFP 2012) | instance.nix: a field whose refinements are all lazy = true is left unforced and checked at access -- matching Chitil's partial-identity semantics where unevaluated parts never trigger violations; one strict refinement on a field carrying no module set decides its whole conjunction at construction (§7.3, on flat values); a field carrying a module set is checked at access |
| Mixin composition | § Bracha & Cook -- Mixin-Based Inheritance (OOPSLA 1990) | mixin.nix: mkMixin/composeMixins implement Bracha's M1 * M2 = fun(i) M1(M2(i) + i) + M2(i) formula; beta reverses direction so parent controls; applyMixin validates structural requires |
| Refinement types | § Rondon, Kawaguchi & Jhala -- Liquid Types (PLDI 2008) | refined.nix: refined attaches predicate refinements to base NixOS types via __schema metadata, following Rondon's model of {v:B | e} base refinements co-located with type declarations |
| Concept | Paper | Influence |
|---|---|---|
| Record algebra | § Leijen -- Extensible Records with Scoped Labels (TFP 2005) | gen-schema consumes gen-algebra's record.compose, record.select, record.mixin etc. The record algebra itself lives in gen-algebra; gen-schema uses it for mixin application and module bridging |
| Module linking | § Cardelli -- Program Fragments, Linking, and Modularization (POPL 1997) | bridge.nix: emitModule translates record-algebra records into NixOS modules (one-directional). Cardelli's linkset model -- separately compiled fragments linked via type-compatible substitution -- informs the design, though gen-schema doesn't implement the full linking calculus |
| Scope graph edge model | § Neron, Tolmach, Visser & Wachsmuth -- A Theory of Name Resolution (ESOP 2015) | entry-type.nix: _edges introspection uses Neron's P (parent) and I (import/ref) edge vocabulary to expose schema topology. gen-schema doesn't implement scope graphs or the resolution calculus -- that lives in gen-scope |