package placement

import (
	
	
	
	

	

	
	
)

const (
	// A work limit bounds CPU, but retaining every unique placement until that
	// limit is reached could still consume too much memory. This independent cap
	// keeps the reusable placement buffer and its deduplication map predictable.
	maxOptimizerPlacementCandidates = 1_000_000
	maxRetainedPlacementCandidates  = 16_384
)

func optimizerIsDescendantOf(,  *layoutgraph.Node,  *limits.OptimizationWorkGuard) (bool, error) {
	 := make(map[*layoutgraph.Node]struct{})
	for  := ; ; {
		if  := .Step();  != nil {
			return false, 
		}
		if  ==  {
			return true, nil
		}
		if  == nil {
			return  == nil, nil
		}
		if ,  := [];  {
			return false, fmt.Errorf("TALA %s found a cycle in node ancestry at %s", .Location(), .DebugID())
		}
		if len() >= limits.MaxEngineNodes {
			return false, fmt.Errorf("TALA %s ancestry exceeds node limit %d", .Location(), limits.MaxEngineNodes)
		}
		[] = struct{}{}
		switch {
		case .Container != nil:
			 = .Container
		case .Cluster != nil:
			 = .Cluster.Vessel
		case .Sequence != nil:
			 = .Sequence.Vessel
		default:
			 = nil
		}
	}
}

func optimizerTreeRoot( *layoutgraph.Tree,  *limits.OptimizationWorkGuard) (*layoutgraph.Tree, error) {
	 := make(map[*layoutgraph.Tree]struct{})
	for  != nil && .Parent != nil {
		if  := .Step();  != nil {
			return nil, 
		}
		if ,  := [];  {
			return nil, fmt.Errorf("TALA %s found a cycle in tree ancestry", .Location())
		}
		if len() >= limits.MaxEngineNodes {
			return nil, fmt.Errorf("TALA %s tree ancestry exceeds node limit %d", .Location(), limits.MaxEngineNodes)
		}
		[] = struct{}{}
		 = .Parent
	}
	return , nil
}

func optimizerFixedOrigin( *layoutgraph.Graph,  *layoutgraph.Node,  *limits.OptimizationWorkGuard) (*geo.Point, error) {
	if  == nil {
		return nil, fmt.Errorf("TALA %s fixed-origin lookup requires a graph", .Location())
	}
	if len(.Nodes) > limits.MaxEngineNodes {
		return nil, fmt.Errorf("TALA %s fixed-origin node count exceeds limit %d", .Location(), limits.MaxEngineNodes)
	}
	for ,  := range .Nodes {
		if  := .Step();  != nil {
			return nil, 
		}
		if  == nil || .OwningContainer() !=  {
			continue
		}
		if  := .FixedOrigin();  != nil {
			return , nil
		}
	}
	return nil, nil
}

func optimizerOrderedNears( *layoutgraph.Node,  *limits.OptimizationWorkGuard) ([]*layoutgraph.Node, error) {
	if  == nil {
		return nil, fmt.Errorf("TALA %s cannot order nears for a nil node", .Location())
	}
	if len(.Nears) > limits.MaxEngineNodes {
		return nil, fmt.Errorf("TALA %s near count exceeds limit %d", .Location(), limits.MaxEngineNodes)
	}
	 := make([]*layoutgraph.Node, 0, len(.Nears))
	for  := range .Nears {
		if  := .Step();  != nil {
			return nil, 
		}
		if  == nil {
			return nil, fmt.Errorf("TALA %s found a nil near on %s", .Location(), .DebugID())
		}
		 = append(, )
	}
	if  := .AddSort(len());  != nil {
		return nil, 
	}
	layoutgraph.SortNodesByID()
	return , nil
}

func appendBoundedOptimizerNodes(,  []*layoutgraph.Node,  *limits.OptimizationWorkGuard) ([]*layoutgraph.Node, error) {
	if int64(len()) > layoutgraph.MaxTopologyReferences-int64(len()) {
		return nil, fmt.Errorf("TALA %s optimizer node references exceed limit %d", .Location(), layoutgraph.MaxTopologyReferences)
	}
	return append(, ...), nil
}

