Skip to content

About

Graph products over accessor-graphs: cartesian/tensor/strong/lexicographic, cells, slices, sparse restriction, containment chains — pure Nix, den-hoag L2

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

161 Commits

Folders and files

Repository files navigation

gen-product — graph products as first-class operations for Nix

CI License: MIT Sponsor

Pure graph products for Nix. gen-product builds the four standard graph products — Cartesian, tensor (direct), strong, and lexicographic — over accessor-graphs, the gen-graph accessor-record convention. Products are lazy in and lazy out: a product is an accessor-graph (gen-graph's accessor-record queries take it whole, topoOrder included; its labeled-graph doors — forgetLabels, labeledTranspose, query, queryFold — take a labeled graph, which a product is not), extended with product metadata that gen-product's own operations read.

gen-product is nixpkgs-lib-free (Class B): it depends only on gen-prelude, the pure utility base. It imports no other gen library — its entire integration story is the shared accessor record { edges, parent, nodes, nodeData } and the gen-schema instance shape (id_hash, name) as the default coordinate currency.

Table of Contents

Overview

A product takes ordered factor specs — named dimensions whose coordinates are registry entries (the identity law: public inputs carry gen-schema identity, never "kind:name" strings) — and answers structural questions about the product-shaped graph they span:

genProduct = import (builtins.getFlake "github:sini/gen-product").lib { prelude = …; };

# a factor spec names a dimension and supplies its accessor-graph
hostFactor = { dim = "host"; graph = hostsGraph; };   # key defaults to (e: e.id_hash)
userFactor = { dim = "user"; graph = usersGraph; };

fleet = genProduct.productN "cartesian" [ hostFactor userFactor ];

# a CELL is a full coordinate — the id gen-graph queries take
cellId = genProduct.nodeAt { host = hosts.axon-01; user = users.sini; } fleet;
fleet.edges cellId                        # product adjacency (an ordinary accessor)
genProduct.coordsOf cellId fleet          # → { host = <entry>; user = <entry>; }

Adjacency per kind — the cell u = { d_i = u_i } has an edge to v = { d_i = v_i } (writing u_i ~ v_i for a directed factor edge):

kind edge rule
cartesian (□) exactly one dimension has u_i ~ v_i; all others equal
tensor (×) every dimension has u_i ~ v_i
strong (⊠) every dimension is equal-or-edge, at least one is an edge
lexicographic (∘) at the first differing dimension: u_i ~ v_i; earlier equal; later free

These are the standard product definitions applied coordinatewise to directed adjacency; on symmetric edge relations they degenerate to the textbook objects (K2□K2 = C4, K2×K2 = 2K2, K2⊠K2 = K4, K2∘K2 = K4).

Gen Ecosystem

Library Role
gen-prelude Pure nixpkgs-lib-free utility base
gen-graph Accessor-based graph query combinators (the accessor-record convention gen-product builds on)
gen-schema Typed registries (the id_hash/name instance shape used as the default coordinate currency)
gen-scope HOAG scope-graph evaluator
gen-select Selector algebra (consumes product cells via the cell adapter)
gen-product This lib — graph products (Cartesian / tensor / strong / lexicographic; cells, slices, fibers, projections, quotients, restriction, containment chains)

Quick Start

As a flake input

{
  inputs.gen-product.url = "github:sini/gen-product";
  # gen-product pulls in gen-prelude transitively — no nixpkgs input required.
}

Then gen-product.lib is the genProduct attrset.

Standalone (non-flake)

let genProduct = import (fetchTarball "https://github.com/sini/gen-product/archive/main.tar.gz") { };
in genProduct.cartesian hostFactor userFactor

Design Principles

  • A product is an accessor-graph. productN, slice, fiber, restrict, and quotient all return the accessor record { edges, parent, nodes, nodeData } (plus a product metadata field, { kind, dims, factors, cellOf, coordsOf, base, restriction, def, enumeration }, which every gen-product operation reads, and __cells, the materialized member list nodeCoordinates returns — its contract is in AGENTS.md <pgraph>); gen-graph's accessor-record queries apply unchanged (its labeled-graph doors do not: a product is not a labeled graph), and products nest as factors of other products.
  • Lazy in, lazy out. Adjacency, cell addressing, slices, projections, and containment chains never scan a factor's nodes list — not-a-node and not-a-member detection is pointwise (via a codec round-trip), so nodeAt and containmentChain succeed even under nodes = throw …. The en-masse operations (nodeCoordinates, nodes) and the lexicographic trailing-dimension fan-out are the documented exceptions.
  • One enumeration per (def, restriction). The member set depends on the product definition and its restriction, never on which coordinates a view has fixed, so a product and every slice of it share a single enumeration instead of each deriving its own — asking a product for H slices costs one enumeration, not H. A view takes that set as a required argument, so the sharing is a property of the construction rather than a cache consulted when present. restrict derives a new one, because changing the restriction changes the set. Slicing that shared set is a fiber lookup on the fixed dimension, and the relational join indexes its probe side, so neither is a scan. The point membership test is likewise a lookup: the normalized restriction carries its own cellId-keyed index as a field, built once per restriction rather than re-derived per probe.
  • Identity at the boundary. Coordinates are registry entries keyed by dimension name; cellIds are opaque internal keys (canonical builtins.toJSON of the ordered factor node ids). No public function takes or returns a "kind:name" string.
  • Factor-spec contract. A codec failure gen-product can decide is a named refusal: the default key refuses a coordinate without id_hash (so nodeAt says not-a-node); a key or entryOf that Nix cannot apply (gen-prelude's isApplicable, so { __functor = _: 5; } included, and a functor reaching no function within 32 __functor steps, named so), an entryOf with a set pattern (read where the node id meets it, by gen-prelude's applicablePatternOf, so { ... }:, { }: and a destructuring functor, nested or not, included), and a key returning a set, list, function or null are malformed-factor, refused when the product is built or the cell addressed. What it cannot decide is the caller's: a supplied entryOf (or the graph's nodeData when entryOf is defaulted) and a supplied key must return or throw on a non-node, never abort. An abort inside their body (a bare entries.${id}, a type error) is not catchable by tryEval, so it ends the evaluation instead of raising not-a-node. Write entryOf = id: entries.${id} or (throw "…"), or use gen-graph's fromRegistry with the defaults.
  • No decomposition. gen-product builds products; it never factors a graph into primes (no Sabidussi–Vizing recognition/cancellation). It answers structural questions only — it never evaluates content.

