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_delegation::MAX_DELIVERY_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    /// Stop a node whose start was refused before the host received a launch:
351    /// no child process exists, so its paths are free at once.
352    pub(crate) fn stop_unlaunched(
353        &mut self,
354        node_id: &str,
355        reason: StopReason,
356    ) -> Result<Vec<String>, WorkGraphError> {
357        let stopped = self.stop(node_id, reason)?;
358        if let Some(node) = self.nodes.get_mut(node_id) {
359            node.lease_expires_epoch_ms = None;
360        }
361        Ok(stopped)
362    }
363
364    /// Record token consumption on a node.
365    pub fn consume_budget(
366        &mut self,
367        node_id: &str,
368        tokens: u64,
369        cost_micros: u64,
370    ) -> Result<bool, WorkGraphError> {
371        let (next_node_tokens, next_node_cost, exhausted) = {
372            let node = self
373                .nodes
374                .get(node_id)
375                .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
376            if node.status != NodeStatus::Active {
377                return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
378            }
379            let next_tokens = node
380                .budget
381                .tokens_consumed
382                .checked_add(tokens)
383                .ok_or(WorkGraphError::Overflow)?;
384            let next_cost = node
385                .budget
386                .cost_micros_consumed
387                .checked_add(cost_micros)
388                .ok_or(WorkGraphError::Overflow)?;
389            if next_tokens > node.budget.tokens_allocated
390                || next_cost > node.budget.cost_micros_allocated
391            {
392                return Err(WorkGraphError::InvalidBudget);
393            }
394            let (reserved_tokens, reserved_cost) = self.reserved_child_budget(node_id, None)?;
395            if tokens
396                > node
397                    .budget
398                    .tokens_remaining()
399                    .saturating_sub(reserved_tokens)
400                || cost_micros > node.budget.cost_remaining().saturating_sub(reserved_cost)
401            {
402                return Err(WorkGraphError::InvalidBudget);
403            }
404            (
405                next_tokens,
406                next_cost,
407                next_tokens == node.budget.tokens_allocated
408                    || next_cost == node.budget.cost_micros_allocated,
409            )
410        };
411        let chain_id = self
412            .chain_id_for_node(node_id)
413            .expect("node always has a root node");
414        let (next_chain_tokens, next_chain_cost, chain_exhausted) = {
415            let chain = self
416                .chain_budgets
417                .get(&chain_id)
418                .ok_or_else(|| WorkGraphError::InvalidGraph("missing chain budget".into()))?;
419            let next_tokens = chain
420                .total_consumed_tokens
421                .checked_add(tokens)
422                .ok_or(WorkGraphError::Overflow)?;
423            let next_cost = chain
424                .total_consumed_cost_micros
425                .checked_add(cost_micros)
426                .ok_or(WorkGraphError::Overflow)?;
427            if next_tokens.saturating_add(chain.unauthorized_tokens) > chain.root_budget_tokens
428                || next_cost.saturating_add(chain.unauthorized_cost_micros)
429                    > chain.root_budget_cost_micros
430            {
431                return Err(WorkGraphError::InvalidBudget);
432            }
433            (
434                next_tokens,
435                next_cost,
436                next_tokens.saturating_add(chain.unauthorized_tokens) == chain.root_budget_tokens
437                    || next_cost.saturating_add(chain.unauthorized_cost_micros)
438                        == chain.root_budget_cost_micros,
439            )
440        };
441
442        // Commit only after all node, child-reservation and chain checks pass.
443        let node = self.nodes.get_mut(node_id).expect("node checked above");
444        node.budget.tokens_consumed = next_node_tokens;
445        node.budget.cost_micros_consumed = next_node_cost;
446        let chain = self
447            .chain_budgets
448            .get_mut(&chain_id)
449            .expect("chain checked above");
450        chain.total_consumed_tokens = next_chain_tokens;
451        chain.total_consumed_cost_micros = next_chain_cost;
452
453        if chain_exhausted {
454            self.stop_recursive(&chain_id, StopReason::BudgetExhausted, &mut Vec::new());
455            return Ok(true);
456        }
457        if exhausted {
458            let node = self.nodes.get_mut(node_id).expect("node checked above");
459            node.status = NodeStatus::Stopped;
460            node.stop_reason = Some(StopReason::BudgetExhausted);
461            self.end_incarnation(node_id);
462            return Ok(true);
463        }
464
465        Ok(false)
466    }
467
468    /// Records token consumption for a node and updates its chain budget.
469    pub fn consume_tokens(&mut self, node_id: &str, tokens: u64) -> Result<(), WorkGraphError> {
470        self.consume_budget(node_id, tokens, 0)?;
471        Ok(())
472    }
473
474    /// Returns the chain budget for a given node's chain.
475    pub fn chain_budget_for(&self, node_id: &str) -> Option<&ChainBudget> {
476        let chain_id = self.chain_id_for_node(node_id)?;
477        self.chain_budgets.get(&chain_id)
478    }
479
480    /// Returns all chains at or above their utilization threshold.
481    pub fn over_budget_chains(&self, threshold_pct: f64) -> Vec<&ChainBudget> {
482        self.chain_budgets
483            .values()
484            .filter(|budget| budget.utilization_pct() >= threshold_pct)
485            .collect()
486    }
487
488    /// Check all nodes for stop conditions and cascade.
489    pub fn enforce_stop_conditions(&mut self) -> Vec<(String, StopReason)> {
490        let exhausted: Vec<String> = self
491            .nodes
492            .iter()
493            .filter(|(_, n)| n.status == NodeStatus::Active && n.budget.is_exhausted())
494            .map(|(id, _)| id.clone())
495            .collect();
496        let mut stopped = Vec::new();
497        for node_id in exhausted {
498            let mut cascade = Vec::new();
499            self.stop_recursive(&node_id, StopReason::BudgetExhausted, &mut cascade);
500            for id in cascade {
501                stopped.push((id, StopReason::BudgetExhausted));
502            }
503        }
504        stopped
505    }
506
507    pub fn get_node(&self, node_id: &str) -> Option<&WorkNode> {
508        self.nodes.get(node_id)
509    }
510
511    /// Advance only the current running incarnation; retries revoke the prior
512    /// attempt's delivery authority without changing the node claim fence.
513    pub(crate) fn begin_delivery_attempt(
514        &mut self,
515        node_id: &str,
516        fence: &str,
517        attempt: u8,
518    ) -> Result<(), WorkGraphError> {
519        let node = self
520            .nodes
521            .get_mut(node_id)
522            .ok_or_else(|| WorkGraphError::InvalidTransition(node_id.into()))?;
523        if node.status != NodeStatus::Active
524            || !node.execution_started
525            || node.execution_fence.as_deref() != Some(fence)
526            || !(1..=crate::core::work_graph_delegation::MAX_DELIVERY_ATTEMPTS).contains(&attempt)
527            || node.delivery_attempt.unwrap_or(0).checked_add(1) != Some(attempt)
528        {
529            return Err(WorkGraphError::InvalidTransition(node_id.into()));
530        }
531        node.delivery_attempt = Some(attempt);
532        Ok(())
533    }
534
535    pub fn contains_agent(&self, agent_id: &str) -> bool {
536        self.nodes.values().any(|node| node.agent_id == agent_id)
537    }
538
539    pub fn children_of(&self, node_id: &str) -> &[String] {
540        self.children.get(node_id).map_or(&[], Vec::as_slice)
541    }
542
543    /// A started incarnation holds its paths while it runs and, once stopped,
544    /// until its window ends: LeanCTX cannot observe the host's child exit, so
545    /// a stopped child keeps write exclusivity for the time it was granted.
546    pub(crate) fn has_live_path_conflict(
547        &self,
548        requested: &[String],
549        now_epoch_ms: u64,
550        except_node_id: Option<&str>,
551    ) -> bool {
552        self.nodes.values().any(|node| {
553            Some(node.node_id.as_str()) != except_node_id
554                && (self.execution_exit_unconfirmed(node)
555                    || (node.execution_started
556                        && node.status == NodeStatus::Stopped
557                        && node
558                            .lease_expires_epoch_ms
559                            .is_some_and(|expires| now_epoch_ms < expires)))
560                && node.path_claims.iter().any(|held| {
561                    requested
562                        .iter()
563                        .any(|claim| path_claims_overlap(held, claim))
564                })
565        })
566    }
567
568    pub fn active_count(&self) -> usize {
569        self.nodes
570            .values()
571            .filter(|n| n.status == NodeStatus::Active)
572            .count()
573    }
574
575    /// A started incarnation is live exactly while its node is active: the host
576    /// owns the child process, and every terminal transition (receipt, complete,
577    /// stop, budget exhaustion) ends LeanCTX's authority over it. Stores written
578    /// by the removed launcher may hold terminal nodes it never acknowledged;
579    /// they are ended too.
580    pub(super) fn execution_exit_unconfirmed(&self, node: &WorkNode) -> bool {
581        node.execution_started && node.status == NodeStatus::Active
582    }
583
584    /// Record the end of a started incarnation; earlier releases read this map
585    /// to free the slot, so it is still written.
586    pub(super) fn end_incarnation(&mut self, node_id: &str) {
587        let Some(node) = self.nodes.get_mut(node_id) else {
588            return;
589        };
590        if !node.execution_started {
591            node.lease_expires_epoch_ms = None;
592        } else if let Some(fence) = &node.execution_fence {
593            self.reaped_executions
594                .insert(node_id.to_string(), fence.clone());
595        }
596    }
597
598    pub fn total_count(&self) -> usize {
599        self.nodes.len()
600    }
601
602    #[allow(clippy::collapsible_if)]
603    fn stop_recursive(&mut self, node_id: &str, reason: StopReason, stopped: &mut Vec<String>) {
604        if let Some(node) = self.nodes.get_mut(node_id) {
605            if matches!(node.status, NodeStatus::Active | NodeStatus::Pending) {
606                node.status = NodeStatus::Stopped;
607                node.stop_reason = Some(reason);
608                // A started node keeps its lease expiry: it bounds the path
609                // exclusivity of a child that may still be running.
610                self.end_incarnation(node_id);
611                stopped.push(node_id.to_string());
612            }
613        }
614        let children: Vec<String> = self.children.get(node_id).cloned().unwrap_or_default();
615        for child_id in children {
616            self.stop_recursive(&child_id, StopReason::ParentStopped, stopped);
617        }
618    }
619
620    pub(super) fn chain_id_for_node(&self, node_id: &str) -> Option<String> {
621        let mut current_id = node_id;
622        let mut current = self.nodes.get(current_id)?;
623        while let Some(parent_id) = current.parent_node_id.as_deref() {
624            current_id = parent_id;
625            current = self.nodes.get(current_id)?;
626        }
627        Some(current_id.to_string())
628    }
629
630    pub(super) fn node_lineage(&self, node_id: &str) -> Vec<String> {
631        let mut lineage = Vec::new();
632        let mut current_id = Some(node_id);
633        while let Some(id) = current_id {
634            let Some(node) = self.nodes.get(id) else {
635                break;
636            };
637            lineage.push(id.to_string());
638            current_id = node.parent_node_id.as_deref();
639        }
640        lineage.reverse();
641        lineage
642    }
643
644    pub(super) fn reserved_child_budget(
645        &self,
646        parent_id: &str,
647        exclude_child_id: Option<&str>,
648    ) -> Result<(u64, u64), WorkGraphError> {
649        let mut tokens = 0_u64;
650        let mut cost = 0_u64;
651        let mut pending_parents = vec![parent_id];
652        let mut visited = BTreeSet::from([parent_id]);
653        while let Some(current_parent) = pending_parents.pop() {
654            for child_id in self.children.get(current_parent).into_iter().flatten() {
655                if current_parent == parent_id && Some(child_id.as_str()) == exclude_child_id {
656                    continue;
657                }
658                if !visited.insert(child_id.as_str()) {
659                    return Err(WorkGraphError::InvalidGraph(
660                        "duplicate child or cycle".into(),
661                    ));
662                }
663                let child = self
664                    .nodes
665                    .get(child_id)
666                    .ok_or_else(|| WorkGraphError::InvalidGraph("dangling child".to_string()))?;
667                // A terminal status alone does not settle usage: complete() can run
668                // without a receipt, and cancellation can leave provider usage unknown.
669                let settled = matches!(child.status, NodeStatus::Completed | NodeStatus::Failed)
670                    // Only measured usage can free an allocation: unfenced legacy
671                    // receipts and figures the child or its host reported (every
672                    // receipt since LeanCTX stopped launching agents) keep the full
673                    // allocation reserved, so under-reporting cannot be re-delegated.
674                    && child.execution_fence.is_some()
675                    && self.receipts.values().any(|receipt| {
676                        receipt.node_id == *child_id
677                            && receipt.usage_source == super::UsageSource::Measured
678                            && receipt.tokens_consumed == child.budget.tokens_consumed
679                            && receipt.cost_micros_consumed == child.budget.cost_micros_consumed
680                            && receipt.execution_fence == child.execution_fence
681                    });
682                let (child_tokens, child_cost) = if settled {
683                    // Keep actual spend and all descendant commitments reserved; only
684                    // the settled node's unused allocation becomes available again.
685                    pending_parents.push(child_id.as_str());
686                    (
687                        child.budget.tokens_consumed,
688                        child.budget.cost_micros_consumed,
689                    )
690                } else {
691                    (
692                        child.budget.tokens_allocated,
693                        child.budget.cost_micros_allocated,
694                    )
695                };
696                tokens = tokens
697                    .checked_add(child_tokens)
698                    .ok_or(WorkGraphError::Overflow)?;
699                cost = cost
700                    .checked_add(child_cost)
701                    .ok_or(WorkGraphError::Overflow)?;
702            }
703            for (child_id, budget) in &self.pending_child_budgets {
704                if (current_parent == parent_id && Some(child_id.as_str()) == exclude_child_id)
705                    || self.pending_child_parents.get(child_id).map(String::as_str)
706                        != Some(current_parent)
707                {
708                    continue;
709                }
710                tokens = tokens
711                    .checked_add(budget.tokens_allocated)
712                    .ok_or(WorkGraphError::Overflow)?;
713                cost = cost
714                    .checked_add(budget.cost_micros_allocated)
715                    .ok_or(WorkGraphError::Overflow)?;
716            }
717        }
718        Ok((tokens, cost))
719    }
720
721    pub(super) fn ensure_chain_budget(&mut self, chain_id: &str) {
722        let root_budget = self
723            .nodes
724            .get(chain_id)
725            .map(|node| node.budget.clone())
726            .unwrap_or(WorkNodeBudget {
727                tokens_allocated: 0,
728                tokens_consumed: 0,
729                cost_micros_allocated: 0,
730                cost_micros_consumed: 0,
731            });
732        self.chain_budgets
733            .entry(chain_id.to_string())
734            .or_insert(ChainBudget {
735                chain_id: chain_id.to_string(),
736                root_budget_tokens: root_budget.tokens_allocated,
737                total_consumed_tokens: 0,
738                total_allocated_tokens: root_budget.tokens_allocated,
739                root_budget_cost_micros: root_budget.cost_micros_allocated,
740                total_consumed_cost_micros: 0,
741                total_allocated_cost_micros: root_budget.cost_micros_allocated,
742                unauthorized_tokens: 0,
743                unauthorized_cost_micros: 0,
744                depth: 0,
745            });
746    }
747
748    pub(super) fn record_chain_allocation(
749        &mut self,
750        chain_id: &str,
751        previous_tokens: u64,
752        tokens_allocated: u64,
753        previous_cost_micros: u64,
754        cost_micros_allocated: u64,
755        depth: u16,
756    ) {
757        self.ensure_chain_budget(chain_id);
758        let chain = self
759            .chain_budgets
760            .get_mut(chain_id)
761            .expect("chain budget initialized");
762        chain.total_allocated_tokens = chain
763            .total_allocated_tokens
764            .saturating_sub(previous_tokens)
765            .saturating_add(tokens_allocated);
766        chain.total_allocated_cost_micros = chain
767            .total_allocated_cost_micros
768            .saturating_sub(previous_cost_micros)
769            .saturating_add(cost_micros_allocated);
770        chain.depth = chain.depth.max(depth);
771    }
772}