func appendOptimizerTreeNears( []*layoutgraph.Node,  *layoutgraph.Tree,  *limits.OptimizationWorkGuard) ([]*layoutgraph.Node, error) {
	if  == nil {
		return , nil
	}
	 := []*layoutgraph.Tree{}
	 := map[*layoutgraph.Tree]struct{}{: {}}
	for len() > 0 {
		if  := .Step();  != nil {
			return nil, 
		}
		 := len() - 1
		 := []
		 = [:]
		if  == nil {
			return nil, fmt.Errorf("TALA %s found a nil tree node", .Location())
		}
		if .Node == nil {
			return nil, fmt.Errorf("TALA %s found a tree entry without a node", .Location())
		}
		,  := optimizerOrderedNears(.Node, )
		if  != nil {
			return nil, 
		}
		,  = appendBoundedOptimizerNodes(, , )
		if  != nil {
			return nil, 
		}
		if len(.Children) > limits.MaxEngineNodes {
			return nil, fmt.Errorf("TALA %s tree child references exceed limit %d", .Location(), limits.MaxEngineNodes)
		}
		for ,  := range slices.Backward(.Children) {
			if  := .Step();  != nil {
				return nil, 
			}

			if  == nil {
				return nil, fmt.Errorf("TALA %s found a nil tree child", .Location())
			}
			if ,  := [];  {
				return nil, fmt.Errorf("TALA %s found a cycle or shared child in a tree", .Location())
			}
			if len() >= limits.MaxEngineNodes {
				return nil, fmt.Errorf("TALA %s tree exceeds node limit %d", .Location(), limits.MaxEngineNodes)
			}
			[] = struct{}{}
			 = append(, )
		}
	}
	return , nil
}

func optimizerAdjacents( *layoutgraph.Node,  []*layoutgraph.EdgeAbduction,  *limits.OptimizationWorkGuard) ([]*layoutgraph.Node, error) {
	if  == nil || .Graph == nil {
		return nil, fmt.Errorf("TALA %s adjacency lookup requires a node with a graph", .Location())
	}
	if len(.Edges) > limits.MaxEngineEdges || len() > limits.MaxEngineEdges {
		return nil, fmt.Errorf("TALA %s adjacency inputs exceed edge limit %d", .Location(), limits.MaxEngineEdges)
	}
	 := make([]*layoutgraph.Node, 0, len(.Edges))
	 := borrowEdgeAbductionBools(len())
	defer returnEdgeAbductionBools()
	 := .values
	for ,  := range .Edges {
		if  := .Step();  != nil {
			return nil, 
		}
		if  == nil || (.From !=  && .To != ) {
			return nil, fmt.Errorf("TALA %s found a malformed incident edge on %s", .Location(), .DebugID())
		}
		 := .Adjacent()
		if  == nil || .TopLeft == nil {
			continue
		}
		 := 
		for ,  := range  {
			if  := .Step();  != nil {
				return nil, 
			}
			if  == nil {
				return nil, fmt.Errorf("TALA %s found a nil edge abduction", .Location())
			}
			if [] {
				continue
			}
			if .CurrentFrom ==  && .CurrentTo ==  && .OriginallyTo != nil {
				[] = true
				 = .OriginallyTo
				break
			}
			if .CurrentFrom ==  && .CurrentTo ==  && .OriginallyFrom != nil {
				[] = true
				 = .OriginallyFrom
				break
			}
		}
		 = append(, )
	}
	if len() != 0 {
		return , nil
	}

	,  := optimizerOrderedNears(, )
	if  != nil {
		return nil, 
	}
	for ,  := range  {
		if .Cluster.IsActive() {
			 = .Cluster.Vessel
		} else if .Sequence.IsActive() {
			 = .Sequence.Vessel
		}
		if ,  := .Graph.NodeToTree[];  {
			,  := optimizerTreeRoot(, )
			if  != nil {
				return nil, 
			}
			if  == nil || .SentinelNode() == nil {
				return nil, fmt.Errorf("TALA %s found a tree without a sentinel", .Location())
			}
			 = .SentinelNode()
		}
		if  == nil || .TopLeft == nil {
			continue
		}
		,  := optimizerIsDescendantOf(, .Container, )
		if  != nil {
			return nil, 
		}
		if  {
			 = append(, )
		}
	}
	if len() != 0 {
		return , nil
	}

	var  []*layoutgraph.Node
	if .IsClusterVessel() {
		 := .Graph.Clusters[]
		if  == nil {
			return nil, fmt.Errorf("TALA %s found a cluster vessel without a cluster", .Location())
		}
		for ,  := range .Nodes {
			if  := .Step();  != nil {
				return nil, 
			}
			,  := optimizerOrderedNears(, )
			if  != nil {
				return nil, 
			}
			,  = appendBoundedOptimizerNodes(, , )
			if  != nil {
				return nil, 
			}
		}
	}
	if  := .Graph.Sequences[];  != nil {
		for ,  := range .Nodes {
			if  := .Step();  != nil {
				return nil, 
			}
			,  := optimizerOrderedNears(, )
			if  != nil {
				return nil, 
			}
			,  = appendBoundedOptimizerNodes(, , )
			if  != nil {
				return nil, 
			}
		}
	}
	if len(.Graph.Trees[]) > limits.MaxEngineNodes {
		return nil, fmt.Errorf("TALA %s tree roots exceed node limit %d", .Location(), limits.MaxEngineNodes)
	}
	for ,  := range .Graph.Trees[] {
		,  = appendOptimizerTreeNears(, , )
		if  != nil {
			return nil, 
		}
	}
	for ,  := range  {
		if  := .Step();  != nil {
			return nil, 
		}
		 := 
		if .Cluster.IsActive() {
			 = .Cluster.Vessel
		} else if .Sequence.IsActive() {
			 = .Sequence.Vessel
		}
		if ,  := .Graph.NodeToTree[];  {
			,  := optimizerTreeRoot(, )
			if  != nil {
				return nil, 
			}
			if  == nil || .SentinelNode() == nil {
				return nil, fmt.Errorf("TALA %s found a tree without a sentinel", .Location())
			}
			 = .SentinelNode()
		}
		if  != nil && .TopLeft != nil {
			 = append(, )
		}
	}
	return , nil
}