API Reference

The complete surface is documented in gen-specs/gen-product/REFERENCE.md in the den-architecture papers repository — reference specs live there, not in the library repo. In brief:

# constructors
productN       = kind: factors: <pgraph>;       # kind ∈ cartesian | tensor | strong | lexicographic
cartesian | tensor | strong = f1: f2: <pgraph>;
lexicographic  = { major, minor }: <pgraph>;   # not commutative: the fields carry the order

# addressing (coords are attrsets of registry entries)
nodeAt   = coords: pgraph: <cellId>;
coordsOf = cellId: pgraph: coords;
nodeCoordinates = pgraph: [ coords ];           # lazy lattice enumeration, pinned row-major

# sub-structures
slice     = partialCoords: pgraph: <pgraph>;    # induced sub-product over remaining dims
fiber     = dim: entry: pgraph: <pgraph>;       # preimage of the projection onto dim
projectTo = dim: pgraph: <graph>;               # factor graph + projection metadata
restrict  = membership: pgraph: <pgraph>;       # sparse sub-product (the real fleet)
quotient  = { key ?, classData ?, keepSelfLoops ? }: classOf: graph: <graph>;     # class-share = quotient by class

# specificity lattice
containmentChain = coords: linearization: pgraph: [ <sliceRecord> ];
linearizeByDimOrder = dims: <linearization>;    # count-major — the den fleet default
linearizations.byRank = ranks: <linearization>; # top-rank interleave
latticeGraph = dims: { nodes; edges; };         # 2^D covering relation (Hasse), node.query-traversable

# error-message helpers (not a rendering API)
show.node   = coords: pgraph: string;
show.subset = dims: string;

den convergences

The generality gen-product buys, documented here and wired in den-hoag:

den concept gen-product expression
user@host scoped config a cell of hosts × users
the real fleet restrict(full product, membership relation) — not every user exists on every host
class-share quotient of the host graph by class
matrix instantiation cells enumeration
settings specificity containmentChain, consumed by gen-settings as a layer list
specificity lattice as a query latticeGraph — the covering relation of 2^D as dim-labeled adjacency, traversed by den's node.query

Testing

Law-based suites under ci/, one named test group per law, plus goldens and a brute-force adjacency oracle recomputed independently of the library. gen-graph's mkGraph is a test-only dev input.

nix develop ./ci --command ci                 # run everything, guarded
nix develop ./ci --command ci adjacency-lex   # a single suite, guarded

ci 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.

The library source (lib/**.nix) is verified nixpkgs-lib-free by ci/tests/purity.nix.

Theoretical Foundations

  • Hammack, Imrich & Klavžar — Handbook of Product Graphs (2nd ed., CRC Press, 2011). The four standard products (Part I), the projection/layer vocabulary, the (weak) homomorphism distinctions, and the associativity/commutativity/unit facts — including the direct product's looped unit, which is why gen-product refuses a tensor unit claim for K1. Deliberately not realized: prime factorization, cancellation, and recognition theory.
  • Kahn, G. 1974 — The Semantics of a Simple Language for Parallel Programming (inherited via gen-graph's accessor convention). Demand-driven structure: adjacency accessors force only what a traversal visits — the laziness discipline restated for products.
  • Mokhov, A. 2017 — Algebraic Graphs with Class, §4.6 Preorders and Equivalence Relations — for the condensation only. condensation is his word and is measured there (2 occurrences), with the dependency reading — "tasks 2 and 3 are executed as a step, simultaneously" — that this library inherits. quotient is not his word: it occurs 0 times in the paper, so generalizing from a condensation by strongly-connected component to a quotient by an arbitrary class map is gen-product's own step and is claimed from no text. The strict-homomorphism property (loops allowed) is likewise stated as construction and not as his result — Mokhov's homomorphisms are §5.5, about newtype wrappers preserving the structure of a graph expression.
  • Davey, B. A. & Priestley, H. A. — Introduction to Lattices and Order (2nd ed., CUP, 2002). The boolean lattice 2^D and its covering relation / Hasse diagram (§1.2, §2.5): latticeGraph exposes the cover S ⋖ S∪{d} as dim-labeled adjacency — each cover adds one atom (2^D is atomistic).

About

Graph products over accessor-graphs: cartesian/tensor/strong/lexicographic, cells, slices, sparse restriction, containment chains — pure Nix, den-hoag L2

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages