Skip to main content

stateknot_core/
child_run_budget.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Checked accounting state transitions; not a database ledger or spawn API.
5
6use std::collections::BTreeSet;
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, de};
10use thiserror::Error;
11
12use crate::{
13    AgentAdmission, AgentResultProvenance, BudgetNarrowingError, BudgetRemaining, BudgetUsage,
14    BudgetUsageError, ChildRunAdmissionIntent, ChildRunKey, ChildRunPolicyError, CompiledGraph,
15    CumulativeBudgetReservation, CumulativeBudgetReservationError, Digest, ExecutionCount,
16    GraphReference, JournalHead, ResolvedBudget, RunLifecycle, RunStatus, Timestamp,
17};
18
19const DOMAIN: &[u8] = b"stateknot.child-run-budget-account.v1\0";
20
21/// Exact, fully priced terminal contribution of one immediate child subtree.
22///
23/// Construction binds trusted admission, lifecycle and terminal journal metadata.
24/// The adapter must independently verify their durable provenance, complete
25/// accounting (including grandchildren exactly once), and all child joins.
26/// A checksum is not proof that any external work finished or was paid for.
27#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
28#[serde(deny_unknown_fields)]
29pub struct ChildRunBudgetSettlement {
30    child: AgentResultProvenance,
31    intent_digest: Digest,
32    admission_digest: Digest,
33    admitted_at: Timestamp,
34    terminal: JournalHead,
35    #[schemars(schema_with = "terminal_status_schema")]
36    status: RunStatus,
37    outcome_digest: Digest,
38    #[schemars(schema_with = "priced_usage_schema")]
39    usage: BudgetUsage,
40}
41
42fn terminal_status_schema(_: &mut SchemaGenerator) -> Schema {
43    json_schema!({"type":"string","enum":["succeeded","failed","cancelled"]})
44}
45
46fn priced_usage_schema(generator: &mut SchemaGenerator) -> Schema {
47    json_schema!({"allOf":[generator.subschema_for::<BudgetUsage>(),
48        {"properties":{"unpriced_cost_events":{"const":"0"}}}]})
49}
50
51impl ChildRunBudgetSettlement {
52    /// Prepares a settlement from independently verified terminal evidence.
53    ///
54    /// Failed and cancelled children still consume their complete known usage.
55    /// Deadline expiry and a known budget overrun do not erase actual charges.
56    /// Unpriced usage cannot settle a reservation as if its cost were zero.
57    pub fn new(
58        admission: &AgentAdmission,
59        lifecycle: &RunLifecycle,
60        terminal: JournalHead,
61    ) -> Result<Self, ChildRunBudgetError> {
62        if lifecycle.provenance() != admission.intent().provenance()
63            || lifecycle.admitted_at() != admission.admitted_at()
64            || lifecycle.changed_at() > terminal.recorded_at()
65        {
66            return Err(ChildRunBudgetError::TerminalMismatch);
67        }
68        let usage = lifecycle
69            .terminal_usage()
70            .ok_or(ChildRunBudgetError::NotTerminal)?;
71        let mut preimage = b"stateknot.child-run-budget-terminal.v1\0".to_vec();
72        preimage.extend(
73            crate::agent_admission::canonical_bytes(lifecycle)
74                .map_err(|_| ChildRunBudgetError::Encoding)?,
75        );
76        let outcome_digest = Digest::sha256(preimage);
77        let value = Self {
78            child: admission.intent().provenance().clone(),
79            intent_digest: admission.intent().intent_digest(),
80            admission_digest: admission.digest(),
81            admitted_at: admission.admitted_at(),
82            terminal,
83            status: lifecycle.status(),
84            outcome_digest,
85            usage: usage.clone(),
86        };
87        value.validate()?;
88        Ok(value)
89    }
90
91    fn validate(&self) -> Result<(), ChildRunBudgetError> {
92        if !self.status.is_terminal() {
93            return Err(ChildRunBudgetError::NotTerminal);
94        }
95        if self.child.tenant_id() != self.terminal.tenant_id()
96            || self.child.run_id() != self.terminal.run_id()
97            || self.terminal.recorded_at() < self.admitted_at
98            || self.terminal.sequence().get() <= 1
99        {
100            return Err(ChildRunBudgetError::TerminalMismatch);
101        }
102        if self.usage.unpriced_cost_events() != ExecutionCount::ZERO {
103            return Err(ChildRunBudgetError::UnpricedSettlement);
104        }
105        Ok(())
106    }
107
108    /// Returns the independently bound terminal journal observation.
109    #[must_use]
110    pub const fn terminal(&self) -> &JournalHead {
111        &self.terminal
112    }
113
114    /// Returns complete child subtree usage, before removing child-local peaks.
115    #[must_use]
116    pub const fn usage(&self) -> &BudgetUsage {
117        &self.usage
118    }
119
120    /// Returns the checksum of the complete terminal lifecycle snapshot.
121    #[must_use]
122    pub const fn outcome_digest(&self) -> Digest {
123        self.outcome_digest
124    }
125
126    /// Returns the exact child admission commit fingerprint.
127    #[must_use]
128    pub const fn admission_digest(&self) -> Digest {
129        self.admission_digest
130    }
131}
132
133impl<'de> Deserialize<'de> for ChildRunBudgetSettlement {
134    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
135        #[derive(Deserialize)]
136        #[serde(deny_unknown_fields)]
137        struct Wire {
138            child: AgentResultProvenance,
139            intent_digest: Digest,
140            admission_digest: Digest,
141            admitted_at: Timestamp,
142            terminal: JournalHead,
143            status: RunStatus,
144            outcome_digest: Digest,
145            usage: BudgetUsage,
146        }
147        let wire = Wire::deserialize(deserializer)?;
148        let value = Self {
149            child: wire.child,
150            intent_digest: wire.intent_digest,
151            admission_digest: wire.admission_digest,
152            admitted_at: wire.admitted_at,
153            terminal: wire.terminal,
154            status: wire.status,
155            outcome_digest: wire.outcome_digest,
156            usage: wire.usage,
157        };
158        value.validate().map_err(de::Error::custom)?;
159        Ok(value)
160    }
161}
162
163/// A lifetime child slot record. Settled entries are retained for retry identity.
164#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
165#[serde(deny_unknown_fields)]
166pub struct ChildRunBudgetEntry {
167    key: ChildRunKey,
168    spawn_digest: Digest,
169    child: AgentResultProvenance,
170    intent_digest: Digest,
171    reservation: CumulativeBudgetReservation,
172    settlement: Option<ChildRunBudgetSettlement>,
173}
174
175impl ChildRunBudgetEntry {
176    fn validate(&self) -> Result<(), ChildRunBudgetError> {
177        if self.key.tenant_id() != self.child.tenant_id()
178            || self.key.parent_run_id() == self.child.run_id()
179        {
180            return Err(ChildRunBudgetError::ParentMismatch);
181        }
182        if let Some(settlement) = &self.settlement {
183            settlement.validate()?;
184            if settlement.child != self.child || settlement.intent_digest != self.intent_digest {
185                return Err(ChildRunBudgetError::TerminalMismatch);
186            }
187        }
188        Ok(())
189    }
190    /// Returns logical ownership, independent of physical attempts and fences.
191    #[must_use]
192    pub const fn key(&self) -> &ChildRunKey {
193        &self.key
194    }
195
196    /// Returns the first accepted child identities, including on an exact retry.
197    #[must_use]
198    pub const fn child(&self) -> &AgentResultProvenance {
199        &self.child
200    }
201
202    /// Returns the complete immutable spawn fingerprint used for retry comparison.
203    #[must_use]
204    pub const fn spawn_digest(&self) -> Digest {
205        self.spawn_digest
206    }
207
208    /// Returns the first-selected child admission-intent fingerprint.
209    #[must_use]
210    pub const fn intent_digest(&self) -> Digest {
211        self.intent_digest
212    }
213
214    /// Returns the original finite reservation, retained after settlement.
215    #[must_use]
216    pub const fn reservation(&self) -> &CumulativeBudgetReservation {
217        &self.reservation
218    }
219
220    /// Returns terminal accounting only after one exact settlement.
221    #[must_use]
222    pub const fn settlement(&self) -> Option<&ChildRunBudgetSettlement> {
223        self.settlement.as_ref()
224    }
225}
226
227impl<'de> Deserialize<'de> for ChildRunBudgetEntry {
228    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
229        #[derive(Deserialize)]
230        #[serde(deny_unknown_fields)]
231        struct Wire {
232            key: ChildRunKey,
233            spawn_digest: Digest,
234            child: AgentResultProvenance,
235            intent_digest: Digest,
236            reservation: CumulativeBudgetReservation,
237            settlement: Option<ChildRunBudgetSettlement>,
238        }
239        let wire = Wire::deserialize(deserializer)?;
240        let value = Self {
241            key: wire.key,
242            spawn_digest: wire.spawn_digest,
243            child: wire.child,
244            intent_digest: wire.intent_digest,
245            reservation: wire.reservation,
246            settlement: wire.settlement,
247        };
248        value.validate().map_err(de::Error::custom)?;
249        Ok(value)
250    }
251}
252
253/// Bounded, integrity-bound accounting state for one parent admission.
254///
255/// Separates parent direct observations, settled immediate-child subtree charges,
256/// and outstanding ceilings. Mutations return a new snapshot; failures preserve
257/// the old value. Retained keys make spawn/settlement retries idempotent even
258/// after closure or deadline expiry. No child record can be removed or refunded.
259///
260/// This is a pure contract, NOT a durable account, lock, authority grant, child
261/// ownership record or scheduler. A storage adapter must verify all evidence and
262/// persist the old-to-new digest transition atomically with parent direct work,
263/// child ownership/admission/settlement and lifecycle guards. In particular,
264/// storing two independently computed snapshots without compare-and-swap loses
265/// reservations. Existing root admission is not an implementation of this API.
266///
267/// ```
268/// use stateknot_core::{AgentAdmission, BudgetUsage, ChildRunAdmissionIntent,
269///     ChildRunBudgetAccount, ChildRunBudgetError, CompiledGraph, JournalHead, Timestamp};
270///
271/// fn prepare_account_transition(
272///     parent: &AgentAdmission,
273///     graph: &CompiledGraph,
274///     direct_head: JournalHead,
275///     direct_usage: BudgetUsage,
276///     child: &ChildRunAdmissionIntent,
277///     now: Timestamp,
278/// ) -> Result<ChildRunBudgetAccount, ChildRunBudgetError> {
279///     let account = ChildRunBudgetAccount::new(parent, graph, direct_head, direct_usage)?;
280///     account.reserve(child, graph, now)
281/// }
282/// ```
283#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
284#[serde(deny_unknown_fields)]
285pub struct ChildRunBudgetAccount {
286    #[schemars(range(min = 1, max = 1))]
287    version: u8,
288    parent: AgentResultProvenance,
289    parent_admission_digest: Digest,
290    parent_admitted_at: Timestamp,
291    graph: GraphReference,
292    budget: ResolvedBudget,
293    #[schemars(range(min = 1, max = 256))]
294    maximum_children: u16,
295    direct_head: JournalHead,
296    direct_usage: BudgetUsage,
297    #[schemars(length(max = 256))]
298    children: Vec<ChildRunBudgetEntry>,
299    digest: Digest,
300}
301
302impl ChildRunBudgetAccount {
303    /// Hard lifetime bound; settled entries still count toward the bound.
304    pub const MAX_CHILDREN: usize = 256;
305    /// Hard serialized snapshot size. Adapters must also cap input before decode.
306    pub const MAX_SNAPSHOT_BYTES: usize = 8 * 1024 * 1024;
307
308    /// Starts from an authoritative parent direct-usage observation, not zero
309    /// by assumption. Parent graph declarations and immutable admission must agree.
310    pub fn new(
311        parent: &AgentAdmission,
312        graph: &CompiledGraph,
313        direct_head: JournalHead,
314        direct_usage: BudgetUsage,
315    ) -> Result<Self, ChildRunBudgetError> {
316        let policy = graph
317            .child_runs()
318            .ok_or(ChildRunBudgetError::ParentMismatch)?;
319        if direct_head.recorded_at() < parent.admitted_at() {
320            return Err(ChildRunBudgetError::DirectObservationMismatch);
321        }
322        let value = Self {
323            version: 1,
324            parent: parent.intent().provenance().clone(),
325            parent_admission_digest: parent.digest(),
326            parent_admitted_at: parent.admitted_at(),
327            graph: graph.reference(),
328            budget: parent.intent().budget().clone(),
329            maximum_children: policy.limits().maximum_children_per_run(),
330            direct_head,
331            direct_usage,
332            children: Vec::new(),
333            digest: Digest::sha256([]),
334        }
335        .seal()?;
336        value.validate_for(parent, graph)?;
337        Ok(value)
338    }
339
340    /// Rebinds restored accounting to authoritative immutable admission/graph pins.
341    /// Does not establish that direct/child observations are current or authentic.
342    pub fn validate_for(
343        &self,
344        parent: &AgentAdmission,
345        graph: &CompiledGraph,
346    ) -> Result<(), ChildRunBudgetError> {
347        if self.parent != *parent.intent().provenance()
348            || self.parent_admission_digest != parent.digest()
349            || self.parent_admitted_at != parent.admitted_at()
350            || self.graph != *parent.intent().graph()
351            || self.graph != graph.reference()
352            || self.budget != *parent.intent().budget()
353            || graph
354                .child_runs()
355                .map(|policy| policy.limits().maximum_children_per_run())
356                != Some(self.maximum_children)
357            || self.direct_head.recorded_at() < parent.admitted_at()
358        {
359            return Err(ChildRunBudgetError::ParentMismatch);
360        }
361        Ok(())
362    }
363
364    /// Adds one finite reservation, or returns the unchanged original on a
365    /// matching ownership-key/spawn-digest retry. Replacement candidate Run IDs
366    /// do not replace the first accepted identities. Rechecks the frozen node/slot
367    /// declaration. Readiness, fences, authority, and live topology are additional
368    /// adapter responsibilities.
369    pub fn reserve(
370        &self,
371        intent: &ChildRunAdmissionIntent,
372        parent_graph: &CompiledGraph,
373        observed_at: Timestamp,
374    ) -> Result<Self, ChildRunBudgetError> {
375        if intent.parent_admission_digest() != self.parent_admission_digest
376            || intent.key().tenant_id() != self.parent.tenant_id()
377            || intent.key().parent_run_id() != self.parent.run_id()
378            || intent.key().parent().base_checkpoint().graph() != &self.graph
379            || parent_graph.reference() != self.graph
380        {
381            return Err(ChildRunBudgetError::ParentMismatch);
382        }
383        intent.validate_declaration(parent_graph)?;
384        intent.child().budget().validate_narrowing(&self.budget)?;
385        if let Some(existing) = self.entry(intent.key()) {
386            return if existing.spawn_digest == intent.spawn_digest() {
387                Ok(self.clone())
388            } else {
389                Err(ChildRunBudgetError::SpawnConflict)
390            };
391        }
392        if self.children.len() >= usize::from(self.maximum_children) {
393            return Err(ChildRunBudgetError::TooManyChildren);
394        }
395        let mut next = self.clone();
396        next.children.push(ChildRunBudgetEntry {
397            key: intent.key().clone(),
398            spawn_digest: intent.spawn_digest(),
399            child: intent.child().provenance().clone(),
400            intent_digest: intent.child().intent_digest(),
401            reservation: CumulativeBudgetReservation::from_budget(intent.child().budget())?,
402            settlement: None,
403        });
404        next.remaining(observed_at)?;
405        next.seal()
406    }
407
408    /// Replaces an outstanding reservation with exact terminal usage once.
409    /// A known overrun is retained, never clipped or dropped; `remaining` then
410    /// blocks further admission. Unknown pricing keeps the old reservation.
411    /// This does not release child ownership or satisfy a lifecycle join.
412    pub fn settle(
413        &self,
414        key: &ChildRunKey,
415        settlement: ChildRunBudgetSettlement,
416    ) -> Result<Self, ChildRunBudgetError> {
417        settlement.validate()?;
418        let index = self
419            .children
420            .iter()
421            .position(|entry| &entry.key == key)
422            .ok_or(ChildRunBudgetError::ChildNotFound)?;
423        let entry = &self.children[index];
424        if entry.child != settlement.child || entry.intent_digest != settlement.intent_digest {
425            return Err(ChildRunBudgetError::TerminalMismatch);
426        }
427        if settlement.admitted_at < self.parent_admitted_at {
428            return Err(ChildRunBudgetError::TerminalMismatch);
429        }
430        if let Some(existing) = &entry.settlement {
431            return if existing == &settlement {
432                Ok(self.clone())
433            } else {
434                Err(ChildRunBudgetError::SettlementConflict)
435            };
436        }
437        let mut next = self.clone();
438        next.children[index].settlement = Some(settlement);
439        next.seal()
440    }
441
442    /// Records an absolute, non-regressing DIRECT usage observation at a later
443    /// journal head, not a delta and not a total that already contains children.
444    /// Exact replay is a no-op; changed evidence at the same head is a conflict.
445    /// Actual over-budget/unpriced usage remains visible and blocks admission.
446    pub fn observe_direct(
447        &self,
448        head: JournalHead,
449        usage: BudgetUsage,
450    ) -> Result<Self, ChildRunBudgetError> {
451        if head == self.direct_head && usage == self.direct_usage {
452            return Ok(self.clone());
453        }
454        if head.tenant_id() != self.parent.tenant_id()
455            || head.run_id() != self.parent.run_id()
456            || head.sequence() <= self.direct_head.sequence()
457            || head.recorded_at() < self.direct_head.recorded_at()
458        {
459            return Err(ChildRunBudgetError::DirectObservationMismatch);
460        }
461        usage.validate_monotonic_after(&self.direct_usage)?;
462        let mut next = self.clone();
463        next.direct_head = head;
464        next.direct_usage = usage;
465        next.seal()
466    }
467
468    /// Returns additive settled usage of immediate child subtrees, exactly once.
469    /// Child-local topology peaks do not leak into the parent's peak observations.
470    pub fn delegated_usage(&self) -> Result<BudgetUsage, ChildRunBudgetError> {
471        let mut total = BudgetUsage::zero();
472        for entry in &self.children {
473            if let Some(settlement) = &entry.settlement {
474                total = total.checked_accumulate(&settlement.usage.cumulative_only())?;
475            }
476        }
477        Ok(total)
478    }
479
480    /// Returns direct plus settled delegated usage, excluding all reservations.
481    pub fn accounted_usage(&self) -> Result<BudgetUsage, ChildRunBudgetError> {
482        Ok(self
483            .direct_usage
484            .checked_accumulate(&self.delegated_usage()?)?)
485    }
486
487    /// Checks actual accounted usage plus all outstanding ceilings at a fresh
488    /// supplied clock. Capacity is a projection, never evidence of expenditure.
489    pub fn remaining(
490        &self,
491        observed_at: Timestamp,
492    ) -> Result<BudgetRemaining, ChildRunBudgetError> {
493        if observed_at < self.direct_head.recorded_at()
494            || self
495                .children
496                .iter()
497                .filter_map(|entry| entry.settlement.as_ref())
498                .any(|settlement| observed_at < settlement.terminal.recorded_at())
499        {
500            return Err(ChildRunBudgetError::ClockBeforeEvidence);
501        }
502        let outstanding: Vec<_> = self
503            .children
504            .iter()
505            .filter(|entry| entry.settlement.is_none())
506            .map(|entry| entry.reservation.clone())
507            .collect();
508        Ok(CumulativeBudgetReservation::check_capacity(
509            &self.budget,
510            &self.accounted_usage()?,
511            &outstanding,
512            observed_at,
513        )?)
514    }
515
516    /// Returns the original retained record for an exact logical key.
517    #[must_use]
518    pub fn entry(&self, key: &ChildRunKey) -> Option<&ChildRunBudgetEntry> {
519        self.children.iter().find(|entry| &entry.key == key)
520    }
521
522    /// Returns canonically ordered lifetime records, including settled children.
523    #[must_use]
524    pub fn children(&self) -> &[ChildRunBudgetEntry] {
525        &self.children
526    }
527
528    /// Returns the separately retained direct-usage observation.
529    #[must_use]
530    pub const fn direct_usage(&self) -> &BudgetUsage {
531        &self.direct_usage
532    }
533
534    /// Returns the exact journal head of the separately retained direct observation.
535    #[must_use]
536    pub const fn direct_head(&self) -> &JournalHead {
537        &self.direct_head
538    }
539
540    /// Returns the fingerprint an adapter must use for atomic snapshot replacement.
541    #[must_use]
542    pub const fn digest(&self) -> Digest {
543        self.digest
544    }
545
546    /// Encodes closed, bounded canonical state. Checksums are not authentication.
547    pub fn canonical_bytes(&self) -> Result<Vec<u8>, ChildRunBudgetError> {
548        let bytes = crate::agent_admission::canonical_bytes(self)
549            .map_err(|_| ChildRunBudgetError::Encoding)?;
550        if bytes.len() > Self::MAX_SNAPSHOT_BYTES {
551            return Err(ChildRunBudgetError::Encoding);
552        }
553        Ok(bytes)
554    }
555
556    fn seal(mut self) -> Result<Self, ChildRunBudgetError> {
557        if self.version != 1 {
558            return Err(ChildRunBudgetError::UnsupportedVersion);
559        }
560        if self.maximum_children == 0
561            || usize::from(self.maximum_children) > Self::MAX_CHILDREN
562            || self.children.len() > usize::from(self.maximum_children)
563        {
564            return Err(ChildRunBudgetError::TooManyChildren);
565        }
566        if self.direct_head.tenant_id() != self.parent.tenant_id()
567            || self.direct_head.run_id() != self.parent.run_id()
568            || self.direct_head.recorded_at() < self.parent_admitted_at
569        {
570            return Err(ChildRunBudgetError::DirectObservationMismatch);
571        }
572        self.children.sort_by_key(|entry| entry.key.digest());
573        let mut keys = BTreeSet::new();
574        let mut runs = BTreeSet::new();
575        for entry in &self.children {
576            entry.validate()?;
577            if entry.key.tenant_id() != self.parent.tenant_id()
578                || entry.key.parent_run_id() != self.parent.run_id()
579                || entry.key.parent().base_checkpoint().graph() != &self.graph
580                || entry.child.tenant_id() != self.parent.tenant_id()
581                || entry.child.run_id() == self.parent.run_id()
582            {
583                return Err(ChildRunBudgetError::ParentMismatch);
584            }
585            if !keys.insert(entry.key.digest()) || !runs.insert(entry.child.run_id()) {
586                return Err(ChildRunBudgetError::DuplicateChild);
587            }
588            if let Some(settlement) = &entry.settlement {
589                if settlement.admitted_at < self.parent_admitted_at {
590                    return Err(ChildRunBudgetError::TerminalMismatch);
591                }
592            }
593        }
594        self.accounted_usage()?;
595        // Fixed zero in the preimage avoids serializing a second shadow wire.
596        self.digest = Digest::sha256([]);
597        let mut preimage = DOMAIN.to_vec();
598        preimage.extend(self.canonical_bytes()?);
599        self.digest = Digest::sha256(preimage);
600        Ok(self)
601    }
602}
603
604impl<'de> Deserialize<'de> for ChildRunBudgetAccount {
605    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
606        #[derive(Deserialize)]
607        #[serde(deny_unknown_fields)]
608        struct Wire {
609            version: u8,
610            parent: AgentResultProvenance,
611            parent_admission_digest: Digest,
612            parent_admitted_at: Timestamp,
613            graph: GraphReference,
614            budget: ResolvedBudget,
615            maximum_children: u16,
616            direct_head: JournalHead,
617            direct_usage: BudgetUsage,
618            #[serde(deserialize_with = "bounded_children")]
619            children: Vec<ChildRunBudgetEntry>,
620            digest: Digest,
621        }
622        let wire = Wire::deserialize(deserializer)?;
623        let expected = wire.digest;
624        let value = Self {
625            version: wire.version,
626            parent: wire.parent,
627            parent_admission_digest: wire.parent_admission_digest,
628            parent_admitted_at: wire.parent_admitted_at,
629            graph: wire.graph,
630            budget: wire.budget,
631            maximum_children: wire.maximum_children,
632            direct_head: wire.direct_head,
633            direct_usage: wire.direct_usage,
634            children: wire.children,
635            digest: expected,
636        }
637        .seal()
638        .map_err(de::Error::custom)?;
639        if value.digest != expected {
640            return Err(de::Error::custom(ChildRunBudgetError::DigestMismatch));
641        }
642        Ok(value)
643    }
644}
645
646fn bounded_children<'de, D: Deserializer<'de>>(
647    deserializer: D,
648) -> Result<Vec<ChildRunBudgetEntry>, D::Error> {
649    struct Visitor;
650    impl<'de> de::Visitor<'de> for Visitor {
651        type Value = Vec<ChildRunBudgetEntry>;
652        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
653            formatter.write_str("at most 256 lifetime child budget entries")
654        }
655        fn visit_seq<A: de::SeqAccess<'de>>(
656            self,
657            mut sequence: A,
658        ) -> Result<Self::Value, A::Error> {
659            let maximum = ChildRunBudgetAccount::MAX_CHILDREN;
660            if sequence.size_hint().is_some_and(|size| size > maximum) {
661                return Err(de::Error::custom(ChildRunBudgetError::TooManyChildren));
662            }
663            let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(maximum));
664            while let Some(value) = sequence.next_element()? {
665                if values.len() == maximum {
666                    return Err(de::Error::custom(ChildRunBudgetError::TooManyChildren));
667                }
668                values.push(value);
669            }
670            Ok(values)
671        }
672    }
673    deserializer.deserialize_seq(Visitor)
674}
675
676/// Closed, public-safe accounting refusal without child inputs or outputs.
677#[derive(Clone, Debug, Eq, Error, PartialEq)]
678#[non_exhaustive]
679pub enum ChildRunBudgetError {
680    /// Admission, tenant, run or graph does not own this account or child.
681    #[error("child budget parent mismatch")]
682    ParentMismatch,
683    /// Unsupported wire version cannot silently acquire current semantics.
684    #[error("unsupported child budget account version")]
685    UnsupportedVersion,
686    /// Lifetime capacity includes settled entries and cannot be recycled.
687    #[error("child budget lifetime bound exceeded")]
688    TooManyChildren,
689    /// Logical key or selected child identity was repeated.
690    #[error("duplicate child budget identity")]
691    DuplicateChild,
692    /// Same logical key was retried with changed immutable spawn intent.
693    #[error("child budget spawn conflict")]
694    SpawnConflict,
695    /// Terminal evidence was changed after one accepted settlement.
696    #[error("child budget settlement conflict")]
697    SettlementConflict,
698    /// Settlement references no retained reservation.
699    #[error("child budget reservation not found")]
700    ChildNotFound,
701    /// Lifecycle is not terminal and cannot release its reservation.
702    #[error("child budget requires terminal evidence")]
703    NotTerminal,
704    /// Terminal evidence and immutable child/admission/journal identities differ.
705    #[error("child budget terminal evidence mismatch")]
706    TerminalMismatch,
707    /// Unknown cost must retain its outstanding reservation.
708    #[error("child budget cannot settle unpriced usage")]
709    UnpricedSettlement,
710    /// Direct usage was substituted, stale, or bound to another journal.
711    #[error("child budget direct observation mismatch")]
712    DirectObservationMismatch,
713    /// Capacity was evaluated with a clock older than retained accounting evidence.
714    #[error("child budget clock predates accounting evidence")]
715    ClockBeforeEvidence,
716    /// The bounded canonical account could not be encoded.
717    #[error("child budget account encoding failed")]
718    Encoding,
719    /// Restored state differs from its integrity fingerprint.
720    #[error("child budget account digest mismatch")]
721    DigestMismatch,
722    /// Scalar/currency arithmetic overflow or monotonicity violation.
723    #[error(transparent)]
724    Usage(#[from] BudgetUsageError),
725    /// Reservation projection exceeds finite or observable capacity.
726    #[error(transparent)]
727    Reservation(#[from] CumulativeBudgetReservationError),
728    /// Declared parent/child closure validation failed.
729    #[error(transparent)]
730    Declaration(#[from] ChildRunPolicyError),
731    /// A child ceiling or deadline widened the immutable parent budget.
732    #[error(transparent)]
733    Narrowing(#[from] BudgetNarrowingError),
734}