func optimizerMedian( layoutgraph.Nodes,  bool,  *limits.OptimizationWorkGuard) (float64, float64, error) {
	if len() == 0 {
		return 0, 0, fmt.Errorf("TALA %s cannot compute a median without positioned neighbors", .Location())
	}
	if int64(len()) > layoutgraph.MaxTopologyReferences {
		return 0, 0, fmt.Errorf("TALA %s median inputs exceed limit %d", .Location(), layoutgraph.MaxTopologyReferences)
	}
	if len() == 1 {
		 := [0]
		if  := .Step();  != nil {
			return 0, 0, 
		}
		if  == nil || .TopLeft == nil {
			return 0, 0, fmt.Errorf("TALA %s cannot compute a median with an unpositioned neighbor", .Location())
		}
		if  := .AddSort(1);  != nil {
			return 0, 0, 
		}
		if  := .AddSort(1);  != nil {
			return 0, 0, 
		}
		if  {
			 := .Graph.CellSize
			if  <= 0 || math.IsNaN() || math.IsInf(, 0) {
				return 0, 0, fmt.Errorf("TALA %s requires a finite positive cell size", .Location())
			}
			return (.TopLeft.X + .Width/2) / , (.TopLeft.Y + .Height/2) / , nil
		}
		return .TopLeft.X + 0.5, .TopLeft.Y + 0.5, nil
	}
	 := make([]*layoutgraph.Node, len())
	 := make([]*layoutgraph.Node, len())
	for ,  := range  {
		if  := .Step();  != nil {
			return 0, 0, 
		}
		if  == nil || .TopLeft == nil {
			return 0, 0, fmt.Errorf("TALA %s cannot compute a median with an unpositioned neighbor", .Location())
		}
		[] = 
		[] = 
	}
	if  := .AddSort(len());  != nil {
		return 0, 0, 
	}
	sort.Slice(, func(,  int) bool {
		,  := [], []
		,  := .TopLeft.X, .TopLeft.X
		if  {
			 += .Width / 2
			 += .Width / 2
		}
		if  ==  {
			return .ID < .ID
		}
		return  < 
	})
	if  := .AddSort(len());  != nil {
		return 0, 0, 
	}
	sort.Slice(, func(,  int) bool {
		,  := [], []
		,  := .TopLeft.Y, .TopLeft.Y
		if  {
			 += .Height / 2
			 += .Height / 2
		}
		if  ==  {
			return .ID < .ID
		}
		return  < 
	})

	 := len() / 2
	var ,  float64
	if  {
		 = [].TopLeft.X + [].Width/2
		 = [].TopLeft.Y + [].Height/2
		if len()%2 == 0 {
			 = ( + [-1].TopLeft.X + [-1].Width/2) / 2
			 = ( + [-1].TopLeft.Y + [-1].Height/2) / 2
		}
		 := [0].Graph.CellSize
		if  <= 0 || math.IsNaN() || math.IsInf(, 0) {
			return 0, 0, fmt.Errorf("TALA %s requires a finite positive cell size", .Location())
		}
		 /= 
		 /= 
	} else {
		 = [].TopLeft.X + 0.5
		 = [].TopLeft.Y + 0.5
		if len()%2 == 0 {
			 = ( + [-1].TopLeft.X) / 2
			 = ( + [-1].TopLeft.Y) / 2
		}
	}
	return , , nil
}

