Skip to main content

lean_ctx/core/work_graph/
control_ops.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use super::path_claims_overlap;
4use super::{
5    BTreeSet, BoundedWorkGraph, ChainBudget, ChildOutcome, MAX_DEPTH, MAX_FAN_OUT, MAX_GRAPH_NODES,
6    MAX_LOCAL_CONCURRENCY, MAX_PATH_CLAIMS, NodeStatus, StopReason, WorkGraphError, WorkNode,
7    WorkNodeBudget, execution_fence, validate_budget, validate_identifier, validate_measured_spend,
8    validate_path_claim, validate_receipt,
9};
10
11impl BoundedWorkGraph {
12    /// Validate every persisted structural and accounting invariant before use.
13    pub fn validate_invariants(&self) -> Result<(), WorkGraphError> {
14        for (node_id, fence) in &self.reaped_executions {
15            if !self.nodes.get(node_id).is_some_and(|node| {
16                node.execution_started && node.execution_fence.as_ref() == Some(fence)
17            }) {
18                return Err(WorkGraphError::InvalidGraph(
19                    "invalid execution exit acknowledgement".into(),
20                ));
21            }
22        }
23        if !self.graph_id.is_empty() {
24            validate_identifier(&self.graph_id, "graph_id")?;
25        }
26        if self.nodes.len() > MAX_GRAPH_NODES
27            || self.max_fan_out == 0
28            || self.max_fan_out > MAX_FAN_OUT
29            || self.max_depth == 0
30            || self.max_depth > MAX_DEPTH
31            || self.max_local_concurrency == 0
32            || self.max_local_concurrency > MAX_LOCAL_CONCURRENCY
33            || self.active_count() > self.local_concurrency_limit()
34        {
35            return Err(WorkGraphError::InvalidGraph(
36                "configured limit exceeded".to_string(),
37            ));
38        }
39        for (node_id, node) in &self.nodes {
40            validate_identifier(node_id, "node_id")?;
41            validate_identifier(&node.node_id, "node_id")?;
42            validate_identifier(&node.agent_id, "agent_id")?;
43            validate_identifier(&node.capsule_ref, "capsule_ref")?;
44            validate_budget(&node.budget)?;
45            for (field, value) in [
46                ("task_ref", node.task_ref.as_str()),
47                ("policy_ref", node.policy_ref.as_str()),
48                ("expected_outcome_ref", node.expected_outcome_ref.as_str()),
49            ] {
50                if !value.is_empty() {
51                    validate_identifier(value, field)?;
52                }
53            }
54            if let Some(parent_task_ref) = node.parent_task_ref.as_deref() {
55                validate_identifier(parent_task_ref, "parent_task_ref")?;
56            }
57            if let Some(parent_id) = node.parent_node_id.as_deref()
58                && !node.task_ref.is_empty()
59            {
60                let parent = self
61                    .nodes
62                    .get(parent_id)
63                    .ok_or_else(|| WorkGraphError::InvalidGraph("missing context parent".into()))?;
64                if node.parent_task_ref.as_deref() != Some(parent.task_ref.as_str())
65                    || node.policy_ref != parent.policy_ref
66                {
67                    return Err(WorkGraphError::InvalidGraph(
68                        "task lineage or policy inheritance mismatch".into(),
69                    ));
70                }
71            }
72            if node.path_claims.len() > MAX_PATH_CLAIMS {
73                return Err(WorkGraphError::TooManyPathClaims);
74            }
75            let mut path_claims = BTreeSet::new();
76            for claim in &node.path_claims {
77                validate_path_claim(claim)?;
78                if !path_claims.insert(claim) {
79                    return Err(WorkGraphError::InvalidGraph(
80                        "duplicate path claim".to_string(),
81                    ));
82                }
83            }
84            if node_id != &node.node_id {
85                return Err(WorkGraphError::InvalidGraph(
86                    "node key mismatch".to_string(),
87                ));
88            }
89            if let Some(fence) = node.execution_fence.as_deref()
90                && fence != execution_fence(&self.graph_id, node)
91            {
92                return Err(WorkGraphError::InvalidGraph(
93                    "invalid execution fence".to_string(),
94                ));
95            }
96            if node.delivery_attempt.is_some_and(|attempt| {
97                !(1..=crate::core::work_graph_executor::MAX_ATTEMPTS).contains(&attempt)
98            }) || (node.delivery_attempt.is_some()
99                && (!node.execution_started || node.execution_fence.is_none()))
100            {
101                return Err(WorkGraphError::InvalidGraph(
102                    "invalid delivery attempt".into(),
103                ));
104            }
105            let lineage = self.checked_lineage(node_id)?;
106            if usize::from(node.depth) + 1 != lineage.len() || node.depth > self.max_depth {
107                return Err(WorkGraphError::InvalidGraph(
108                    "invalid node depth".to_string(),
109                ));
110            }
111            if let Some(parent_id) = node.parent_node_id.as_deref()
112                && !self
113                    .children
114                    .get(parent_id)
115                    .is_some_and(|children| children.contains(node_id))
116            {
117                return Err(WorkGraphError::InvalidGraph(
118                    "parent/child mismatch".to_string(),
119                ));
120            }
121            if node.parent_node_id.is_none() && !self.chain_budgets.contains_key(node_id) {
122                return Err(WorkGraphError::InvalidGraph(
123                    "missing chain budget".to_string(),
124                ));
125            }
126        }
127        for (parent_id, children) in &self.children {
128            if !self.nodes.contains_key(parent_id)
129                || children.len() > self.max_fan_out
130                || children.iter().collect::<BTreeSet<_>>().len() != children.len()
131            {
132                return Err(WorkGraphError::InvalidGraph(
133                    "invalid child index".to_string(),
134                ));
135            }
136            for child_id in children {
137                if self
138                    .nodes
139                    .get(child_id)
140                    .and_then(|node| node.parent_node_id.as_deref())
141                    != Some(parent_id)
142                {
143                    return Err(WorkGraphError::InvalidGraph("dangling child".to_string()));
144                }
145            }
146            let (tokens, cost) = self.reserved_child_budget(parent_id, None)?;
147            let parent = &self.nodes[parent_id];
148            if tokens > parent.budget.tokens_remaining() || cost > parent.budget.cost_remaining() {
149                return Err(WorkGraphError::InvalidGraph(
150                    "child budget over-allocation".to_string(),
151                ));
152            }
153        }
154        for (child_id, budget) in &self.pending_child_budgets {
155            validate_identifier(child_id, "pending_child_id")?;
156            validate_budget(budget)?;
157            if self.nodes.contains_key(child_id)
158                || !self.pending_child_parents.contains_key(child_id)
159            {
160                return Err(WorkGraphError::InvalidGraph(
161                    "invalid pending budget".to_string(),
162                ));
163            }
164        }
165        for receipt in self.receipts.values() {
166            validate_receipt(receipt)?;
167            let node = self
168                .nodes
169                .get(&receipt.node_id)
170                .ok_or_else(|| WorkGraphError::InvalidGraph("orphan receipt".to_string()))?;
171            if node.parent_node_id.is_none()
172                || node.budget.tokens_consumed != receipt.tokens_consumed
173                || node.budget.cost_micros_consumed != receipt.cost_micros_consumed
174                || (node.execution_fence.is_some()
175                    && receipt.execution_fence != node.execution_fence)
176            {
177                return Err(WorkGraphError::InvalidGraph(
178                    "receipt/node mismatch".to_string(),
179                ));
180            }
181        }
182        for (node_id, spend) in &self.failed_spend {
183            validate_measured_spend(spend)?;
184            let node = self
185                .nodes
186                .get(node_id)
187                .ok_or_else(|| WorkGraphError::InvalidGraph("orphan failed spend".into()))?;
188            if node_id != &spend.node_id
189                || node.parent_node_id.is_none()
190                || node.status != NodeStatus::Stopped
191                || node.stop_reason != Some(StopReason::BudgetExhausted)
192                || node.execution_fence.as_deref() != Some(spend.execution_fence.as_str())
193                || (spend.tokens_consumed <= node.budget.tokens_allocated
194                    && spend.cost_micros_consumed <= node.budget.cost_micros_allocated)
195                || self
196                    .receipts
197                    .values()
198                    .any(|receipt| receipt.node_id == *node_id)
199                || self.accepted_path.contains(node_id)
200            {
201                return Err(WorkGraphError::InvalidGraph(
202                    "failed spend/node mismatch".into(),
203                ));
204            }
205        }
206        for node_id in &self.accepted_path {
207            if !self.nodes.contains_key(node_id) {
208                return Err(WorkGraphError::InvalidGraph(
209                    "orphan accepted path".to_string(),
210                ));
211            }
212        }
213        let mut supported_path = BTreeSet::new();
214        for receipt in self.receipts.values() {
215            if receipt.outcome == ChildOutcome::Accepted
216                && self.accepted_path.contains(&receipt.node_id)
217            {
218                supported_path.extend(self.checked_lineage(&receipt.node_id)?);
219            }
220        }
221        if supported_path != self.accepted_path {
222            return Err(WorkGraphError::InvalidGraph(
223                "accepted path lacks accepted receipt lineage".to_string(),
224            ));
225        }
226        for (chain_id, chain) in &self.chain_budgets {
227            let root = self
228                .nodes
229                .get(chain_id)
230                .filter(|node| node.parent_node_id.is_none())
231                .ok_or_else(|| WorkGraphError::InvalidGraph("invalid chain root".to_string()))?;
232            let mut allocated_tokens = 0_u64;
233            let mut allocated_cost = 0_u64;
234            let mut consumed_tokens = 0_u64;
235            let mut consumed_cost = 0_u64;
236            let mut unauthorized_tokens = 0_u64;
237            let mut unauthorized_cost = 0_u64;
238            let mut depth = 0_u16;
239            for node in self.nodes.values() {
240                if self.checked_lineage(&node.node_id)?.first() != Some(chain_id) {
241                    continue;
242                }
243                allocated_tokens = allocated_tokens
244                    .checked_add(node.budget.tokens_allocated)
245                    .ok_or(WorkGraphError::Overflow)?;
246                allocated_cost = allocated_cost
247                    .checked_add(node.budget.cost_micros_allocated)
248                    .ok_or(WorkGraphError::Overflow)?;
249                consumed_tokens = consumed_tokens
250                    .checked_add(node.budget.tokens_consumed)
251                    .ok_or(WorkGraphError::Overflow)?;
252                consumed_cost = consumed_cost
253                    .checked_add(node.budget.cost_micros_consumed)
254                    .ok_or(WorkGraphError::Overflow)?;
255                depth = depth.max(node.depth);
256                if let Some(spend) = self.failed_spend.get(&node.node_id) {
257                    unauthorized_tokens = unauthorized_tokens.saturating_add(
258                        spend
259                            .tokens_consumed
260                            .saturating_sub(node.budget.tokens_allocated),
261                    );
262                    unauthorized_cost = unauthorized_cost.saturating_add(
263                        spend
264                            .cost_micros_consumed
265                            .saturating_sub(node.budget.cost_micros_allocated),
266                    );
267                }
268            }
269            for (child_id, budget) in &self.pending_child_budgets {
270                let Some(parent_id) = self.pending_child_parents.get(child_id) else {
271                    continue;
272                };
273                if self.checked_lineage(parent_id)?.first() == Some(chain_id) {
274                    let pending_depth = self.nodes[parent_id]
275                        .depth
276                        .checked_add(1)
277                        .ok_or(WorkGraphError::Overflow)?;
278                    depth = depth.max(pending_depth);
279                    allocated_tokens = allocated_tokens
280                        .checked_add(budget.tokens_allocated)
281                        .ok_or(WorkGraphError::Overflow)?;
282                    allocated_cost = allocated_cost
283                        .checked_add(budget.cost_micros_allocated)
284                        .ok_or(WorkGraphError::Overflow)?;
285                }
286            }
287            if chain.chain_id != *chain_id
288                || chain.root_budget_tokens != root.budget.tokens_allocated
289                || chain.root_budget_cost_micros != root.budget.cost_micros_allocated
290                || chain.total_allocated_tokens != allocated_tokens
291                || chain.total_allocated_cost_micros != allocated_cost
292                || chain.total_consumed_tokens != consumed_tokens
293                || chain.total_consumed_cost_micros != consumed_cost
294                || chain.unauthorized_tokens != unauthorized_tokens
295                || chain.unauthorized_cost_micros != unauthorized_cost
296                || chain.depth != depth
297                || consumed_tokens > chain.root_budget_tokens
298                || consumed_cost > chain.root_budget_cost_micros
299            {
300                return Err(WorkGraphError::InvalidGraph(
301                    "chain accounting mismatch".to_string(),
302                ));
303            }
304        }
305        Ok(())
306    }
307
308    pub fn root_agent_for(&self, node_id: &str) -> Result<&str, WorkGraphError> {
309        let root_id = self
310            .checked_lineage(node_id)?
311            .into_iter()
312            .next()
313            .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
314        Ok(self.nodes[&root_id].agent_id.as_str())
315    }
316
317    fn checked_lineage(&self, node_id: &str) -> Result<Vec<String>, WorkGraphError> {
318        let mut lineage = Vec::new();
319        let mut seen = BTreeSet::new();
320        let mut current_id = Some(node_id);
321        while let Some(id) = current_id {
322            if !seen.insert(id.to_string()) {
323                return Err(WorkGraphError::InvalidGraph("cycle detected".to_string()));
324            }
325            let node = self
326                .nodes
327                .get(id)
328                .ok_or_else(|| WorkGraphError::NodeNotFound(id.to_string()))?;
329            lineage.push(id.to_string());
330            current_id = node.parent_node_id.as_deref();
331        }
332        lineage.reverse();
333        Ok(lineage)
334    }
335
336    /// Stop a node and all its descendants (cascade).
337    pub fn stop(
338        &mut self,
339        node_id: &str,
340        reason: StopReason,
341    ) -> Result<Vec<String>, WorkGraphError> {
342        if !self.nodes.contains_key(node_id) {
343            return Err(WorkGraphError::NodeNotFound(node_id.to_string()));
344        }
345        let mut stopped = Vec::new();
346        self.stop_recursive(node_id, reason, &mut stopped);
347        Ok(stopped)
348    }
349
350    /// Record token consumption on a node.
351    pub fn consume_budget(
352        &mut self,
353        node_id: &str,
354        tokens: u64,
355        cost_micros: u64,
356    ) -> Result<bool, WorkGraphError> {
357        let (next_node_tokens, next_node_cost, exhausted) = {
358            let node = self
359                .nodes
360                .get(node_id)
361                .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
362            if node.status != NodeStatus::Active {
363                return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
364            }
365            let next_tokens = node
366                .budget
367                .tokens_consumed
368                .checked_add(tokens)
369                .ok_or(WorkGraphError::Overflow)?;
370            let next_cost = node
371                .budget
372                .cost_micros_consumed
373                .checked_add(cost_micros)
374                .ok_or(WorkGraphError::Overflow)?;
375            if next_tokens > node.budget.tokens_allocated
376                || next_cost > node.budget.cost_micros_allocated
377            {
378                return Err(WorkGraphError::InvalidBudget);
379            }
380            let (reserved_tokens, reserved_cost) = self.reserved_child_budget(node_id, None)?;
381            if tokens
382                > node
383                    .budget
384                    .tokens_remaining()
385                    .saturating_sub(reserved_tokens)
386                || cost_micros > node.budget.cost_remaining().saturating_sub(reserved_cost)
387            {
388                return Err(WorkGraphError::InvalidBudget);
389            }
390            (
391                next_tokens,
392                next_cost,
393                next_tokens == node.budget.tokens_allocated
394                    || next_cost == node.budget.cost_micros_allocated,
395            )
396        };
397        let chain_id = self
398            .chain_id_for_node(node_id)
399            .expect("node always has a root node");
400        let (next_chain_tokens, next_chain_cost, chain_exhausted) = {
401            let chain = self
402                .chain_budgets
403                .get(&chain_id)
404                .ok_or_else(|| WorkGraphError::InvalidGraph("missing chain budget".into()))?;
405            let next_tokens = chain
406                .total_consumed_tokens
407                .checked_add(tokens)
408                .ok_or(WorkGraphError::Overflow)?;
409            let next_cost = chain
410                .total_consumed_cost_micros
411                .checked_add(cost_micros)
412                .ok_or(WorkGraphError::Overflow)?;
413            if next_tokens.saturating_add(chain.unauthorized_tokens) > chain.root_budget_tokens
414                || next_cost.saturating_add(chain.unauthorized_cost_micros)
415                    > chain.root_budget_cost_micros
416            {
417                return Err(WorkGraphError::InvalidBudget);
418            }
419            (
420                next_tokens,
421                next_cost,
422                next_tokens.saturating_add(chain.unauthorized_tokens) == chain.root_budget_tokens
423                    || next_cost.saturating_add(chain.unauthorized_cost_micros)
424                        == chain.root_budget_cost_micros,
425            )
426        };
427
428        // Commit only after all node, child-reservation and chain checks pass.
429        let node = self.nodes.get_mut(node_id).expect("node checked above");
430        node.budget.tokens_consumed = next_node_tokens;
431        node.budget.cost_micros_consumed = next_node_cost;
432        let chain = self
433            .chain_budgets
434            .get_mut(&chain_id)
435            .expect("chain checked above");
436        chain.total_consumed_tokens = next_chain_tokens;
437        chain.total_consumed_cost_micros = next_chain_cost;
438
439        if chain_exhausted {
440            self.stop_recursive(&chain_id, StopReason::BudgetExhausted, &mut Vec::new());
441            return Ok(true);
442        }
443        if exhausted {
444            let node = self.nodes.get_mut(node_id).expect("node checked above");
445            node.status = NodeStatus::Stopped;
446            node.stop_reason = Some(StopReason::BudgetExhausted);
447            node.lease_expires_epoch_ms = None;
448            return Ok(true);
449        }
450
451        Ok(false)
452    }
453
454    /// Records token consumption for a node and updates its chain budget.
455    pub fn consume_tokens(&mut self, node_id: &str, tokens: u64) -> Result<(), WorkGraphError> {
456        self.consume_budget(node_id, tokens, 0)?;
457        Ok(())
458    }
459
460    /// Returns the chain budget for a given node's chain.
461    pub fn chain_budget_for(&self, node_id: &str) -> Option<&ChainBudget> {
462        let chain_id = self.chain_id_for_node(node_id)?;
463        self.chain_budgets.get(&chain_id)
464    }
465
466    /// Returns all chains at or above their utilization threshold.
467    pub fn over_budget_chains(&self, threshold_pct: f64) -> Vec<&ChainBudget> {
468        self.chain_budgets
469            .values()
470            .filter(|budget| budget.utilization_pct() >= threshold_pct)
471            .collect()
472    }
473
474    /// Check all nodes for stop conditions and cascade.
475    pub fn enforce_stop_conditions(&mut self) -> Vec<(String, StopReason)> {
476        let exhausted: Vec<String> = self
477            .nodes
478            .iter()
479            .filter(|(_, n)| n.status == NodeStatus::Active && n.budget.is_exhausted())
480            .map(|(id, _)| id.clone())
481            .collect();
482        let mut stopped = Vec::new();
483        for node_id in exhausted {
484            let mut cascade = Vec::new();
485            self.stop_recursive(&node_id, StopReason::BudgetExhausted, &mut cascade);
486            for id in cascade {
487                stopped.push((id, StopReason::BudgetExhausted));
488            }
489        }
490        stopped
491    }
492
493    pub fn get_node(&self, node_id: &str) -> Option<&WorkNode> {
494        self.nodes.get(node_id)
495    }
496
497    /// Advance only the current running incarnation; retries revoke the prior
498    /// attempt's delivery authority without changing the node claim fence.
499    pub(crate) fn begin_delivery_attempt(
500        &mut self,
501        node_id: &str,
502        fence: &str,
503        attempt: u8,
504    ) -> Result<(), WorkGraphError> {
505        let node = self
506            .nodes
507            .get_mut(node_id)
508            .ok_or_else(|| WorkGraphError::InvalidTransition(node_id.into()))?;
509        if node.status != NodeStatus::Active
510            || !node.execution_started
511            || node.execution_fence.as_deref() != Some(fence)
512            || !(1..=crate::core::work_graph_executor::MAX_ATTEMPTS).contains(&attempt)
513            || node.delivery_attempt.unwrap_or(0).checked_add(1) != Some(attempt)
514        {
515            return Err(WorkGraphError::InvalidTransition(node_id.into()));
516        }
517        node.delivery_attempt = Some(attempt);
518        Ok(())
519    }
520
521    pub fn contains_agent(&self, agent_id: &str) -> bool {
522        self.nodes.values().any(|node| node.agent_id == agent_id)
523    }
524
525    pub fn children_of(&self, node_id: &str) -> &[String] {
526        self.children.get(node_id).map_or(&[], Vec::as_slice)
527    }
528
529    pub(crate) fn has_live_path_conflict(
530        &self,
531        requested: &[String],
532        _now_epoch_ms: u64,
533        except_node_id: Option<&str>,
534    ) -> bool {
535        self.nodes.values().any(|node| {
536            Some(node.node_id.as_str()) != except_node_id
537                && self.execution_exit_unconfirmed(node)
538                && node.path_claims.iter().any(|held| {
539                    requested
540                        .iter()
541                        .any(|claim| path_claims_overlap(held, claim))
542                })
543        })
544    }
545
546    pub fn active_count(&self) -> usize {
547        self.nodes
548            .values()
549            .filter(|n| n.status == NodeStatus::Active || self.execution_exit_unconfirmed(n))
550            .count()
551    }
552
553    pub(super) fn execution_exit_unconfirmed(&self, node: &WorkNode) -> bool {
554        node.execution_started
555            && (node.execution_fence.is_none()
556                || self.reaped_executions.get(&node.node_id) != node.execution_fence.as_ref())
557    }
558
559    /// Only the owning executor's verified capture path may acknowledge exit.
560    pub(crate) fn acknowledge_execution_exit(
561        &mut self,
562        node_id: &str,
563        fence: &str,
564    ) -> Result<(), WorkGraphError> {
565        let node = self
566            .nodes
567            .get(node_id)
568            .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.into()))?;
569        if !node.execution_started || node.execution_fence.as_deref() != Some(fence) {
570            return Err(WorkGraphError::InvalidTransition(node_id.into()));
571        }
572        self.reaped_executions.insert(node_id.into(), fence.into());
573        Ok(())
574    }
575
576    pub fn total_count(&self) -> usize {
577        self.nodes.len()
578    }
579
580    #[allow(clippy::collapsible_if)]
581    fn stop_recursive(&mut self, node_id: &str, reason: StopReason, stopped: &mut Vec<String>) {
582        if let Some(node) = self.nodes.get_mut(node_id) {
583            if matches!(node.status, NodeStatus::Active | NodeStatus::Pending) {
584                node.status = NodeStatus::Stopped;
585                node.stop_reason = Some(reason);
586                node.lease_expires_epoch_ms = None;
587                stopped.push(node_id.to_string());
588            }
589        }
590        let children: Vec<String> = self.children.get(node_id).cloned().unwrap_or_default();
591        for child_id in children {
592            self.stop_recursive(&child_id, StopReason::ParentStopped, stopped);
593        }
594    }
595
596    pub(super) fn chain_id_for_node(&self, node_id: &str) -> Option<String> {
597        let mut current_id = node_id;
598        let mut current = self.nodes.get(current_id)?;
599        while let Some(parent_id) = current.parent_node_id.as_deref() {
600            current_id = parent_id;
601            current = self.nodes.get(current_id)?;
602        }
603        Some(current_id.to_string())
604    }
605
606    pub(super) fn node_lineage(&self, node_id: &str) -> Vec<String> {
607        let mut lineage = Vec::new();
608        let mut current_id = Some(node_id);
609        while let Some(id) = current_id {
610            let Some(node) = self.nodes.get(id) else {
611                break;
612            };
613            lineage.push(id.to_string());
614            current_id = node.parent_node_id.as_deref();
615        }
616        lineage.reverse();
617        lineage
618    }
619
620    pub(super) fn reserved_child_budget(
621        &self,
622        parent_id: &str,
623        exclude_child_id: Option<&str>,
624    ) -> Result<(u64, u64), WorkGraphError> {
625        let mut tokens = 0_u64;
626        let mut cost = 0_u64;
627        let mut pending_parents = vec![parent_id];
628        let mut visited = BTreeSet::from([parent_id]);
629        while let Some(current_parent) = pending_parents.pop() {
630            for child_id in self.children.get(current_parent).into_iter().flatten() {
631                if current_parent == parent_id && Some(child_id.as_str()) == exclude_child_id {
632                    continue;
633                }
634                if !visited.insert(child_id.as_str()) {
635                    return Err(WorkGraphError::InvalidGraph(
636                        "duplicate child or cycle".into(),
637                    ));
638                }
639                let child = self
640                    .nodes
641                    .get(child_id)
642                    .ok_or_else(|| WorkGraphError::InvalidGraph("dangling child".to_string()))?;
643                // A terminal status alone does not settle usage: complete() can run
644                // without a receipt, and cancellation can leave provider usage unknown.
645                let settled = matches!(child.status, NodeStatus::Completed | NodeStatus::Failed)
646                    // Unfenced legacy receipts bypass canonical usage verification
647                    // at the registered tool boundary and cannot authorize reuse.
648                    && child.execution_fence.is_some()
649                    && self.receipts.values().any(|receipt| {
650                        receipt.node_id == *child_id
651                            && receipt.tokens_consumed == child.budget.tokens_consumed
652                            && receipt.cost_micros_consumed == child.budget.cost_micros_consumed
653                            && receipt.execution_fence == child.execution_fence
654                    });
655                let (child_tokens, child_cost) = if settled {
656                    // Keep actual spend and all descendant commitments reserved; only
657                    // the settled node's unused allocation becomes available again.
658                    pending_parents.push(child_id.as_str());
659                    (
660                        child.budget.tokens_consumed,
661                        child.budget.cost_micros_consumed,
662                    )
663                } else {
664                    (
665                        child.budget.tokens_allocated,
666                        child.budget.cost_micros_allocated,
667                    )
668                };
669                tokens = tokens
670                    .checked_add(child_tokens)
671                    .ok_or(WorkGraphError::Overflow)?;
672                cost = cost
673                    .checked_add(child_cost)
674                    .ok_or(WorkGraphError::Overflow)?;
675            }
676            for (child_id, budget) in &self.pending_child_budgets {
677                if (current_parent == parent_id && Some(child_id.as_str()) == exclude_child_id)
678                    || self.pending_child_parents.get(child_id).map(String::as_str)
679                        != Some(current_parent)
680                {
681                    continue;
682                }
683                tokens = tokens
684                    .checked_add(budget.tokens_allocated)
685                    .ok_or(WorkGraphError::Overflow)?;
686                cost = cost
687                    .checked_add(budget.cost_micros_allocated)
688                    .ok_or(WorkGraphError::Overflow)?;
689            }
690        }
691        Ok((tokens, cost))
692    }
693
694    pub(super) fn ensure_chain_budget(&mut self, chain_id: &str) {
695        let root_budget = self
696            .nodes
697            .get(chain_id)
698            .map(|node| node.budget.clone())
699            .unwrap_or(WorkNodeBudget {
700                tokens_allocated: 0,
701                tokens_consumed: 0,
702                cost_micros_allocated: 0,
703                cost_micros_consumed: 0,
704            });
705        self.chain_budgets
706            .entry(chain_id.to_string())
707            .or_insert(ChainBudget {
708                chain_id: chain_id.to_string(),
709                root_budget_tokens: root_budget.tokens_allocated,
710                total_consumed_tokens: 0,
711                total_allocated_tokens: root_budget.tokens_allocated,
712                root_budget_cost_micros: root_budget.cost_micros_allocated,
713                total_consumed_cost_micros: 0,
714                total_allocated_cost_micros: root_budget.cost_micros_allocated,
715                unauthorized_tokens: 0,
716                unauthorized_cost_micros: 0,
717                depth: 0,
718            });
719    }
720
721    pub(super) fn record_chain_allocation(
722        &mut self,
723        chain_id: &str,
724        previous_tokens: u64,
725        tokens_allocated: u64,
726        previous_cost_micros: u64,
727        cost_micros_allocated: u64,
728        depth: u16,
729    ) {
730        self.ensure_chain_budget(chain_id);
731        let chain = self
732            .chain_budgets
733            .get_mut(chain_id)
734            .expect("chain budget initialized");
735        chain.total_allocated_tokens = chain
736            .total_allocated_tokens
737            .saturating_sub(previous_tokens)
738            .saturating_add(tokens_allocated);
739        chain.total_allocated_cost_micros = chain
740            .total_allocated_cost_micros
741            .saturating_sub(previous_cost_micros)
742            .saturating_add(cost_micros_allocated);
743        chain.depth = chain.depth.max(depth);
744    }
745}