government

commit cdf2d0cb24bc5f0af81926cf5d0b2a709fd84abc

tree

parent:
3608a1b3f346ed04e58a598e4f092b09f515c3fd

nmyk <nick@nmyk.io>

2026-11-14T15:34:40-05:00

add tree layering

diff --git a/ast/layer.go b/ast/layer.go
new file mode 100644
index 0000000000000000000000000000000000000000..e0f5589f548468e1eed43dcc84835c8a7dbde691
--- /dev/null
+++ b/ast/layer.go
@@ -0,0 +1,86 @@
+package ast
+
+import (
+	"cmp"
+	"errors"
+	"fmt"
+	"slices"
+)
+
+// Edge is a parent->child link in the tree. In the certificates it is a
+// policy mapping, issuerDomainPolicy -> subjectDomainPolicy, in the cert at
+// the parent's depth.
+type Edge struct {
+	Parent, Child *Node
+}
+
+// Layers is the tree cut into one slice per certificate. Cert d (counting
+// from 1) holds the nodes at depth d and the edges leaving them, so it is
+// index d-1 here. Cert 1 lists its nodes as policies; the nodes below are
+// created by the validator from cert d-1's mappings, because certs 2..n
+// assert only anyPolicy.
+//
+// Nodes are not padded down to depth n. An atom above the bottom has no
+// mapping, so it expects only its own OID, and anyPolicy in each later cert
+// makes the validator copy it down one level at a time. That keeps it from
+// being pruned without writing anything for it.
+type Layers struct {
+	Nodes [][]*Node
+	Edges [][]Edge
+}
+
+// Depth is the number of certificates the program needs.
+func (l Layers) Depth() int {
+	return len(l.Nodes)
+}
+
+// Layer puts top-level forms at depth 1 and each list's elements one
+// deeper than the list. A node shared by several parents must sit at a
+// single depth, because a policy node exists at exactly one depth of the
+// graph.
+func Layer(t *Tree) (Layers, error) {
+	if len(t.Forms) == 0 {
+		// An empty policy tree fails validation, so there is no empty
+		// program to encode.
+		return Layers{}, errors.New("a program needs at least one form")
+	}
+	depth := map[*Node]int{}
+	var l Layers
+	var visit func(n *Node, d int) error
+	visit = func(n *Node, d int) error {
+		if prev, seen := depth[n]; seen {
+			if prev != d {
+				return fmt.Errorf("node %d is reached at depths %d and %d", n.ID, prev, d)
+			}
+			return nil
+		}
+		depth[n] = d
+		for len(l.Nodes) < d {
+			l.Nodes = append(l.Nodes, nil)
+			l.Edges = append(l.Edges, nil)
+		}
+		l.Nodes[d-1] = append(l.Nodes[d-1], n)
+		for _, c := range n.Children {
+			l.Edges[d-1] = append(l.Edges[d-1], Edge{n, c})
+			if err := visit(c, d+1); err != nil {
+				return err
+			}
+		}
+		return nil
+	}
+	for _, f := range t.Forms {
+		if err := visit(f, 1); err != nil {
+			return Layers{}, err
+		}
+	}
+
+	// Certificates list policies and mappings in id order, so the same
+	// program always produces the same bytes.
+	for d := range l.Nodes {
+		slices.SortFunc(l.Nodes[d], func(a, b *Node) int { return cmp.Compare(a.ID, b.ID) })
+		slices.SortFunc(l.Edges[d], func(a, b Edge) int {
+			return cmp.Or(cmp.Compare(a.Parent.ID, b.Parent.ID), cmp.Compare(a.Child.ID, b.Child.ID))
+		})
+	}
+	return l, nil
+}
diff --git a/ast/layer_test.go b/ast/layer_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..98170bd6f6e1962029a3bf8c2a718f6825d7eed5
--- /dev/null
+++ b/ast/layer_test.go
@@ -0,0 +1,135 @@
+package ast
+
+import (
+	"strings"
+	"testing"
+)
+
+func mustLayer(t *testing.T, src string) Layers {
+	t.Helper()
+	tree, err := ToTree(mustRead(t, src))
+	if err != nil {
+		t.Fatal(err)
+	}
+	l, err := Layer(tree)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return l
+}
+
+func oidString(t *testing.T, n *Node) string {
+	t.Helper()
+	oid, err := n.OID()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return strings.Replace(oid.String(), Root, "GOV", 1)
+}
+
+// TestWorkedExample checks Layer against the table in DESIGN.md's worked
+// example, written in the same OID notation.
+func TestWorkedExample(t *testing.T) {
+	l := mustLayer(t, "(+ 1 (* 2 3))")
+	wantNodes := [][]string{
+		{"GOV.0.1.1"},
+		{"GOV.0.2.21", "GOV.2.3.49", "GOV.0.4.1"},
+		{"GOV.0.5.23", "GOV.2.6.50", "GOV.2.7.51"},
+	}
+	wantEdges := [][]string{
+		{"GOV.0.1.1 -> GOV.0.2.21", "GOV.0.1.1 -> GOV.2.3.49", "GOV.0.1.1 -> GOV.0.4.1"},
+		{"GOV.0.4.1 -> GOV.0.5.23", "GOV.0.4.1 -> GOV.2.6.50", "GOV.0.4.1 -> GOV.2.7.51"},
+		nil,
+	}
+	if l.Depth() != 3 {
+		t.Fatalf("Depth = %d, want 3", l.Depth())
+	}
+	for d := range wantNodes {
+		var nodes []string
+		for _, n := range l.Nodes[d] {
+			nodes = append(nodes, oidString(t, n))
+		}
+		if got, want := strings.Join(nodes, ", "), strings.Join(wantNodes[d], ", "); got != want {
+			t.Errorf("depth %d nodes = %s, want %s", d+1, got, want)
+		}
+		var edges []string
+		for _, e := range l.Edges[d] {
+			edges = append(edges, oidString(t, e.Parent)+" -> "+oidString(t, e.Child))
+		}
+		if got, want := strings.Join(edges, ", "), strings.Join(wantEdges[d], ", "); got != want {
+			t.Errorf("cert %d mappings = %s, want %s", d+1, got, want)
+		}
+	}
+}
+
+func TestLayerShapes(t *testing.T) {
+	tests := []struct {
+		src   string
+		depth int
+		nodes []int // node count per depth
+		edges []int // mapping count per cert
+	}{
+		{"42", 1, []int{1}, []int{0}},
+		{"1 2 3", 1, []int{3}, []int{0}},
+		{"(f)", 2, []int{1, 1}, []int{1, 0}},
+		// The shallow 1 is not padded: depth 2 has only the list's three
+		// elements, and nothing at depth 3 or 4 is written for the 1.
+		{"1 (a (b (c)))", 4, []int{2, 2, 2, 1}, []int{2, 2, 1, 0}},
+		{"'(a . b)", 3, []int{1, 2, 3}, []int{2, 3, 0}},
+	}
+	for _, tt := range tests {
+		l := mustLayer(t, tt.src)
+		if l.Depth() != tt.depth {
+			t.Errorf("%s: Depth = %d, want %d", tt.src, l.Depth(), tt.depth)
+			continue
+		}
+		for d := 0; d < tt.depth; d++ {
+			if len(l.Nodes[d]) != tt.nodes[d] || len(l.Edges[d]) != tt.edges[d] {
+				t.Errorf("%s: depth %d has %d nodes and %d edges, want %d and %d",
+					tt.src, d+1, len(l.Nodes[d]), len(l.Edges[d]), tt.nodes[d], tt.edges[d])
+			}
+		}
+	}
+}
+
+func TestLayerSortsById(t *testing.T) {
+	// Children listed out of id order.
+	a := &Node{ID: 3, NS: NSInt, Text: "1"}
+	b := &Node{ID: 2, NS: NSInt, Text: "2"}
+	list := &Node{ID: 1, NS: NSBuiltin, Text: ListNode, Children: []*Node{a, b}}
+	l, err := Layer(&Tree{Forms: []*Node{list}})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if l.Nodes[1][0] != b || l.Edges[0][0].Child != b {
+		t.Error("depth 2 is not in id order")
+	}
+}
+
+func TestLayerSharedNode(t *testing.T) {
+	x := &Node{ID: 4, NS: NSSymbol, Text: "x"}
+	f := &Node{ID: 2, NS: NSSymbol, Text: "f"}
+	g := &Node{ID: 6, NS: NSSymbol, Text: "g"}
+	inner := &Node{ID: 5, NS: NSBuiltin, Text: ListNode, Children: []*Node{g, x}}
+
+	sameDepth := &Node{ID: 1, NS: NSBuiltin, Text: ListNode, Children: []*Node{f, x}}
+	other := &Node{ID: 3, NS: NSBuiltin, Text: ListNode, Children: []*Node{g, x}}
+	l, err := Layer(&Tree{Forms: []*Node{sameDepth, other}})
+	if err != nil {
+		t.Fatalf("shared node at one depth: %v", err)
+	}
+	if len(l.Nodes[1]) != 3 || len(l.Edges[0]) != 4 {
+		t.Errorf("depth 2: %d nodes, %d edges; want 3 and 4", len(l.Nodes[1]), len(l.Edges[0]))
+	}
+
+	twoDepths := &Node{ID: 1, NS: NSBuiltin, Text: ListNode, Children: []*Node{f, x, inner}}
+	if _, err := Layer(&Tree{Forms: []*Node{twoDepths}}); err == nil || !strings.Contains(err.Error(), "depths 2 and 3") {
+		t.Errorf("shared node at two depths: error = %v", err)
+	}
+}
+
+func TestLayerEmptyProgram(t *testing.T) {
+	if _, err := Layer(&Tree{}); err == nil {
+		t.Error("empty program layered without error")
+	}
+}