func optimizerMedianToNeighbors( *layoutgraph.Node,  bool,  []*layoutgraph.EdgeAbduction,  *limits.OptimizationWorkGuard) (float64, float64, error) {
	,  := optimizerAdjacents(, , )
	if  != nil {
		return 0, 0, 
	}
	return optimizerMedian(layoutgraph.Nodes(), , )
}

func optimizerDoesOverlap( *layoutgraph.Node,  *geo.Point,  []*layoutgraph.Node,  *limits.OptimizationWorkGuard) (bool, error) {
	if  == nil || .Graph == nil ||  == nil {
		return false, fmt.Errorf("TALA %s overlap check requires a node, graph, and point", .Location())
	}
	if len(.Graph.Nodes) > limits.MaxEngineNodes || len() > limits.MaxEngineNodes {
		return false, fmt.Errorf("TALA %s overlap inputs exceed node limit %d", .Location(), limits.MaxEngineNodes)
	}
	 := .X + .Width
	 := .Y + .Height
	for ,  := range .Graph.Nodes {
		if  := .Step();  != nil {
			return false, 
		}
		if  == nil {
			return false, fmt.Errorf("TALA %s found a nil graph node", .Location())
		}
		if  ==  {
			continue
		}
		 := false
		for ,  := range  {
			if  := .Step();  != nil {
				return false, 
			}
			if  ==  {
				 = true
				break
			}
		}
		if  || .TopLeft == nil {
			continue
		}
		const  = 500.0
		if .X > .TopLeft.X+.Width+ ||
			.X+.Width+ < .TopLeft.X ||
			.Y > .TopLeft.Y+.Height+ ||
			.Y+.Height+ < .TopLeft.Y {
			continue
		}
		if  := .Add(uint64(len(.Edges)));  != nil {
			return false, 
		}
		 := float64(.DeltaTo(, ))
		if .X < .TopLeft.X+.Width+ && + > .TopLeft.X &&
			.Y < .TopLeft.Y+.Height+ && + > .TopLeft.Y {
			return true, nil
		}
	}
	return false, nil
}

func optimizerIsOccupied( *layoutgraph.Graph,  *geo.Point,  *limits.OptimizationWorkGuard) (*layoutgraph.Node, bool, error) {
	if  == nil ||  == nil {
		return nil, false, fmt.Errorf("TALA %s occupancy check requires a graph and point", .Location())
	}
	if len(.Nodes) > limits.MaxEngineNodes {
		return nil, false, fmt.Errorf("TALA %s occupancy node count exceeds limit %d", .Location(), limits.MaxEngineNodes)
	}
	for ,  := range .Nodes {
		if  := .Step();  != nil {
			return nil, false, 
		}
		if  == nil {
			return nil, false, fmt.Errorf("TALA %s found a nil graph node", .Location())
		}
		if .TopLeft != nil &&  != nil && nonNilEquals(.TopLeft, ) {
			return , true, nil
		}
	}
	return nil, false, nil
}

func optimizerCanMove( *layoutgraph.Node,  *geo.Point,  bool,  *limits.OptimizationWorkGuard) (bool, error) {
	if  == nil || .Graph == nil ||  == nil {
		return false, fmt.Errorf("TALA %s movement check requires a node, graph, and point", .Location())
	}
	if nonNilEquals(.TopLeft, ) {
		return true, nil
	}
	, ,  := optimizerIsOccupied(.Graph, , )
	if  != nil ||  || ! {
		return ! &&  == nil, 
	}
	,  := optimizerDoesOverlap(, , nil, )
	return ! &&  == nil, 
}

// chargeOptimizerScoring accounts for the nested edge, abduction, blocker, and
// symmetry scans performed by the legacy scoring helpers. Those helpers poll
// context internally; this conservative charge additionally makes repeated
// candidate scoring obey the shared operation budget.
func chargeOptimizerScoring( *layoutgraph.Node,  []*layoutgraph.EdgeAbduction,  bool,  *limits.OptimizationWorkGuard) error {
	if  == nil || .Graph == nil {
		return fmt.Errorf("TALA %s scoring requires a node with a graph", .Location())
	}
	 := uint64(len(.Edges) + 1)
	 := uint64(len(.Graph.Nodes) + len() + 1)
	if  {
		if math.MaxUint64- <  {
			return fmt.Errorf("%w: %s scoring work arithmetic overflow", limits.ErrOptimizationResourceLimit, .Location())
		}
		 += 
	}
	return .AddProduct(, )
}

