1use super::{
4 BTreeMap, BTreeSet, BoundedWorkGraph, BudgetAllocation, ChainBudget, ChildExecutionReceipt,
5 ChildOutcome, FusedResults, MAX_DEPTH, MAX_FAN_OUT, MAX_GRAPH_NODES, MAX_LOCAL_CONCURRENCY,
6 MAX_PATH_CLAIMS, MeasuredExecutionSpend, NodeStatus, ResultConflict, StopReason,
7 TeamValueReport, WorkAttribution, WorkGraphError, WorkNode, WorkNodeBudget, cascade_budget,
8 execution_fence, validate_budget, validate_cascade, validate_identifier,
9 validate_measured_spend, validate_path_claim, validate_receipt,
10};
11
12impl BoundedWorkGraph {
13 #[must_use]
14 pub fn new(max_fan_out: usize, max_depth: u16) -> Self {
15 Self {
16 graph_id: String::new(),
17 nodes: BTreeMap::new(),
18 children: BTreeMap::new(),
19 chain_budgets: BTreeMap::new(),
20 pending_child_budgets: BTreeMap::new(),
21 pending_child_parents: BTreeMap::new(),
22 receipts: BTreeMap::new(),
23 failed_spend: BTreeMap::new(),
24 reaped_executions: BTreeMap::new(),
25 accepted_path: BTreeSet::new(),
26 max_local_concurrency: MAX_FAN_OUT,
27 max_fan_out: max_fan_out.clamp(1, MAX_FAN_OUT),
28 max_depth: max_depth.clamp(1, MAX_DEPTH),
29 }
30 }
31
32 #[must_use]
33 pub fn with_local_concurrency(mut self, max_local_concurrency: usize) -> Self {
34 self.max_local_concurrency = max_local_concurrency.clamp(1, MAX_LOCAL_CONCURRENCY);
35 self
36 }
37
38 pub fn with_graph_id(mut self, graph_id: &str) -> Result<Self, WorkGraphError> {
39 validate_identifier(graph_id, "graph_id")?;
40 self.graph_id = graph_id.to_string();
41 Ok(self)
42 }
43
44 pub fn bind_graph_id(&mut self, graph_id: &str) -> Result<(), WorkGraphError> {
45 validate_identifier(graph_id, "graph_id")?;
46 if !self.graph_id.is_empty() && self.graph_id != graph_id {
47 return Err(WorkGraphError::InvalidGraph("graph id mismatch".into()));
48 }
49 self.graph_id = graph_id.to_string();
50 Ok(())
51 }
52
53 pub fn graph_id(&self) -> &str {
54 &self.graph_id
55 }
56
57 pub fn observation(&self) -> serde_json::Value {
60 self.observe_if_changed(None)
61 }
62
63 pub fn observe_if_changed(&self, if_revision: Option<&str>) -> serde_json::Value {
66 let nodes: Vec<_> = self
67 .nodes
68 .values()
69 .map(|node| {
70 serde_json::json!({
71 "node_id": node.node_id,
72 "agent_id": node.agent_id,
73 "parent_node_id": node.parent_node_id,
74 "status": node.status,
75 "execution_started": node.execution_started,
76 "process_exit": if !node.execution_started { "not_started" }
77 else if self.execution_exit_unconfirmed(node) { "unconfirmed" }
78 else { "confirmed" },
79 "stop_reason": node.stop_reason,
80 "tokens_consumed": node.budget.tokens_consumed,
81 "tokens_remaining": node.budget.tokens_remaining(),
82 "cost_micros_consumed": node.budget.cost_micros_consumed,
83 "cost_micros_remaining": node.budget.cost_remaining(),
84 "accepted": self.accepted_path.contains(&node.node_id),
85 })
86 })
87 .collect();
88 let mut observation = serde_json::json!({
89 "schema_version": 1,
90 "graph_id": self.graph_id,
91 "max_concurrency": self.local_concurrency_limit(),
92 "nodes": nodes,
93 });
94 let revision = blake3::hash(observation.to_string().as_bytes())
95 .to_hex()
96 .to_string();
97 if if_revision == Some(revision.as_str()) {
98 return serde_json::json!({
99 "schema_version": 1,
100 "graph_id": self.graph_id,
101 "revision": revision,
102 "unchanged": true,
103 });
104 }
105 observation["revision"] = revision.into();
106 observation["unchanged"] = false.into();
107 observation
108 }
109
110 pub(super) fn local_concurrency_limit(&self) -> usize {
111 self.max_local_concurrency.clamp(1, MAX_LOCAL_CONCURRENCY)
112 }
113
114 pub fn add_root(
116 &mut self,
117 node_id: String,
118 agent_id: String,
119 capsule_ref: String,
120 budget: WorkNodeBudget,
121 ) -> Result<&WorkNode, WorkGraphError> {
122 if self.nodes.len() >= MAX_GRAPH_NODES {
123 return Err(WorkGraphError::CapacityExceeded);
124 }
125 validate_identifier(&node_id, "node_id")?;
126 validate_identifier(&agent_id, "agent_id")?;
127 validate_identifier(&capsule_ref, "capsule_ref")?;
128 validate_budget(&budget)?;
129 let concurrency_limit = self.local_concurrency_limit();
130 if self.active_count() >= concurrency_limit {
131 return Err(WorkGraphError::LocalConcurrencyExceeded(concurrency_limit));
132 }
133 if self.nodes.contains_key(&node_id) {
134 return Err(WorkGraphError::DuplicateNode(node_id));
135 }
136 let node = WorkNode {
137 node_id: node_id.clone(),
138 agent_id,
139 parent_node_id: None,
140 capsule_ref,
141 status: NodeStatus::Active,
142 budget,
143 depth: 0,
144 stop_reason: None,
145 outcome_ref: None,
146 claim_attempt: 0,
147 delivery_attempt: None,
148 execution_fence: None,
149 lease_expires_epoch_ms: None,
150 path_claims: Vec::new(),
151 task_ref: String::new(),
152 parent_task_ref: None,
153 policy_ref: String::new(),
154 expected_outcome_ref: String::new(),
155 execution_started: false,
156 };
157 self.nodes.insert(node_id.clone(), node);
158 self.chain_budgets.insert(
159 node_id.clone(),
160 ChainBudget {
161 chain_id: node_id.clone(),
162 root_budget_tokens: self.nodes[&node_id].budget.tokens_allocated,
163 total_consumed_tokens: 0,
164 total_allocated_tokens: self.nodes[&node_id].budget.tokens_allocated,
165 root_budget_cost_micros: self.nodes[&node_id].budget.cost_micros_allocated,
166 total_consumed_cost_micros: 0,
167 total_allocated_cost_micros: self.nodes[&node_id].budget.cost_micros_allocated,
168 unauthorized_tokens: 0,
169 unauthorized_cost_micros: 0,
170 depth: 0,
171 },
172 );
173 Ok(self.nodes.get(&node_id).expect("root node inserted above"))
174 }
175
176 pub fn delegate(
178 &mut self,
179 parent_node_id: &str,
180 child_node_id: String,
181 child_agent_id: String,
182 capsule_ref: String,
183 child_budget: WorkNodeBudget,
184 ) -> Result<&WorkNode, WorkGraphError> {
185 self.insert_child(
186 parent_node_id,
187 child_node_id,
188 child_agent_id,
189 capsule_ref,
190 child_budget,
191 NodeStatus::Active,
192 )
193 }
194
195 pub fn queue_child(
197 &mut self,
198 parent_node_id: &str,
199 child_node_id: String,
200 child_agent_id: String,
201 capsule_ref: String,
202 child_budget: WorkNodeBudget,
203 ) -> Result<&WorkNode, WorkGraphError> {
204 self.insert_child(
205 parent_node_id,
206 child_node_id,
207 child_agent_id,
208 capsule_ref,
209 child_budget,
210 NodeStatus::Pending,
211 )
212 }
213
214 pub fn claim_and_activate(&mut self, node_id: &str) -> Result<&WorkNode, WorkGraphError> {
216 self.claim_and_activate_until(node_id, None)
217 }
218
219 pub fn claim_and_activate_until(
220 &mut self,
221 node_id: &str,
222 lease_expires_epoch_ms: Option<u64>,
223 ) -> Result<&WorkNode, WorkGraphError> {
224 validate_identifier(node_id, "node_id")?;
225 let concurrency_limit = self.local_concurrency_limit();
226 if self.active_count() >= concurrency_limit {
227 return Err(WorkGraphError::LocalConcurrencyExceeded(concurrency_limit));
228 }
229 let parent_id = self
230 .nodes
231 .get(node_id)
232 .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?
233 .parent_node_id
234 .clone();
235 let Some(parent_id) = parent_id else {
236 return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
237 };
238 if self.nodes.get(&parent_id).map(|node| node.status) != Some(NodeStatus::Active) {
239 return Err(WorkGraphError::ParentNotActive(parent_id));
240 }
241 let graph_id = self.graph_id.clone();
242 let node = self.nodes.get_mut(node_id).expect("node checked above");
243 if node.status != NodeStatus::Pending {
244 return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
245 }
246 node.claim_attempt = node
247 .claim_attempt
248 .checked_add(1)
249 .ok_or(WorkGraphError::Overflow)?;
250 node.execution_fence = Some(execution_fence(&graph_id, node));
251 node.delivery_attempt = None;
252 node.lease_expires_epoch_ms = lease_expires_epoch_ms;
253 node.status = NodeStatus::Active;
254 Ok(node)
255 }
256
257 pub fn claim_or_resume_active_until(
259 &mut self,
260 node_id: &str,
261 lease_expires_epoch_ms: u64,
262 ) -> Result<&WorkNode, WorkGraphError> {
263 let capsule_ref = self
264 .nodes
265 .get(node_id)
266 .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?
267 .capsule_ref
268 .clone();
269 if self.nodes.iter().any(|(candidate_id, candidate)| {
270 candidate_id != node_id
271 && candidate.execution_started
272 && candidate.capsule_ref == capsule_ref
273 }) {
274 return Err(WorkGraphError::InvalidGraph(
275 "context capsule was already consumed by another node".into(),
276 ));
277 }
278 match self.nodes.get(node_id).map(|node| node.status) {
279 Some(NodeStatus::Pending) => {
280 self.claim_and_activate_until(node_id, Some(lease_expires_epoch_ms))?;
281 let node = self.nodes.get_mut(node_id).expect("node claimed above");
282 node.execution_started = true;
283 Ok(node)
284 }
285 Some(NodeStatus::Active) => {
286 let node = self.nodes.get_mut(node_id).expect("node checked above");
287 if node.parent_node_id.is_none()
288 || node.execution_fence.is_none()
289 || node.execution_started
290 {
291 return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
292 }
293 node.lease_expires_epoch_ms = Some(lease_expires_epoch_ms);
294 node.execution_started = true;
295 Ok(node)
296 }
297 Some(_) => Err(WorkGraphError::InvalidTransition(node_id.to_string())),
298 None => Err(WorkGraphError::NodeNotFound(node_id.to_string())),
299 }
300 }
301
302 pub fn recover_expired_execution(
303 &mut self,
304 node_id: &str,
305 now_epoch_ms: u64,
306 ) -> Result<Vec<String>, WorkGraphError> {
307 let node = self
308 .nodes
309 .get(node_id)
310 .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
311 let expired = node.parent_node_id.is_some()
312 && node.status == NodeStatus::Active
313 && node
314 .lease_expires_epoch_ms
315 .is_some_and(|expires| now_epoch_ms >= expires);
316 if expired {
317 return self.stop(node_id, StopReason::LeaseLost);
318 }
319 Ok(Vec::new())
320 }
321
322 pub fn set_path_claims(
324 &mut self,
325 node_id: &str,
326 mut path_claims: Vec<String>,
327 ) -> Result<(), WorkGraphError> {
328 if path_claims.len() > MAX_PATH_CLAIMS {
329 return Err(WorkGraphError::TooManyPathClaims);
330 }
331 path_claims.sort();
332 path_claims.dedup();
333 for claim in &path_claims {
334 validate_path_claim(claim)?;
335 }
336 let node = self
337 .nodes
338 .get_mut(node_id)
339 .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
340 if node.status != NodeStatus::Pending {
341 return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
342 }
343 node.path_claims = path_claims;
344 Ok(())
345 }
346
347 pub fn configure_root_context(
348 &mut self,
349 node_id: &str,
350 task_ref: &str,
351 policy_ref: &str,
352 expected_outcome_ref: &str,
353 ) -> Result<(), WorkGraphError> {
354 validate_identifier(task_ref, "task_ref")?;
355 validate_identifier(policy_ref, "policy_ref")?;
356 validate_identifier(expected_outcome_ref, "expected_outcome_ref")?;
357 let node = self
358 .nodes
359 .get_mut(node_id)
360 .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
361 if node.parent_node_id.is_some() {
362 return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
363 }
364 node.task_ref = task_ref.to_string();
365 node.parent_task_ref = None;
366 node.policy_ref = policy_ref.to_string();
367 node.expected_outcome_ref = expected_outcome_ref.to_string();
368 Ok(())
369 }
370
371 pub fn configure_child_context(
372 &mut self,
373 node_id: &str,
374 task_ref: &str,
375 expected_outcome_ref: &str,
376 ) -> Result<(), WorkGraphError> {
377 validate_identifier(task_ref, "task_ref")?;
378 validate_identifier(expected_outcome_ref, "expected_outcome_ref")?;
379 let parent_id = self
380 .nodes
381 .get(node_id)
382 .and_then(|node| node.parent_node_id.clone())
383 .ok_or_else(|| WorkGraphError::InvalidTransition(node_id.to_string()))?;
384 let parent = self
385 .nodes
386 .get(&parent_id)
387 .ok_or_else(|| WorkGraphError::NodeNotFound(parent_id.clone()))?;
388 if parent.task_ref.is_empty() || parent.policy_ref.is_empty() {
389 return Err(WorkGraphError::InvalidGraph(
390 "parent context is not configured".into(),
391 ));
392 }
393 let parent_task_ref = parent.task_ref.clone();
394 let policy_ref = parent.policy_ref.clone();
395 let node = self
396 .nodes
397 .get_mut(node_id)
398 .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
399 if node.status != NodeStatus::Pending {
400 return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
401 }
402 node.task_ref = task_ref.to_string();
403 node.parent_task_ref = Some(parent_task_ref);
404 node.policy_ref = policy_ref;
405 node.expected_outcome_ref = expected_outcome_ref.to_string();
406 Ok(())
407 }
408
409 fn insert_child(
410 &mut self,
411 parent_node_id: &str,
412 child_node_id: String,
413 child_agent_id: String,
414 capsule_ref: String,
415 child_budget: WorkNodeBudget,
416 status: NodeStatus,
417 ) -> Result<&WorkNode, WorkGraphError> {
418 if self.nodes.len() >= MAX_GRAPH_NODES {
419 return Err(WorkGraphError::CapacityExceeded);
420 }
421 validate_identifier(parent_node_id, "parent_node_id")?;
422 validate_identifier(&child_node_id, "child_node_id")?;
423 validate_identifier(&child_agent_id, "child_agent_id")?;
424 validate_identifier(&capsule_ref, "capsule_ref")?;
425 validate_budget(&child_budget)?;
426 if self.nodes.contains_key(&child_node_id) {
427 return Err(WorkGraphError::DuplicateNode(child_node_id));
428 }
429 let pending_budget = self.pending_child_budgets.get(&child_node_id);
430 let pending_parent = self.pending_child_parents.get(&child_node_id);
431 let pending_reservation_matches = match (pending_budget, pending_parent) {
432 (None, None) => true,
433 (Some(_), Some(parent)) => parent == parent_node_id,
434 _ => false,
435 };
436 if !pending_reservation_matches {
437 return Err(WorkGraphError::InvalidGraph(
438 "pending child reservation is incomplete or belongs to another parent".into(),
439 ));
440 }
441 let (reserved_tokens, reserved_cost) =
442 self.reserved_child_budget(parent_node_id, Some(&child_node_id))?;
443 let parent = self
444 .nodes
445 .get(parent_node_id)
446 .ok_or_else(|| WorkGraphError::NodeNotFound(parent_node_id.to_string()))?;
447 if parent.status != NodeStatus::Active {
448 return Err(WorkGraphError::ParentNotActive(parent_node_id.to_string()));
449 }
450 let new_depth = parent.depth + 1;
451 if new_depth > self.max_depth {
452 return Err(WorkGraphError::DepthExceeded(self.max_depth));
453 }
454 let available_tokens = parent
455 .budget
456 .tokens_remaining()
457 .saturating_sub(reserved_tokens);
458 let available_cost = parent.budget.cost_remaining().saturating_sub(reserved_cost);
459 if child_budget.tokens_allocated > available_tokens {
460 return Err(WorkGraphError::BudgetExceedsParent {
461 child_requested: child_budget.tokens_allocated,
462 parent_remaining: available_tokens,
463 });
464 }
465 if child_budget.cost_micros_allocated > available_cost {
466 return Err(WorkGraphError::BudgetExceedsParent {
467 child_requested: child_budget.cost_micros_allocated,
468 parent_remaining: available_cost,
469 });
470 }
471 let current_children = self.children.get(parent_node_id).map_or(0, Vec::len);
472 if current_children >= self.max_fan_out {
473 return Err(WorkGraphError::FanOutExceeded(self.max_fan_out));
474 }
475 let concurrency_limit = self.local_concurrency_limit();
476 if status == NodeStatus::Active && self.active_count() >= concurrency_limit {
477 return Err(WorkGraphError::LocalConcurrencyExceeded(concurrency_limit));
478 }
479 let child_tokens_allocated = child_budget.tokens_allocated;
480 let child_cost_allocated = child_budget.cost_micros_allocated;
481 let node = WorkNode {
482 node_id: child_node_id.clone(),
483 agent_id: child_agent_id,
484 parent_node_id: Some(parent_node_id.to_string()),
485 capsule_ref,
486 status,
487 budget: child_budget,
488 depth: new_depth,
489 stop_reason: None,
490 outcome_ref: None,
491 claim_attempt: 0,
492 delivery_attempt: None,
493 execution_fence: None,
494 lease_expires_epoch_ms: None,
495 path_claims: Vec::new(),
496 task_ref: String::new(),
497 parent_task_ref: None,
498 policy_ref: String::new(),
499 expected_outcome_ref: String::new(),
500 execution_started: false,
501 };
502 self.nodes.insert(child_node_id.clone(), node);
503 self.children
504 .entry(parent_node_id.to_string())
505 .or_default()
506 .push(child_node_id.clone());
507 let chain_id = self
508 .chain_id_for_node(&child_node_id)
509 .expect("delegated child always has a root node");
510 let pending_budget =
511 self.pending_child_budgets
512 .remove(&child_node_id)
513 .unwrap_or(WorkNodeBudget {
514 tokens_allocated: 0,
515 tokens_consumed: 0,
516 cost_micros_allocated: 0,
517 cost_micros_consumed: 0,
518 });
519 self.pending_child_parents.remove(&child_node_id);
520 self.record_chain_allocation(
521 &chain_id,
522 pending_budget.tokens_allocated,
523 child_tokens_allocated,
524 pending_budget.cost_micros_allocated,
525 child_cost_allocated,
526 new_depth,
527 );
528 Ok(self
529 .nodes
530 .get(&child_node_id)
531 .expect("child node inserted above"))
532 }
533
534 pub fn allocate_child_budget(
539 &mut self,
540 parent_id: &str,
541 child_id: &str,
542 fraction: f64,
543 ) -> Result<WorkNodeBudget, WorkGraphError> {
544 validate_identifier(parent_id, "parent_node_id")?;
545 validate_identifier(child_id, "child_node_id")?;
546 if self.nodes.contains_key(child_id) || self.pending_child_budgets.contains_key(child_id) {
547 return Err(WorkGraphError::DuplicateNode(child_id.to_string()));
548 }
549 let (parent_budget_tokens, parent_used_tokens, parent_cost_remaining, parent_depth) = {
550 let parent = self
551 .nodes
552 .get(parent_id)
553 .ok_or_else(|| WorkGraphError::NodeNotFound(parent_id.to_string()))?;
554 if parent.status != NodeStatus::Active {
555 return Err(WorkGraphError::ParentNotActive(parent_id.to_string()));
556 }
557 if parent.depth >= self.max_depth {
558 return Err(WorkGraphError::DepthExceeded(self.max_depth));
559 }
560 (
561 parent.budget.tokens_allocated,
562 parent.budget.tokens_consumed,
563 parent.budget.cost_remaining(),
564 parent.depth,
565 )
566 };
567
568 let (reserved_tokens, reserved_cost) =
569 self.reserved_child_budget(parent_id, Some(child_id))?;
570 let parent_remaining = parent_budget_tokens
571 .saturating_sub(parent_used_tokens)
572 .saturating_sub(reserved_tokens);
573 if parent_remaining == 0 {
574 return Err(WorkGraphError::BudgetExceedsParent {
575 child_requested: 1,
576 parent_remaining,
577 });
578 }
579
580 let allocation = BudgetAllocation {
581 parent_budget_tokens,
582 parent_used_tokens,
583 child_fraction: fraction,
584 minimum_budget: 0,
585 maximum_budget: parent_remaining,
586 };
587 let mut cascaded = cascade_budget(&allocation);
588 cascaded.depth = u32::from(parent_depth) + 1;
589 cascaded.lineage = self.node_lineage(parent_id);
590 cascaded.lineage.push(child_id.to_string());
591 validate_cascade(&cascaded)?;
592 if cascaded.allocated_tokens > parent_remaining {
593 return Err(WorkGraphError::BudgetExceedsParent {
594 child_requested: cascaded.allocated_tokens,
595 parent_remaining,
596 });
597 }
598
599 let parent_cost_remaining = parent_cost_remaining.saturating_sub(reserved_cost);
600 let cost_micros_allocated = if parent_cost_remaining == 0 {
601 0
602 } else {
603 ((parent_cost_remaining as f64 * fraction) as u64)
604 .max(1)
605 .min(parent_cost_remaining)
606 };
607 let child_budget = WorkNodeBudget {
608 tokens_allocated: cascaded.allocated_tokens,
609 tokens_consumed: 0,
610 cost_micros_allocated,
611 cost_micros_consumed: 0,
612 };
613 let chain_id = self
614 .chain_id_for_node(parent_id)
615 .expect("parent node always has a root node");
616 self.pending_child_budgets
617 .insert(child_id.to_string(), child_budget.clone());
618 self.pending_child_parents
619 .insert(child_id.to_string(), parent_id.to_string());
620 self.record_chain_allocation(
621 &chain_id,
622 0,
623 child_budget.tokens_allocated,
624 0,
625 child_budget.cost_micros_allocated,
626 parent_depth + 1,
627 );
628
629 Ok(child_budget)
630 }
631
632 pub fn complete(&mut self, node_id: &str, outcome_ref: String) -> Result<(), WorkGraphError> {
634 validate_identifier(&outcome_ref, "outcome_ref")?;
635 let node = self
636 .nodes
637 .get_mut(node_id)
638 .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
639 if node.status != NodeStatus::Active {
640 return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
641 }
642 node.status = NodeStatus::Completed;
643 node.outcome_ref = Some(outcome_ref);
644 node.lease_expires_epoch_ms = None;
645 Ok(())
646 }
647
648 pub fn record_child_receipt(
650 &mut self,
651 receipt: ChildExecutionReceipt,
652 ) -> Result<(), WorkGraphError> {
653 validate_receipt(&receipt)?;
654 if self.receipts.contains_key(&receipt.receipt_id)
655 || self
656 .receipts
657 .values()
658 .any(|known| known.node_id == receipt.node_id)
659 {
660 return Err(WorkGraphError::DuplicateReceipt(receipt.receipt_id));
661 }
662 let node = self
663 .nodes
664 .get(&receipt.node_id)
665 .ok_or_else(|| WorkGraphError::NodeNotFound(receipt.node_id.clone()))?;
666 if node.parent_node_id.is_none() || node.status != NodeStatus::Active {
667 return Err(WorkGraphError::InvalidTransition(receipt.node_id));
668 }
669 if node.execution_fence.is_some() && receipt.execution_fence != node.execution_fence {
670 return Err(WorkGraphError::StaleExecutionFence(receipt.node_id));
671 }
672 if receipt.tokens_consumed > node.budget.tokens_allocated
673 || receipt.cost_micros_consumed > node.budget.cost_micros_allocated
674 || receipt.tokens_consumed < node.budget.tokens_consumed
675 || receipt.cost_micros_consumed < node.budget.cost_micros_consumed
676 {
677 return Err(WorkGraphError::ReceiptExceedsBudget(receipt.node_id));
678 }
679 let token_delta = receipt.tokens_consumed - node.budget.tokens_consumed;
680 let cost_delta = receipt.cost_micros_consumed - node.budget.cost_micros_consumed;
681 let (reserved_tokens, reserved_cost) =
682 self.reserved_child_budget(&receipt.node_id, None)?;
683 if token_delta
684 > node
685 .budget
686 .tokens_remaining()
687 .saturating_sub(reserved_tokens)
688 || cost_delta > node.budget.cost_remaining().saturating_sub(reserved_cost)
689 {
690 return Err(WorkGraphError::ReceiptExceedsBudget(receipt.node_id));
691 }
692
693 let node_id = receipt.node_id.clone();
694 let receipt_id = receipt.receipt_id.clone();
695 let chain_id = self
696 .chain_id_for_node(&node_id)
697 .expect("receipt node always has a root");
698 self.ensure_chain_budget(&chain_id);
699 let chain = self
700 .chain_budgets
701 .get(&chain_id)
702 .expect("chain budget initialized");
703 let chain_consumed = chain
704 .total_consumed_tokens
705 .checked_add(token_delta)
706 .ok_or(WorkGraphError::Overflow)?;
707 let chain_cost = chain
708 .total_consumed_cost_micros
709 .checked_add(cost_delta)
710 .ok_or(WorkGraphError::Overflow)?;
711 if chain_consumed.saturating_add(chain.unauthorized_tokens) > chain.root_budget_tokens
712 || chain_cost.saturating_add(chain.unauthorized_cost_micros)
713 > chain.root_budget_cost_micros
714 {
715 return Err(WorkGraphError::ReceiptExceedsBudget(node_id));
716 }
717 let node = self
718 .nodes
719 .get_mut(&node_id)
720 .expect("receipt node checked above");
721 node.budget.tokens_consumed = receipt.tokens_consumed;
722 node.budget.cost_micros_consumed = receipt.cost_micros_consumed;
723 node.status = match receipt.outcome {
724 ChildOutcome::Accepted | ChildOutcome::Partial => NodeStatus::Completed,
725 ChildOutcome::Rejected => NodeStatus::Failed,
726 };
727 node.outcome_ref = Some(receipt.outcome_ref.clone());
728 node.lease_expires_epoch_ms = None;
729 self.chain_budgets
730 .get_mut(&chain_id)
731 .expect("chain budget initialized")
732 .total_consumed_tokens = chain_consumed;
733 self.chain_budgets
734 .get_mut(&chain_id)
735 .expect("chain budget initialized")
736 .total_consumed_cost_micros = chain_cost;
737 self.receipts.insert(receipt_id, receipt);
738 Ok(())
739 }
740
741 pub fn record_failed_execution_spend(
747 &mut self,
748 spend: MeasuredExecutionSpend,
749 ) -> Result<(), WorkGraphError> {
750 validate_measured_spend(&spend)?;
751 if self.failed_spend.get(&spend.node_id) == Some(&spend) {
752 return Ok(());
753 }
754 if self.failed_spend.contains_key(&spend.node_id)
755 || self
756 .receipts
757 .values()
758 .any(|receipt| receipt.node_id == spend.node_id)
759 {
760 return Err(WorkGraphError::DuplicateReceipt(spend.spend_id));
761 }
762 let node = self
763 .nodes
764 .get(&spend.node_id)
765 .ok_or_else(|| WorkGraphError::NodeNotFound(spend.node_id.clone()))?;
766 if node.parent_node_id.is_none() || node.status != NodeStatus::Active {
767 return Err(WorkGraphError::InvalidTransition(spend.node_id));
768 }
769 if node.execution_fence.as_deref() != Some(spend.execution_fence.as_str()) {
770 return Err(WorkGraphError::StaleExecutionFence(spend.node_id));
771 }
772 if spend.tokens_consumed <= node.budget.tokens_allocated
773 && spend.cost_micros_consumed <= node.budget.cost_micros_allocated
774 {
775 return Err(WorkGraphError::InvalidBudget);
776 }
777
778 let node_id = spend.node_id.clone();
779 let chain_id = self
780 .chain_id_for_node(&node_id)
781 .expect("failed spend node always has a root");
782 let unauthorized_tokens = spend
783 .tokens_consumed
784 .saturating_sub(node.budget.tokens_allocated);
785 let unauthorized_cost = spend
786 .cost_micros_consumed
787 .saturating_sub(node.budget.cost_micros_allocated);
788 self.stop(&node_id, StopReason::BudgetExhausted)?;
789 let chain = self
790 .chain_budgets
791 .get_mut(&chain_id)
792 .expect("failed spend chain budget initialized");
793 chain.unauthorized_tokens = chain
794 .unauthorized_tokens
795 .saturating_add(unauthorized_tokens);
796 chain.unauthorized_cost_micros = chain
797 .unauthorized_cost_micros
798 .saturating_add(unauthorized_cost);
799 self.failed_spend.insert(node_id, spend);
800 Ok(())
801 }
802
803 pub fn evaluate_child_outcome(&self, node_id: &str) -> Result<ChildOutcome, WorkGraphError> {
805 validate_identifier(node_id, "node_id")?;
806 self.receipts
807 .values()
808 .find(|receipt| receipt.node_id == node_id)
809 .map(|receipt| receipt.outcome)
810 .ok_or_else(|| WorkGraphError::MissingReceipt(node_id.to_string()))
811 }
812
813 pub fn mark_accepted_path(&mut self, node_ids: &[String]) -> Result<(), WorkGraphError> {
817 let mut accepted = BTreeSet::new();
818 for node_id in node_ids {
819 validate_identifier(node_id, "node_id")?;
820 let receipt = self
821 .receipts
822 .values()
823 .find(|receipt| receipt.node_id == *node_id)
824 .ok_or_else(|| WorkGraphError::MissingReceipt(node_id.clone()))?;
825 if receipt.outcome != ChildOutcome::Accepted {
826 return Err(WorkGraphError::RejectedAcceptedPath(node_id.clone()));
827 }
828 accepted.extend(self.node_lineage(node_id));
829 }
830 self.accepted_path = accepted;
831 Ok(())
832 }
833
834 pub fn is_on_accepted_path(&self, node_id: &str) -> bool {
835 self.accepted_path.contains(node_id)
836 }
837
838 pub fn fuse_accepted_results(&self) -> Result<FusedResults, WorkGraphError> {
841 let mut candidates: BTreeMap<String, BTreeMap<String, Vec<String>>> = BTreeMap::new();
842 for receipt in self.receipts.values() {
843 if !self.accepted_path.contains(&receipt.node_id) {
844 continue;
845 }
846 for claim in &receipt.claims {
847 candidates
848 .entry(claim.key.clone())
849 .or_default()
850 .entry(claim.value.clone())
851 .or_default()
852 .push(receipt.node_id.clone());
853 }
854 }
855 let mut accepted = BTreeMap::new();
856 let mut conflicts = Vec::new();
857 for (key, values) in candidates {
858 if values.len() == 1 {
859 let (value, _) = values.into_iter().next().expect("one value");
860 accepted.insert(key, value);
861 } else {
862 let mut node_ids: Vec<String> = values.values().flatten().cloned().collect();
863 node_ids.sort();
864 node_ids.dedup();
865 conflicts.push(ResultConflict {
866 key,
867 values: values.into_keys().collect(),
868 node_ids,
869 });
870 }
871 }
872 Ok(FusedResults {
873 accepted,
874 conflicts,
875 })
876 }
877
878 pub fn attribution(&self) -> Result<WorkAttribution, WorkGraphError> {
879 let mut result = WorkAttribution {
880 accepted_tokens: 0,
881 accepted_cost_micros: 0,
882 waste_tokens: 0,
883 waste_cost_micros: 0,
884 };
885 for node in self.nodes.values() {
886 let (tokens, cost) = self.failed_spend.get(&node.node_id).map_or(
887 (
888 node.budget.tokens_consumed,
889 node.budget.cost_micros_consumed,
890 ),
891 |spend| (spend.tokens_consumed, spend.cost_micros_consumed),
892 );
893 let (token_total, cost_total) = if self.accepted_path.contains(&node.node_id) {
894 (
895 &mut result.accepted_tokens,
896 &mut result.accepted_cost_micros,
897 )
898 } else {
899 (&mut result.waste_tokens, &mut result.waste_cost_micros)
900 };
901 *token_total = token_total
902 .checked_add(tokens)
903 .ok_or(WorkGraphError::Overflow)?;
904 *cost_total = cost_total
905 .checked_add(cost)
906 .ok_or(WorkGraphError::Overflow)?;
907 }
908 Ok(result)
909 }
910
911 pub fn team_value_report(&self) -> Result<TeamValueReport, WorkGraphError> {
912 let attribution = self.attribution()?;
913 let total_tokens = attribution
914 .accepted_tokens
915 .checked_add(attribution.waste_tokens)
916 .ok_or(WorkGraphError::Overflow)?;
917 let total_cost_micros = attribution
918 .accepted_cost_micros
919 .checked_add(attribution.waste_cost_micros)
920 .ok_or(WorkGraphError::Overflow)?;
921 let accepted_cost_basis_points = if total_cost_micros == 0 {
922 0
923 } else {
924 u16::try_from(
925 u128::from(attribution.accepted_cost_micros).saturating_mul(10_000)
926 / u128::from(total_cost_micros),
927 )
928 .unwrap_or(10_000)
929 };
930 Ok(TeamValueReport {
931 accepted_tokens: attribution.accepted_tokens,
932 total_tokens,
933 accepted_cost_micros: attribution.accepted_cost_micros,
934 total_cost_micros,
935 waste_tokens: attribution.waste_tokens,
936 waste_cost_micros: attribution.waste_cost_micros,
937 accepted_cost_basis_points,
938 })
939 }
940}