package layoutgraph

import (
	
	
	

	
	
)

const (
	maxEngineTopologyReferences  int64 = 1_000_000
	maxEngineRoutePoints         int64 = limits.MaxEngineRoutePoints
	maxEngineTopologyDepth             = limits.MaxEngineTreeDepth
	maxEnginePreflightWork       int64 = maxEngineTopologyReferences * 8
	maxPooledParentRelationNodes       = 4096
)

type parentRelationScratch struct {
	state  map[*Node]uint8
	depths map[*Node]int
	path   []*Node
}

var parentRelationScratchPool = typedpool.New(func() *parentRelationScratch {
	return &parentRelationScratch{
		state:  make(map[*Node]uint8, 128),
		depths: make(map[*Node]int, 128),
		path:   make([]*Node, 0, 16),
	}
})

func borrowParentRelationScratch( int) (*parentRelationScratch, bool) {
	if  > maxPooledParentRelationNodes {
		return &parentRelationScratch{
			state:  make(map[*Node]uint8, ),
			depths: make(map[*Node]int, ),
			path:   make([]*Node, 0, min(, maxEngineTopologyDepth)),
		}, false
	}
	 := parentRelationScratchPool.Get()
	clear(.state)
	clear(.depths)
	clear(.path[:cap(.path)])
	.path = .path[:0]
	return , true
}

func returnParentRelationScratch( *parentRelationScratch,  bool) {
	if ! {
		return
	}
	clear(.state)
	clear(.depths)
	clear(.path[:cap(.path)])
	.path = .path[:0]
	parentRelationScratchPool.Put()
}

func validateNodeParentRelation(
	 workStepper,
	 map[*Node]struct{},
	 string,
	 func(*Node) *Node,
) error {
	,  := borrowParentRelationScratch(len())
	defer returnParentRelationScratch(, )
	 := .state
	 := .depths
	for  := range  {
		if [] == 2 {
			continue
		}
		.path = .path[:0]
		 := 
		for  != nil && [] == 0 {
			if  := .Step();  != nil {
				return 
			}
			[] = 1
			.path = append(.path, )
			 = ()
		}
		if  != nil && [] == 1 {
			return fmt.Errorf("TALA engine %s cycle detected at node %d", , .ID)
		}
		 := 0
		if  != nil {
			 = []
		}
		for ,  := range slices.Backward(.path) {
			++
			if  > maxEngineTopologyDepth {
				return fmt.Errorf("TALA engine %s depth exceeds limit %d", , maxEngineTopologyDepth)
			}
			[] = 
			[] = 2
		}
	}
	return nil
}

// ancestryParent matches the precedence used by isDescendantOf. Keep this
// separate from container: active cluster and sequence ancestry follows the
// vessel itself, while container follows the vessel's direct container.
func ancestryParent( *Node) *Node {
	if  == nil {
		return nil
	}
	if .Container != nil {
		return .Container
	}
	if .Cluster != nil {
		return .Cluster.Vessel
	}
	if .Sequence != nil {
		return .Sequence.Vessel
	}
	return nil
}