// chargeOptimizerTranspose bounds the independent reachability, rotation, and
// scoring guards used by transpose under the optimizer's single operation
// budget. Cheap eligibility checks avoid charging the worst case when
// transpose will return immediately.
func chargeOptimizerTranspose( *layoutgraph.Graph,  *layoutgraph.Node,  []*layoutgraph.EdgeAbduction,  *limits.OptimizationWorkGuard) error {
	if  == nil ||  == nil || .Graph == nil {
		return fmt.Errorf("TALA %s transpose requires a node with a graph", .Location())
	}
	if len(.Nodes) > limits.MaxEngineNodes || len(.Edges) > limits.MaxEngineEdges || len() > limits.MaxEngineEdges {
		return fmt.Errorf("TALA %s transpose inputs exceed engine limits", .Location())
	}
	for ,  := range  {
		if  := .Step();  != nil {
			return 
		}
		if  == nil {
			return fmt.Errorf("TALA %s found a nil edge abduction", .Location())
		}
	}
	if .Hierarchy != nil || .FixedTopLeft != nil || len(.Edges) < 1 || len(.Edges) > 2 {
		return .Step()
	}
	if ,  := .NodeToTree[];  || .IsTreeSentinel() {
		return .Step()
	}

	 := uint64(len(.Nodes) + 1)
	 := uint64(len(.Edges) + 1)
	 := uint64(len() + 1)
	// Reachability is performed several times while selecting a rotation side.
	for range 6 {
		if  := .Add( +  + );  != nil {
			return 
		}
	}
	// At most four trial rotations and one committed rotation are scored.
	for range 5 {
		if  == nil {
			if  := .AddProduct(, );  != nil {
				return 
			}
			if  := .AddProduct(, );  != nil {
				return 
			}
		} else if  := .AddProduct(uint64(len(.Edges)+1), +);  != nil {
			return 
		}
	}
	// Rotating containers can translate descendants for each trial.
	for range 4 {
		if  := .AddProduct(, );  != nil {
			return 
		}
	}
	return nil
}

func optimizerDescendants( *layoutgraph.Node,  *limits.OptimizationWorkGuard) ([]*layoutgraph.Node, error) {
	if  == nil || .Graph == nil {
		return nil, fmt.Errorf("TALA %s movement requires a node with a graph", .Location())
	}
	 := .Graph
	type  struct {
		 *layoutgraph.Node
	}
	 := map[*layoutgraph.Node]struct{}{: {}}
	 := make([], 0)
	 := func( *layoutgraph.Node) error {
		if  := .Step();  != nil {
			return 
		}
		if  == nil {
			return fmt.Errorf("TALA %s found a nil descendant", .Location())
		}
		if ,  := [];  {
			return nil
		}
		if len() >= limits.MaxEngineNodes {
			return fmt.Errorf("TALA %s descendant count exceeds limit %d", .Location(), limits.MaxEngineNodes)
		}
		[] = struct{}{}
		 = append(, {: })
		return nil
	}
	 := func( *layoutgraph.Node) error {
		if  := .Sequences[];  != nil {
			if len(.Nodes) > limits.MaxEngineNodes {
				return fmt.Errorf("TALA %s sequence child references exceed node limit %d", .Location(), limits.MaxEngineNodes)
			}
			for ,  := range slices.Backward(.Nodes) {
				if  := ();  != nil {
					return 
				}
			}
		}
		if  != nil && .IsClusterVessel() {
			if  := .Clusters[];  != nil {
				if len(.Nodes) > limits.MaxEngineNodes {
					return fmt.Errorf("TALA %s cluster child references exceed node limit %d", .Location(), limits.MaxEngineNodes)
				}
				for ,  := range slices.Backward(.Nodes) {
					if  := ();  != nil {
						return 
					}
				}
			}
		}
		if  == nil || .IsContainer() {
			 := .Containers[]
			if len() > limits.MaxEngineNodes {
				return fmt.Errorf("TALA %s container child references exceed node limit %d", .Location(), limits.MaxEngineNodes)
			}
			for ,  := range slices.Backward() {
				if  := ();  != nil {
					return 
				}
			}
		}
		return nil
	}
	if  := ();  != nil {
		return nil, 
	}
	 := make([]*layoutgraph.Node, 0, len())
	for len() > 0 {
		if  := .Step();  != nil {
			return nil, 
		}
		 := len() - 1
		 := [].
		 = [:]
		 = append(, )
		if  := ();  != nil {
			return nil, 
		}
	}
	return , nil
}

func optimizerMoveNodeAbs( *layoutgraph.Node, ,  float64,  *limits.OptimizationWorkGuard) error {
	if  == nil || .TopLeft == nil {
		return fmt.Errorf("TALA %s cannot move an unpositioned node", .Location())
	}
	if .TopLeft.X ==  && .TopLeft.Y ==  {
		return .Step()
	}
	// Most optimizer candidates are ordinary leaves. The general path below
	// walks ownership maps and snapshots descendants for atomic rollback, but
	// those structures are provably empty for a non-container/non-vessel leaf.
	// Moving the single positioned node cannot fail, so avoid allocating a seen
	// map and snapshot slice for every candidate.
	if .Graph != nil && !.IsContainer() && !.IsClusterVessel() && .Graph.Sequences[] == nil {
		.Translate(-.TopLeft.X, -.TopLeft.Y)
		return nil
	}
	,  := optimizerDescendants(, )
	if  != nil {
		return 
	}
	 := make([]nodePositionSnapshot, 0, len()+1)
	 = append(, nodePositionSnapshot{node: , topLeft: snapshotPointer(.TopLeft)})
	for ,  := range  {
		if  := .Step();  != nil {
			return 
		}
		if .TopLeft == nil {
			return fmt.Errorf("TALA %s cannot move an unpositioned descendant", .Location())
		}
		 = append(, nodePositionSnapshot{node: , topLeft: snapshotPointer(.TopLeft)})
	}
	 := false
	defer func() {
		if ! {
			restoreNodePositions()
		}
	}()
	,  := -.TopLeft.X, -.TopLeft.Y
	.Translate(, )
	for ,  := range  {
		if  := .Step();  != nil {
			return 
		}
		.Translate(, )
	}
	 = true
	return nil
}

func optimizerSwapPositions(,  *layoutgraph.Node,  *limits.OptimizationWorkGuard) ( error) {
	if  == nil ||  == nil || .TopLeft == nil || .TopLeft == nil {
		return fmt.Errorf("TALA %s cannot swap unpositioned nodes", .Location())
	}
	,  := captureOptimizerNodePositions([]*layoutgraph.Node{, }, )
	if  != nil {
		return 
	}
	 := false
	defer func() {
		if  := recover();  != nil {
			restoreNodePositions()
			panic()
		}
		if ! {
			restoreNodePositions()
		}
	}()
	,  := .TopLeft.X, .TopLeft.Y
	if  := optimizerMoveNodeAbs(, .TopLeft.X, .TopLeft.Y, );  != nil {
		return 
	}
	if  := optimizerMoveNodeAbs(, , , );  != nil {
		return 
	}
	 = true
	return nil
}

type optimizerNodeMutationSnapshot struct {
	node    *layoutgraph.Node
	topLeft pointerSnapshot[geo.Point]
	width   float64
	height  float64
}

type optimizerClusterMutationSnapshot struct {
	cluster     *layoutgraph.Cluster
	arrangement layoutgraph.ClusterArrangement
	desired     layoutgraph.ClusterArrangement
	padding     float64
}

type optimizerHerdMutationSnapshot struct {
	herd  *layoutgraph.HerdAssignment
	value layoutgraph.HerdAssignment
}

type optimizerMutationSnapshot struct {
	nodes        []optimizerNodeMutationSnapshot
	clusters     []optimizerClusterMutationSnapshot
	herds        []optimizerHerdMutationSnapshot
	costSnapshot *layoutgraph.PlacementCostSnapshot

	// Scratch is owned by one optimizer invocation at a time. Reusing storage
	// avoids rebuilding allocation capacity on every annealing iteration; the
	// topology and rollback values are still captured afresh on each call.
	seenNodes    map[*layoutgraph.Node]struct{}
	seenClusters map[*layoutgraph.Cluster]struct{}
	seenHerds    map[*layoutgraph.HerdAssignment]struct{}
}

func captureOptimizerMutationState( *layoutgraph.Graph,  *limits.OptimizationWorkGuard) (*optimizerMutationSnapshot, error) {
	return captureOptimizerMutationStateInto(, , new(optimizerMutationSnapshot))
}