// validateCombineNodeTopology validates node-owned records across all graphs as
// one bounded inventory. Split subgraphs intentionally share the large
// graph-owned entity maps, but each subgraph has its own Nodes and Edges slices
// and may expose additional topology through those nodes. Walking the union
// makes that validation linear in the distinct runtime records rather than in
// the number of subgraphs.
func validateCombineNodeTopology( context.Context,  []*Graph) error {
	,  := limits.NewWorkGuard(, "CombineSubgraphs", maxEngineWorkUnits)
	if  != nil {
		return 
	}
	.SetLimit(maxEnginePreflightWork)

	var  int64
	var  int64
	 := func( string) error {
		if  >= maxEngineTopologyReferences {
			return fmt.Errorf(
				"TALA CombineSubgraphs topology references exceed limit %d while visiting %s",
				maxEngineTopologyReferences,
				,
			)
		}
		++
		return .Step()
	}
	 := func( string, ,  int) error {
		if  <  {
			return fmt.Errorf("TALA CombineSubgraphs %s has invalid slice capacity", )
		}
		 := int64( - )
		if  > maxEngineTopologyReferences- {
			return fmt.Errorf(
				"TALA CombineSubgraphs topology references exceed limit %d while reserving %s capacity",
				maxEngineTopologyReferences,
				,
			)
		}
		 += 
		return .Check()
	}
	 := func( string) error {
		return fmt.Errorf("TALA CombineSubgraphs node-owned topology contains nil %s", )
	}

	 := make(map[*Node]struct{})
	 := make(map[*Edge]struct{})
	 := make(map[*Cluster]struct{})
	 := make(map[*Sequence]struct{})
	 := make(map[*EdgeAbduction]struct{})
	 := make(map[*HerdAssignment]struct{})
	 := make(map[*Hierarchy]struct{})

	var  []*Node
	var  []*Edge
	var  []*Cluster
	var  []*Sequence
	var  []*EdgeAbduction
	var  []*HerdAssignment
	var  []*Hierarchy

	 := func( *Node,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := [];  {
			return nil
		}
		if len() >= maxEngineNodes {
			return fmt.Errorf("TALA CombineSubgraphs unique node count exceeds limit %d", maxEngineNodes)
		}
		[] = struct{}{}
		 = append(, )
		return nil
	}
	 := func( *Edge,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := [];  {
			return nil
		}
		if len() >= maxEngineEdges {
			return fmt.Errorf("TALA CombineSubgraphs unique edge count exceeds limit %d", maxEngineEdges)
		}
		[] = struct{}{}
		 = append(, )
		return nil
	}
	 := func( *Cluster,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *Sequence,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *EdgeAbduction,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *HerdAssignment,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *Hierarchy,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}

	for ,  := range  {
		if  == nil {
			return fmt.Errorf("TALA CombineSubgraphs received a nil graph")
		}
		for ,  := range .Nodes {
			if  == nil {
				return fmt.Errorf("TALA CombineSubgraphs graph node at index %d is nil", )
			}
			if  := (, true, "graph node");  != nil {
				return 
			}
		}
		for ,  := range .Edges {
			if  == nil {
				return fmt.Errorf("TALA CombineSubgraphs graph edge at index %d is nil", )
			}
			if  := (, true, "graph edge");  != nil {
				return 
			}
		}
	}

	var , , ,  int
	var , ,  int
	for  < len() ||  < len() ||  < len() ||
		 < len() ||  < len() ||
		 < len() ||  < len() {
		switch {
		case  < len():
			 := []
			++
			if  := (.Container, false, "node container");  != nil {
				return 
			}
			if  := ("node edges", len(.Edges), cap(.Edges));  != nil {
				return 
			}
			for ,  := range .Edges {
				if  := (, true, "node edge");  != nil {
					return 
				}
			}
			for  := range .Nears {
				if  := (, true, "near node");  != nil {
					return 
				}
			}
			for  := range .LongDistanceNeighborRequirements {
				if  := (, true, "long-distance neighbor requirement key");  != nil {
					return 
				}
			}
			if  := (.Cluster, false, "node cluster");  != nil {
				return 
			}
			if  := (.Sequence, false, "node sequence");  != nil {
				return 
			}
			if  := (.HerdAssignment, false, "node herd assignment");  != nil {
				return 
			}
			if  := (.Hierarchy, false, "node hierarchy");  != nil {
				return 
			}

		case  < len():
			 := []
			++
			if  := (.From, true, "edge source");  != nil {
				return 
			}
			if  := (.To, true, "edge target");  != nil {
				return 
			}
			 := int64(cap(.Points))
			if  > maxEngineRoutePoints- {
				return fmt.Errorf("TALA CombineSubgraphs route point count exceeds limit %d", maxEngineRoutePoints)
			}
			 += 
			for ,  := range .Points {
				if  == nil {
					return ("edge route point")
				}
				if  := .Step();  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			if  := (.Vessel, true, "cluster vessel");  != nil {
				return 
			}
			if  := (.Container, false, "cluster container");  != nil {
				return 
			}
			if  := ("cluster nodes", len(.Nodes), cap(.Nodes));  != nil {
				return 
			}
			for ,  := range .Nodes {
				if  := (, true, "cluster node");  != nil {
					return 
				}
			}
			if  := ("cluster edge abductions", len(.EdgeAbductions), cap(.EdgeAbductions));  != nil {
				return 
			}
			for ,  := range .EdgeAbductions {
				if  := (, true, "cluster edge abduction");  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			if  := (.Vessel, true, "sequence vessel");  != nil {
				return 
			}
			if  := (.Container, false, "sequence container");  != nil {
				return 
			}
			if  := ("sequence nodes", len(.Nodes), cap(.Nodes));  != nil {
				return 
			}
			for ,  := range .Nodes {
				if  := (, true, "sequence node");  != nil {
					return 
				}
			}
			if  := ("sequence edge abductions", len(.EdgeAbductions), cap(.EdgeAbductions));  != nil {
				return 
			}
			for ,  := range .EdgeAbductions {
				if  := (, true, "sequence edge abduction");  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			if  := (.Edge, true, "abducted edge");  != nil {
				return 
			}
			for ,  := range []struct {
				 *Node
				 string
			}{
				{.OriginallyFrom, "abduction original source"},
				{.OriginallyTo, "abduction original target"},
				{.CurrentFrom, "abduction current source"},
				{.CurrentTo, "abduction current target"},
			} {
				if  := (., false, .);  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			for  := range .oppositeSidePaired {
				if  := (, true, "opposite-side herd node");  != nil {
					return 
				}
			}
			for  := range .sameSidePaired {
				if  := (, true, "same-side herd node");  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			for  := range .level {
				if  := (, true, "hierarchy level node");  != nil {
					return 
				}
			}
		}
	}

	if  := validateNodeParentRelation(, , "container parent", func( *Node) *Node {
		return .Container
	});  != nil {
		return 
	}
	if  := validateNodeParentRelation(, , "effective container parent", func( *Node) *Node {
		return .container()
	});  != nil {
		return 
	}
	if  := validateNodeParentRelation(, , "ancestry parent", ancestryParent);  != nil {
		return 
	}
	return .Finish()
}

// validateEngineGraph performs a bounded, iterative walk of every runtime
// topology reference before layout code allocates snapshots or starts work.
// It intentionally validates structural safety rather than semantic layout
// policy, which belongs at the adapter boundary.
func validateEngineGraph( context.Context,  string,  *Graph) error {
	if  == nil {
		return fmt.Errorf("TALA engine requires a graph")
	}
	,  := limits.NewWorkGuard(, , maxEngineWorkUnits)
	if  != nil {
		return 
	}
	.SetLimit(maxEnginePreflightWork)

	var  int64
	var  int64
	 := func( string) error {
		if  >= maxEngineTopologyReferences {
			return fmt.Errorf("TALA engine topology references exceed limit %d while visiting %s", maxEngineTopologyReferences, )
		}
		++
		return .Step()
	}
	 := func( string, ,  int) error {
		if  <  {
			return fmt.Errorf("TALA engine %s has invalid slice capacity", )
		}
		 := int64( - )
		if  > maxEngineTopologyReferences- {
			return fmt.Errorf("TALA engine topology references exceed limit %d while reserving %s capacity", maxEngineTopologyReferences, )
		}
		 += 
		return .Check()
	}
	 := func( string) error {
		return fmt.Errorf("TALA engine topology contains nil %s", )
	}

	 := make(map[*Node]struct{})
	 := make(map[*Edge]struct{})
	 := make(map[*Cluster]struct{})
	 := make(map[*Sequence]struct{})
	 := make(map[*Tree]struct{})
	 := make(map[*EdgeAbduction]struct{})
	 := make(map[*HerdAssignment]struct{})
	 := make(map[*Hierarchy]struct{})

	var  []*Node
	var  []*Edge
	var  []*Cluster
	var  []*Sequence
	var  []*Tree
	var  []*EdgeAbduction
	var  []*HerdAssignment
	var  []*Hierarchy

	 := func( *Node,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := [];  {
			return nil
		}
		if len() >= maxEngineNodes {
			return fmt.Errorf("TALA engine unique node count exceeds limit %d", maxEngineNodes)
		}
		[] = struct{}{}
		 = append(, )
		return nil
	}
	 := func( *Edge,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := [];  {
			return nil
		}
		if len() >= maxEngineEdges {
			return fmt.Errorf("TALA engine unique edge count exceeds limit %d", maxEngineEdges)
		}
		[] = struct{}{}
		 = append(, )
		return nil
	}
	 := func( *Cluster,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *Sequence,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *Tree,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *EdgeAbduction,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *HerdAssignment,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}
	 := func( *Hierarchy,  bool,  string) error {
		if  == nil {
			if  {
				return ()
			}
			return nil
		}
		if  := ();  != nil {
			return 
		}
		if ,  := []; ! {
			[] = struct{}{}
			 = append(, )
		}
		return nil
	}

	if  := ("graph nodes", len(.Nodes), cap(.Nodes));  != nil {
		return 
	}
	for ,  := range .Nodes {
		if  == nil {
			return fmt.Errorf("graph node at index %d is nil", )
		}
		if  := (, true, "graph node");  != nil {
			return 
		}
	}
	if  := ("graph edges", len(.Edges), cap(.Edges));  != nil {
		return 
	}
	for ,  := range .Edges {
		if  == nil {
			return fmt.Errorf("graph edge at index %d is nil", )
		}
		if .From == nil || .To == nil {
			return fmt.Errorf("graph edge %d has unplaced or missing endpoints", .entityID())
		}
		if  := (, true, "graph edge");  != nil {
			return 
		}
	}

	for ,  := range .Containers {
		if  := (, false, "container key");  != nil {
			return 
		}
		if  := ("container children", len(), cap());  != nil {
			return 
		}
		for ,  := range  {
			if  := (, true, "container child");  != nil {
				return 
			}
		}
	}
	for ,  := range .Clusters {
		if  := (, true, "cluster vessel key");  != nil {
			return 
		}
		if  := (, true, "cluster record");  != nil {
			return 
		}
	}
	for ,  := range .Sequences {
		if  := (, true, "sequence vessel key");  != nil {
			return 
		}
		if  := (, true, "sequence record");  != nil {
			return 
		}
	}
	for ,  := range .Trees {
		// Root-sentinel trees are intentionally keyed by nil.
		if  := (, false, "tree root key");  != nil {
			return 
		}
		if  := ("tree roots", len(), cap());  != nil {
			return 
		}
		for ,  := range  {
			if  := (, true, "tree root");  != nil {
				return 
			}
		}
	}
	for ,  := range .NodeToTree {
		if  := (, true, "node-to-tree key");  != nil {
			return 
		}
		if  := (, true, "node-to-tree value");  != nil {
			return 
		}
	}
	for ,  := range .Hubs {
		if  := (, true, "hub key");  != nil {
			return 
		}
		if  := ("hub spokes", len(), cap());  != nil {
			return 
		}
		for ,  := range  {
			if  := (, true, "hub spoke");  != nil {
				return 
			}
		}
	}
	for  := range .Directions {
		if  := (, false, "direction key");  != nil {
			return 
		}
	}
	for ,  := range .CommonUncleSiblings {
		if  := (, true, "common-sibling key");  != nil {
			return 
		}
		if  := ("common siblings", len(), cap());  != nil {
			return 
		}
		for ,  := range  {
			if  := (, true, "common sibling");  != nil {
				return 
			}
		}
	}

	var , , ,  int
	var , , ,  int
	for  < len() ||  < len() ||  < len() ||
		 < len() ||  < len() ||  < len() ||
		 < len() ||  < len() {
		switch {
		case  < len():
			 := []
			++
			if  := (.Container, false, "node container");  != nil {
				return 
			}
			if  := ("node edges", len(.Edges), cap(.Edges));  != nil {
				return 
			}
			for ,  := range .Edges {
				if  := (, true, "node edge");  != nil {
					return 
				}
			}
			for  := range .Nears {
				if  := (, true, "near node");  != nil {
					return 
				}
			}
			for  := range .LongDistanceNeighborRequirements {
				if  := (, true, "long-distance neighbor requirement key");  != nil {
					return 
				}
			}
			if  := (.Cluster, false, "node cluster");  != nil {
				return 
			}
			if  := (.Sequence, false, "node sequence");  != nil {
				return 
			}
			if  := (.HerdAssignment, false, "node herd assignment");  != nil {
				return 
			}
			if  := (.Hierarchy, false, "node hierarchy");  != nil {
				return 
			}

		case  < len():
			 := []
			++
			if  := (.From, true, "edge source");  != nil {
				return 
			}
			if  := (.To, true, "edge target");  != nil {
				return 
			}
			 := int64(cap(.Points))
			if  > maxEngineRoutePoints- {
				return fmt.Errorf("TALA engine route point count exceeds limit %d", maxEngineRoutePoints)
			}
			 += 
			for ,  := range .Points {
				if  == nil {
					return ("edge route point")
				}
				if  := .Step();  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			if  := (.Vessel, true, "cluster vessel");  != nil {
				return 
			}
			if  := (.Container, false, "cluster container");  != nil {
				return 
			}
			if  := ("cluster nodes", len(.Nodes), cap(.Nodes));  != nil {
				return 
			}
			for ,  := range .Nodes {
				if  := (, true, "cluster node");  != nil {
					return 
				}
			}
			if  := ("cluster edge abductions", len(.EdgeAbductions), cap(.EdgeAbductions));  != nil {
				return 
			}
			for ,  := range .EdgeAbductions {
				if  := (, true, "cluster edge abduction");  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			if  := (.Vessel, true, "sequence vessel");  != nil {
				return 
			}
			if  := (.Container, false, "sequence container");  != nil {
				return 
			}
			if  := ("sequence nodes", len(.Nodes), cap(.Nodes));  != nil {
				return 
			}
			for ,  := range .Nodes {
				if  := (, true, "sequence node");  != nil {
					return 
				}
			}
			if  := ("sequence edge abductions", len(.EdgeAbductions), cap(.EdgeAbductions));  != nil {
				return 
			}
			for ,  := range .EdgeAbductions {
				if  := (, true, "sequence edge abduction");  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			if  := (.Node, true, "tree node");  != nil {
				return 
			}
			if  := (.Parent, false, "tree parent");  != nil {
				return 
			}
			if  := (.SentinelEdge, false, "tree sentinel edge");  != nil {
				return 
			}
			if  := ("tree children", len(.Children), cap(.Children));  != nil {
				return 
			}
			for ,  := range .Children {
				if  := (, true, "tree child");  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			if  := (.Edge, true, "abducted edge");  != nil {
				return 
			}
			for ,  := range []struct {
				 *Node
				 string
			}{
				{.OriginallyFrom, "abduction original source"},
				{.OriginallyTo, "abduction original target"},
				{.CurrentFrom, "abduction current source"},
				{.CurrentTo, "abduction current target"},
			} {
				if  := (., false, .);  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			for  := range .oppositeSidePaired {
				if  := (, true, "opposite-side herd node");  != nil {
					return 
				}
			}
			for  := range .sameSidePaired {
				if  := (, true, "same-side herd node");  != nil {
					return 
				}
			}

		case  < len():
			 := []
			++
			for  := range .level {
				if  := (, true, "hierarchy level node");  != nil {
					return 
				}
			}
		}
	}

	// Validate parent chains independently of the declared container map so a
	// stale or hidden parent pointer cannot introduce recursion or excessive
	// depth into later snapshot/layout walks.
	if  := validateNodeParentRelation(, , "container parent", func( *Node) *Node {
		return .Container
	});  != nil {
		return 
	}

	// Active clusters and sequences override Node.Container in container.
	// Validate that effective parent relation separately: ancestry helpers walk
	// it directly and would otherwise recurse forever even when the raw
	// Container pointers form a valid forest.
	if  := validateNodeParentRelation(, , "effective container parent", func( *Node) *Node {
		return .container()
	});  != nil {
		return 
	}
	if  := validateNodeParentRelation(, , "ancestry parent", ancestryParent);  != nil {
		return 
	}

	// Every descendant walk in the engine follows the union of direct
	// containers, active cluster membership, and active sequence membership.
	// Validate that combined ownership graph, not just Containers, so later
	// recursive movement/snapshot helpers have a firm depth bound.
	type  struct {
		     *Node
		 []*Node
		    int
	}
	 := func( *Node) ([]*Node, error) {
		var  []*Node
		if  == nil || .isContainer {
			 = append(, .Containers[]...)
		}
		if  != nil && .isClusterVessel {
			 := .Clusters[]
			if  == nil {
				return nil, fmt.Errorf("TALA engine cluster vessel %d has no cluster record", .ID)
			}
			 = append(, .Nodes...)
		}
		if ,  := .Sequences[];  {
			if  == nil {
				return nil, ("sequence record")
			}
			 = append(, .Nodes...)
		}
		return , nil
	}
	 := make(map[*Node]uint8, len()+1)
	 := make(map[*Node]int, len()+1)
	 := make([]*Node, 0, len()+1)
	if ,  := .Containers[nil];  {
		 = append(, nil)
	}
	for  := range  {
		if  != nil {
			 = append(, )
		}
	}
	for ,  := range  {
		if [] != 0 {
			continue
		}
		,  := ()
		if  != nil {
			return 
		}
		[] = 1
		 := []{{: , : }}
		for len() > 0 {
			 := &[len()-1]
			if . >= len(.) {
				 := 1
				if . == nil {
					 = 0
				}
				 := 
				for ,  := range . {
					if  :=  + [];  >  {
						 = 
					}
				}
				if  > maxEngineTopologyDepth {
					return fmt.Errorf("TALA engine descendant depth exceeds limit %d", maxEngineTopologyDepth)
				}
				[.] = 
				[.] = 2
				 = [:len()-1]
				continue
			}
			 := .[.]
			.++
			if  := .Step();  != nil {
				return 
			}
			switch [] {
			case 1:
				return fmt.Errorf("TALA engine descendant cycle detected at node %d", .ID)
			case 0:
				,  := ()
				if  != nil {
					return 
				}
				[] = 1
				 = append(, {: , : })
			}
		}
	}

	// Tree child links and parent links are both traversed because either side
	// can be stale independently.
	type  struct {
		  *Tree
		 int
	}
	 := make(map[*Tree]uint8, len())
	 := make(map[*Tree]int, len())
	for  := range  {
		if [] != 0 {
			continue
		}
		[] = 1
		 := []{{: }}
		for len() > 0 {
			 := &[len()-1]
			if . >= len(..Children) {
				 := 1
				for ,  := range ..Children {
					if  := [] + 1;  >  {
						 = 
					}
				}
				if  > maxEngineTopologyDepth {
					return fmt.Errorf("TALA engine tree depth exceeds limit %d", maxEngineTopologyDepth)
				}
				[.] = 
				[.] = 2
				 = [:len()-1]
				continue
			}
			 := ..Children[.]
			.++
			if  := .Step();  != nil {
				return 
			}
			switch [] {
			case 1:
				return fmt.Errorf("TALA engine tree child cycle detected")
			case 0:
				[] = 1
				 = append(, {: })
			}
		}
	}
	 := make(map[*Tree]uint8, len())
	 := make(map[*Tree]int, len())
	for  := range  {
		if [] == 2 {
			continue
		}
		var  []*Tree
		 := 
		for  != nil && [] == 0 {
			if  := .Step();  != nil {
				return 
			}
			[] = 1
			 = append(, )
			 = .Parent
		}
		if  != nil && [] == 1 {
			return fmt.Errorf("TALA engine tree parent cycle detected")
		}
		 := 0
		if  != nil {
			 = []
		}
		for ,  := range slices.Backward() {
			++
			if  > maxEngineTopologyDepth {
				return fmt.Errorf("TALA engine tree depth exceeds limit %d", maxEngineTopologyDepth)
			}
			[] = 
			[] = 2
		}
	}

	// A serialized tree is a value tree, not a graph: every runtime Tree must
	// therefore have exactly one owning root/parent path. The inventory above
	// deliberately de-duplicates pointers to keep preflight work linear, so do a
	// separate forest walk before serialization. Without this check, a small DAG
	// whose children repeatedly share the same subtree would expand
	// exponentially while Serialize copied it into graph JSON values.
	type  struct {
		   *Tree
		 *Tree
	}
	 := make(map[*Tree]*Tree, len())
	 := make(map[*Node]*Tree, len())
	for ,  := range .Trees {
		for ,  := range  {
			 := []{{: }}
			for len() > 0 {
				 := [len()-1]
				 = [:len()-1]
				if  := .Step();  != nil {
					return 
				}
				if ,  := [.];  {
					if . == nil {
						return fmt.Errorf("TALA engine tree is listed as more than one root")
					}
					if  == . {
						return fmt.Errorf("TALA engine tree is repeated under one parent")
					}
					return fmt.Errorf("TALA engine tree is shared by multiple parents")
				}
				[.] = .
				if ,  := [..Node];  &&  != . {
					return fmt.Errorf("TALA engine node %d is owned by multiple trees", ..Node.ID)
				}
				[..Node] = .

				for ,  := range slices.Backward(..Children) {

					if .Parent != . {
						return fmt.Errorf("TALA engine tree child has an inconsistent parent")
					}
					 = append(, {: , : .})
				}
			}
		}
	}
	for ,  := range .Trees {
		for ,  := range  {
			if .Parent == nil {
				continue
			}
			// Placement-tree construction temporarily attaches an installed root beneath a
			// placement-only wrapper. That wrapper is not part of Graph.Trees, but
			// its backlink must still be exact. An installed parent would instead
			// give this root two locations in the serialized forest.
			if ,  := [.Parent];  {
				return fmt.Errorf("TALA engine tree root also has an installed parent")
			}
			 := 0
			for ,  := range .Parent.Children {
				if  := .Step();  != nil {
					return 
				}
				if  ==  {
					++
				}
			}
			if  != 1 {
				return fmt.Errorf("TALA engine tree root has an inconsistent placement parent")
			}
		}
	}

	// NodeToTree is derived state and may legitimately be absent on a freshly
	// constructed graph. When present alongside an installed forest, however,
	// it must be the exact inverse of Tree.Node; accepting partial or orphaned
	// aliases would make later layout helpers observe a different topology from
	// the serializer.
	for ,  := range .NodeToTree {
		if .Node !=  {
			return fmt.Errorf("TALA engine node-to-tree alias does not match the tree node")
		}
		if len() > 0 {
			if ,  := []; ! {
				return fmt.Errorf("TALA engine node-to-tree alias references a tree outside the installed forest")
			}
		}
	}
	if len(.NodeToTree) > 0 && len() > 0 {
		if len(.NodeToTree) != len() {
			return fmt.Errorf("TALA engine node-to-tree aliases do not cover the installed forest")
		}
		for ,  := range  {
			if .NodeToTree[] !=  {
				return fmt.Errorf("TALA engine node-to-tree aliases do not match the installed forest")
			}
		}
	}

	return .Finish()
}