// release clears graph references while retaining request-local buffer capacity.
// It is also safe after an interrupted capture, when only a prefix was recorded.
func ( *optimizerMutationSnapshot) () {
	clear(.nodes)
	clear(.clusters)
	clear(.herds)
	.nodes = .nodes[:0]
	.clusters = .clusters[:0]
	.herds = .herds[:0]
	.costSnapshot = nil
	clear(.seenNodes)
	clear(.seenClusters)
	clear(.seenHerds)
}

func captureOptimizerMutationStateInto( *layoutgraph.Graph,  *limits.OptimizationWorkGuard,  *optimizerMutationSnapshot) (*optimizerMutationSnapshot, error) {
	.release()
	if  == nil {
		return nil, fmt.Errorf("TALA %s requires a graph", .Location())
	}
	if len(.Nodes) > limits.MaxEngineNodes {
		return nil, fmt.Errorf("TALA %s snapshot node count exceeds limit %d", .Location(), limits.MaxEngineNodes)
	}
	if len(.Containers) > limits.MaxEngineNodes+1 || len(.Clusters) > limits.MaxEngineNodes || len(.Sequences) > limits.MaxEngineNodes {
		return nil, fmt.Errorf("TALA %s optimizer topology maps exceed node limit %d", .Location(), limits.MaxEngineNodes)
	}
	 := .EdgeLengthCacheEntries()
	if int64() > layoutgraph.MaxTopologyReferences {
		return nil, fmt.Errorf("TALA %s edge-length cache entries exceed limit %d", .Location(), layoutgraph.MaxTopologyReferences)
	}
	for range  {
		if  := .Step();  != nil {
			return nil, 
		}
	}
	 := .SnapshotPlacementCosts()
	if  := .Finish();  != nil {
		return nil, 
	}
	.costSnapshot = 
	if .seenNodes == nil {
		.seenNodes = make(map[*layoutgraph.Node]struct{}, len(.Nodes))
	}
	 := .seenNodes
	 := func( *layoutgraph.Node) error {
		if  := .Step();  != nil {
			return 
		}
		if  == nil {
			return fmt.Errorf("TALA %s found a nil graph node", .Location())
		}
		if ,  := [];  {
			return nil
		}
		if len() >= limits.MaxEngineNodes {
			return fmt.Errorf("TALA %s snapshot node count exceeds limit %d", .Location(), limits.MaxEngineNodes)
		}
		[] = struct{}{}
		.nodes = append(.nodes, optimizerNodeMutationSnapshot{
			node: , topLeft: snapshotPointer(.TopLeft), width: .Width, height: .Height,
		})
		return nil
	}
	for ,  := range .Nodes {
		if  := ();  != nil {
			return nil, 
		}
	}
	// The snapshot already contains the queue in discovery order.
	for  := 0;  < len(.nodes); ++ {
		 := .nodes[].node
		if len(.Containers[]) > limits.MaxEngineNodes {
			return nil, fmt.Errorf("TALA %s container child references exceed node limit %d", .Location(), limits.MaxEngineNodes)
		}
		for ,  := range .Containers[] {
			if  := ();  != nil {
				return nil, 
			}
		}
		if  := .Clusters[];  != nil {
			if len(.Nodes) > limits.MaxEngineNodes {
				return nil, fmt.Errorf("TALA %s cluster child references exceed node limit %d", .Location(), limits.MaxEngineNodes)
			}
			for ,  := range .Nodes {
				if  := ();  != nil {
					return nil, 
				}
			}
		}
		if  := .Sequences[];  != nil {
			if len(.Nodes) > limits.MaxEngineNodes {
				return nil, fmt.Errorf("TALA %s sequence child references exceed node limit %d", .Location(), limits.MaxEngineNodes)
			}
			for ,  := range .Nodes {
				if  := ();  != nil {
					return nil, 
				}
			}
		}
	}

	if .seenClusters == nil && len(.Clusters) != 0 {
		.seenClusters = make(map[*layoutgraph.Cluster]struct{})
	}
	 := .seenClusters
	for ,  := range .Clusters {
		if  := .Step();  != nil {
			return nil, 
		}
		if  == nil {
			continue
		}
		if ,  := [];  {
			continue
		}
		[] = struct{}{}
		.clusters = append(.clusters, optimizerClusterMutationSnapshot{
			cluster: , arrangement: .Arrangement, desired: .DesiredArrangement, padding: .Padding,
		})
	}

	 := .seenHerds
	for ,  := range .nodes {
		if  := .Step();  != nil {
			return nil, 
		}
		 := .node.HerdAssignment
		if  == nil {
			continue
		}
		if ,  := [];  {
			continue
		}
		if  == nil {
			 = make(map[*layoutgraph.HerdAssignment]struct{})
			.seenHerds = 
		}
		[] = struct{}{}
		.herds = append(.herds, optimizerHerdMutationSnapshot{herd: , value: *})
	}
	return , nil
}

func ( *optimizerMutationSnapshot) () {
	if  == nil {
		return
	}
	for ,  := range .nodes {
		.node.TopLeft = .topLeft.restore()
		.node.Width = .width
		.node.Height = .height
	}
	for ,  := range .clusters {
		.cluster.Arrangement = .arrangement
		.cluster.DesiredArrangement = .desired
		.cluster.Padding = .padding
	}
	for ,  := range .herds {
		*.herd = .value
	}
	.costSnapshot.Restore()
}

func captureOptimizerNodePositions( []*layoutgraph.Node,  *limits.OptimizationWorkGuard) ([]nodePositionSnapshot, error) {
	if len() <= 2 {
		 := true
		for ,  := range  {
			if  == nil {
				return nil, fmt.Errorf("TALA %s found a nil node", .Location())
			}
			if .Graph == nil || .IsContainer() || .IsClusterVessel() || .Graph.Sequences[] != nil {
				 = false
				break
			}
		}
		if  {
			 := make([]nodePositionSnapshot, 0, len())
			for ,  := range  {
				 := false
				for ,  := range  {
					if .node ==  {
						 = true
						break
					}
				}
				if  {
					continue
				}
				if  := .Step();  != nil {
					return nil, 
				}
				 = append(, nodePositionSnapshot{node: , topLeft: snapshotPointer(.TopLeft)})
			}
			return , nil
		}
	}
	if len() == 1 {
		// optimizerDescendants already deduplicates its traversal, including
		// the root. A single root needs no second map or combined node slice.
		,  := optimizerDescendants([0], )
		if  != nil {
			return nil, 
		}
		 := make([]nodePositionSnapshot, len()+1)
		for  := range  {
			if  := .Step();  != nil {
				return nil, 
			}
			 := [0]
			if  > 0 {
				 = [-1]
			}
			[] = nodePositionSnapshot{node: , topLeft: snapshotPointer(.TopLeft)}
		}
		return , nil
	}
	 := make(map[*layoutgraph.Node]struct{})
	 := make([]nodePositionSnapshot, 0, len())
	for ,  := range  {
		if  == nil {
			return nil, fmt.Errorf("TALA %s found a nil node", .Location())
		}
		 := []*layoutgraph.Node{}
		,  := optimizerDescendants(, )
		if  != nil {
			return nil, 
		}
		 = append(, ...)
		for ,  := range  {
			if ,  := [];  {
				continue
			}
			if len() >= limits.MaxEngineNodes {
				return nil, fmt.Errorf("TALA %s position snapshot exceeds node limit %d", .Location(), limits.MaxEngineNodes)
			}
			if  := .Step();  != nil {
				return nil, 
			}
			[] = struct{}{}
			 = append(, nodePositionSnapshot{node: , topLeft: snapshotPointer(.TopLeft)})
		}
	}
	return , nil
}

// withOptimizerPositionsSwapped owns the rollback point for a speculative swap
// and its scoring callback. The former nested atomic swap captured the same
// geometry twice without any intervening mutation. Reuse this rollback point,
// replaying the second capture's exact work and cancellation checkpoints.
func withOptimizerPositionsSwapped(,  *layoutgraph.Node,  *limits.OptimizationWorkGuard,  func() error) ( error) {
	 := .Used()
	,  := captureOptimizerNodePositions([]*layoutgraph.Node{, }, )
	if  != nil {
		return 
	}
	 := .Used() - 
	defer restoreNodePositions()
	if  == nil ||  == nil || .TopLeft == nil || .TopLeft == nil {
		return fmt.Errorf("TALA %s cannot swap unpositioned nodes", .Location())
	}
	for range  {
		if  := .Step();  != nil {
			return 
		}
	}
	,  := .TopLeft.X, .TopLeft.Y
	if  := optimizerMoveNodeAbs(, .TopLeft.X, .TopLeft.Y, );  != nil {
		return 
	}
	if  := optimizerMoveNodeAbs(, , , );  != nil {
		return 
	}
	return ()
}