Skip to main content

rocketmq_runtime/resource_budget/
budget.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16use std::sync::atomic::fence;
17use std::sync::atomic::AtomicU64;
18use std::sync::atomic::AtomicUsize;
19use std::sync::atomic::Ordering;
20use std::sync::Arc;
21use std::sync::Mutex;
22use std::sync::MutexGuard;
23
24use smallvec::SmallVec;
25use std::time::Duration;
26use tokio::sync::futures::Notified;
27use tokio::sync::Notify;
28
29use super::clock::MonotonicClock;
30use super::clock::SystemMonotonicClock;
31use super::dynamic::DynamicBudgetKey;
32use super::dynamic::DynamicKeyRegistrationFailure;
33use super::dynamic::DynamicKeyRegistry;
34use super::limit::BudgetClass;
35use super::limit::BudgetDimension;
36use super::limit::BudgetLimit;
37use super::limit::FullPolicy;
38use super::limit::RateLimit;
39
40/// Represents budget snapshot.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct BudgetSnapshot {
43    /// The path value.
44    pub path: Arc<str>,
45    /// The number of current entries.
46    pub current_count: usize,
47    /// The current size in bytes.
48    pub current_bytes: usize,
49    /// The number of admitted entries.
50    pub admitted_count: u64,
51    /// The number of released entries.
52    pub released_count: u64,
53    /// The number of rejected entries.
54    pub rejected_count: u64,
55    /// The number of throttled entries.
56    pub throttled_count: u64,
57    /// The number of dropped entries.
58    pub dropped_count: u64,
59    /// The number of coalesced entries.
60    pub coalesced_count: u64,
61    /// The number of closed slow consumer entries.
62    pub closed_slow_consumer_count: u64,
63}
64
65/// A normal resource-budget admission rejection.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct BudgetRejection {
68    path: Arc<str>,
69    exhausted_path: Arc<str>,
70    reason: BudgetRejectionReason,
71    policy: FullPolicy,
72}
73
74/// Why a resource budget refused new work.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum BudgetRejectionReason {
77    /// Count, byte, or rate capacity is exhausted.
78    Capacity(BudgetDimension),
79    /// This dynamic generation or one of its ancestors has closed admission.
80    Closed,
81}
82
83impl BudgetRejection {
84    #[must_use]
85    /// Returns the path.
86    pub fn path(&self) -> &str {
87        &self.path
88    }
89
90    #[must_use]
91    /// Returns the exhausted path.
92    pub fn exhausted_path(&self) -> &str {
93        &self.exhausted_path
94    }
95
96    #[must_use]
97    /// Returns the exhausted capacity dimension, or `None` for closed admission.
98    pub const fn dimension(&self) -> Option<BudgetDimension> {
99        match self.reason {
100            BudgetRejectionReason::Capacity(dimension) => Some(dimension),
101            BudgetRejectionReason::Closed => None,
102        }
103    }
104
105    /// Returns the admission rejection reason without projecting closure onto capacity.
106    #[must_use]
107    pub const fn reason(&self) -> BudgetRejectionReason {
108        self.reason
109    }
110
111    /// Returns whether admission has permanently closed for this handle.
112    #[must_use]
113    pub const fn is_closed(&self) -> bool {
114        matches!(self.reason, BudgetRejectionReason::Closed)
115    }
116
117    #[must_use]
118    /// Returns the policy.
119    pub const fn policy(&self) -> FullPolicy {
120        self.policy
121    }
122}
123
124/// The result of moving a permit's reservations from its source budget to a
125/// target budget in the same tree.
126///
127/// Reservations held by ancestors shared by both budgets stay held throughout
128/// the transfer. A rejection leaves the source permit exactly as it was.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum PermitBudgetTransferStatus {
131    /// The permit now owns the target budget chain.
132    Rebound,
133    /// The permit was already bound to the requested target.
134    Unchanged,
135    /// The target rejected the permit and the source permit is unchanged.
136    Rejected(BudgetRejection),
137}
138
139/// Represents resource budget tree.
140pub struct ResourceBudgetTree {
141    root: ResourceBudget,
142}
143
144impl fmt::Debug for ResourceBudgetTree {
145    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146        formatter
147            .debug_struct("ResourceBudgetTree")
148            .field("root", &self.root)
149            .finish()
150    }
151}
152
153impl ResourceBudgetTree {
154    /// Creates a new `ResourceBudgetTree`.
155    ///
156    /// # Errors
157    ///
158    /// Returns a contract violation when the root name is blank or malformed,
159    /// or when its budget limit is invalid.
160    pub fn new(name: impl Into<String>, limit: BudgetLimit) -> Result<Self, crate::RuntimeContractViolation> {
161        Self::with_clock(name, limit, Arc::new(SystemMonotonicClock::new()))
162    }
163
164    /// Creates a tree with an injected monotonic clock.
165    ///
166    /// # Errors
167    ///
168    /// Returns a contract violation when the root name is blank or malformed,
169    /// or when its budget limit is invalid.
170    pub fn with_clock(
171        name: impl Into<String>,
172        limit: BudgetLimit,
173        clock: Arc<dyn MonotonicClock>,
174    ) -> Result<Self, crate::RuntimeContractViolation> {
175        let name = validated_name(name.into())?;
176        limit.validate(&name)?;
177        let admission_gates: Arc<[Arc<AdmissionGate>]> = Arc::from([]);
178        let capacity_notify = Arc::new(CapacitySignal::default());
179        let node = Arc::new(BudgetNode::new(
180            Arc::from(name.as_str()),
181            limit,
182            clock,
183            admission_gates.clone(),
184            Arc::clone(&capacity_notify),
185            true,
186        ));
187        Ok(Self {
188            root: ResourceBudget {
189                node: Arc::clone(&node),
190                chain: Arc::from([node]),
191                capacity_notify,
192                keys: DynamicKeyRegistry::new(),
193                admission_gates,
194            },
195        })
196    }
197
198    /// Creates a tree whose dynamic key registry holds at most `max_entries`
199    /// names.
200    ///
201    /// # Errors
202    ///
203    /// Returns a contract violation when the root name is blank or malformed,
204    /// or when its budget limit is invalid.
205    pub fn with_clock_and_key_capacity(
206        name: impl Into<String>,
207        limit: BudgetLimit,
208        clock: Arc<dyn MonotonicClock>,
209        max_entries: usize,
210    ) -> Result<Self, crate::RuntimeContractViolation> {
211        let mut tree = Self::with_clock(name, limit, clock)?;
212        tree.root.keys = DynamicKeyRegistry::with_max_entries(max_entries);
213        Ok(tree)
214    }
215
216    #[must_use]
217    /// Returns the root.
218    pub fn root(&self) -> ResourceBudget {
219        self.root.clone()
220    }
221}
222
223/// Represents resource budget.
224#[derive(Clone)]
225pub struct ResourceBudget {
226    node: Arc<BudgetNode>,
227    chain: Arc<[Arc<BudgetNode>]>,
228    capacity_notify: Arc<CapacitySignal>,
229    keys: DynamicKeyRegistry,
230    admission_gates: Arc<[Arc<AdmissionGate>]>,
231}
232
233/// Wakes tasks of one budget tree that wait for capacity or for a dynamic budget to close.
234///
235/// Every permit release, rebind, shrink, and promotion in the tree signals capacity, and those
236/// happen several times per request, so a capacity signal first checks whether anyone waits
237/// instead of always taking the `Notify` lock. A waiter enables its [`Notified`] and registers
238/// through [`Self::register_waiter`] before its final capacity check; a signal fences after the
239/// capacity change and before reading the waiter count. One of the two always observes the
240/// other, so a release is never lost. Closure is rare and always notifies.
241#[derive(Default)]
242pub(crate) struct CapacitySignal {
243    notify: Notify,
244    waiters: AtomicUsize,
245}
246
247impl CapacitySignal {
248    /// Returns a future completed by the next capacity or closure signal.
249    pub(crate) fn notified(&self) -> Notified<'_> {
250        self.notify.notified()
251    }
252
253    /// Counts the caller as waiting for capacity until the guard drops.
254    ///
255    /// Call it after enabling the [`Notified`] from [`Self::notified`] and before the final
256    /// capacity check.
257    pub(crate) fn register_waiter(&self) -> CapacityWaiter<'_> {
258        self.waiters.fetch_add(1, Ordering::SeqCst);
259        fence(Ordering::SeqCst);
260        CapacityWaiter { signal: self }
261    }
262
263    /// Signals a capacity change, after it is visible in the budget counters.
264    fn signal(&self) {
265        fence(Ordering::SeqCst);
266        if self.waiters.load(Ordering::Acquire) != 0 {
267            self.notify.notify_waiters();
268        }
269    }
270
271    /// Signals that a dynamic budget closed, waking every enabled waiter.
272    fn signal_closed(&self) {
273        self.notify.notify_waiters();
274    }
275}
276
277/// A waiter counted by [`CapacitySignal::register_waiter`].
278pub(crate) struct CapacityWaiter<'a> {
279    signal: &'a CapacitySignal,
280}
281
282impl Drop for CapacityWaiter<'_> {
283    fn drop(&mut self) {
284        self.signal.waiters.fetch_sub(1, Ordering::Release);
285    }
286}
287
288struct AdmissionGate {
289    path: Arc<str>,
290    closed: Mutex<bool>,
291}
292
293// Always acquire gates root-to-leaf, before node or queue state locks. Static
294// budgets have no gates. Keeping this guard across a synchronous queue admission
295// also prevents closure from triggering destructive capacity/age policies.
296pub(super) struct BudgetAdmission<'a> {
297    budget: &'a ResourceBudget,
298    _guards: SmallVec<[MutexGuard<'a, bool>; 2]>,
299}
300
301impl BudgetAdmission<'_> {
302    pub(super) fn try_acquire(&self, bytes: usize, class: BudgetClass) -> Result<ResourcePermit, BudgetRejection> {
303        self.budget.try_acquire_open(bytes, class, true)
304    }
305
306    pub(super) fn try_acquire_waiting(
307        &self,
308        bytes: usize,
309        class: BudgetClass,
310    ) -> Result<ResourcePermit, BudgetRejection> {
311        self.budget.try_acquire_open(bytes, class, false)
312    }
313}
314
315impl fmt::Debug for ResourceBudget {
316    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
317        formatter
318            .debug_struct("ResourceBudget")
319            .field("path", &self.node.path)
320            .field("limit", &self.node.limit)
321            .finish()
322    }
323}
324
325impl ResourceBudget {
326    /// Creates a child that inherits every dynamic ancestor's admission state.
327    ///
328    /// Creating a static child after closure is allowed; the resulting handle
329    /// remains closed and cannot acquire or accept rebound permits.
330    ///
331    /// # Errors
332    ///
333    /// Returns a contract violation when the child name is blank or malformed,
334    /// its limit is invalid, or its limit exceeds its parent.
335    pub fn child(&self, name: impl Into<String>, limit: BudgetLimit) -> Result<Self, crate::RuntimeContractViolation> {
336        self.child_with_gates(name, limit, self.admission_gates.clone(), true)
337    }
338
339    /// Creates a group child named `name` together with all of its children.
340    ///
341    /// The group joins its children under one path, `<this>/<name>/<child>`, and enforces
342    /// `limit` like any other level. When no rate is configured and the children's capacities,
343    /// and their capacities net of the control reserve, add up to no more than the group's,
344    /// the group can never run out before one of its children does. It then counts nothing
345    /// itself, which saves one shared update per permit taken below it. The group handle is
346    /// not returned, so nothing acquires from it directly or adds children to it later.
347    ///
348    /// # Errors
349    ///
350    /// Returns a contract violation when a name or limit is invalid, or when a child limit
351    /// exceeds the group limit.
352    pub fn child_group<const N: usize>(
353        &self,
354        name: impl Into<String>,
355        limit: BudgetLimit,
356        children: [(&str, BudgetLimit); N],
357    ) -> Result<[Self; N], crate::RuntimeContractViolation> {
358        let counted = !children_fit_within(limit, children.iter().map(|(_, child)| *child));
359        let group = self.child_with_gates(name, limit, self.admission_gates.clone(), counted)?;
360        let mut created = Vec::with_capacity(N);
361        for (child_name, child_limit) in children {
362            created.push(group.child(child_name, child_limit)?);
363        }
364        Ok(created
365            .try_into()
366            .unwrap_or_else(|_: Vec<Self>| unreachable!("one budget is created for each of the N children")))
367    }
368
369    fn child_with_gates(
370        &self,
371        name: impl Into<String>,
372        limit: BudgetLimit,
373        admission_gates: Arc<[Arc<AdmissionGate>]>,
374        counted: bool,
375    ) -> Result<Self, crate::RuntimeContractViolation> {
376        let name = validated_name(name.into())?;
377        let path: Arc<str> = Arc::from(format!("{}/{}", self.node.path, name));
378        limit.validate_child(self.node.limit, &path)?;
379        let node = Arc::new(BudgetNode::new(
380            path,
381            limit,
382            Arc::clone(&self.node.clock),
383            admission_gates.clone(),
384            Arc::clone(&self.capacity_notify),
385            counted,
386        ));
387        let mut chain = Vec::with_capacity(self.chain.len() + 1);
388        chain.extend(self.chain.iter().cloned());
389        chain.push(Arc::clone(&node));
390        Ok(Self {
391            node,
392            chain: Arc::from(chain),
393            capacity_notify: Arc::clone(&self.capacity_notify),
394            keys: self.keys.clone(),
395            admission_gates,
396        })
397    }
398
399    /// Registers a bounded dynamic child key under this budget.
400    ///
401    /// The key owns a child budget and holds its name reserved until
402    /// [`DynamicBudgetKey::retire_until`] observes that the child has no
403    /// reservations left. A name that is already held cannot be registered
404    /// again, so a retired generation never runs beside the one that replaced
405    /// it. Use [`Self::child`] when the key does not need a retirement
406    /// lifecycle.
407    ///
408    /// # Errors
409    ///
410    /// Returns [`DynamicKeyRegistrationFailure`] when the child contract is
411    /// invalid, a dynamic ancestor has closed, the name is still held, or the
412    /// tree holds its maximum number of dynamic keys.
413    pub fn register_dynamic_child(
414        &self,
415        name: impl Into<String>,
416        limit: BudgetLimit,
417    ) -> Result<DynamicBudgetKey, DynamicKeyRegistrationFailure> {
418        let _admission = self.admit().map_err(|_| DynamicKeyRegistrationFailure::Closed)?;
419        let name = validated_name(name.into()).map_err(DynamicKeyRegistrationFailure::Invalid)?;
420        let path: Arc<str> = Arc::from(format!("{}/{}", self.node.path, name));
421        let mut gates = self.admission_gates.to_vec();
422        gates.push(Arc::new(AdmissionGate {
423            path: path.clone(),
424            closed: Mutex::new(false),
425        }));
426        let child = self
427            .child_with_gates(name, limit, Arc::from(gates), true)
428            .map_err(DynamicKeyRegistrationFailure::Invalid)?;
429        self.keys.register(child, path)
430    }
431
432    /// Returns whether a dynamic ancestor has permanently closed admission.
433    /// Existing permits remain valid and can still be released or moved to an open budget.
434    #[must_use]
435    pub fn is_closed(&self) -> bool {
436        self.admission_gates
437            .iter()
438            .any(|gate| *gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner))
439    }
440
441    pub(super) fn close_dynamic(&self) {
442        if let Some(gate) = self.admission_gates.last() {
443            *gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true;
444            self.capacity_notify.signal_closed();
445        }
446    }
447
448    pub(super) fn admit(&self) -> Result<BudgetAdmission<'_>, BudgetRejection> {
449        let mut guards = SmallVec::new();
450        for gate in self.admission_gates.iter() {
451            let guard = gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
452            if *guard {
453                let rejection = BudgetRejection {
454                    path: self.node.path.clone(),
455                    exhausted_path: gate.path.clone(),
456                    reason: BudgetRejectionReason::Closed,
457                    policy: self.node.limit.full_policy,
458                };
459                self.record_budget_rejection(&rejection);
460                return Err(rejection);
461            }
462            guards.push(guard);
463        }
464        Ok(BudgetAdmission {
465            budget: self,
466            _guards: guards,
467        })
468    }
469
470    /// Attempts to acquire.
471    ///
472    /// A [`BudgetRejection`] is a normal bounded outcome when the requested
473    /// capacity is unavailable; it is not an operational runtime failure.
474    pub fn try_acquire(&self, bytes: usize, class: BudgetClass) -> Result<ResourcePermit, BudgetRejection> {
475        self.try_acquire_internal(bytes, class, true)
476    }
477
478    fn try_acquire_internal(
479        &self,
480        bytes: usize,
481        class: BudgetClass,
482        record_failure: bool,
483    ) -> Result<ResourcePermit, BudgetRejection> {
484        let _admission = self.admit()?;
485        self.try_acquire_open(bytes, class, record_failure)
486    }
487
488    fn try_acquire_open(
489        &self,
490        bytes: usize,
491        class: BudgetClass,
492        record_failure: bool,
493    ) -> Result<ResourcePermit, BudgetRejection> {
494        let mut reservations = PendingReservations::new(&self.chain, bytes, class);
495        if let Err((node, dimension)) = reservations.reserve_all() {
496            if record_failure {
497                self.record_node_rejection(node, BudgetRejectionReason::Capacity(dimension));
498            }
499            return Err(BudgetRejection {
500                path: Arc::clone(&self.node.path),
501                exhausted_path: Arc::clone(&node.path),
502                reason: BudgetRejectionReason::Capacity(dimension),
503                policy: self.node.limit.full_policy,
504            });
505        }
506        reservations.commit();
507        Ok(ResourcePermit {
508            chain: Arc::clone(&self.chain),
509            bytes,
510            class,
511        })
512    }
513
514    pub(crate) fn permanent_acquire_rejection(&self, bytes: usize, class: BudgetClass) -> Option<BudgetRejection> {
515        let _admission = match self.admit() {
516            Ok(admission) => admission,
517            Err(rejection) => return Some(rejection),
518        };
519        self.chain.iter().find_map(|node| {
520            let dimension = node.permanent_exhaustion_dimension(bytes, class)?;
521            self.record_node_rejection(node, BudgetRejectionReason::Capacity(dimension));
522            Some(BudgetRejection {
523                path: Arc::clone(&self.node.path),
524                exhausted_path: Arc::clone(&node.path),
525                reason: BudgetRejectionReason::Capacity(dimension),
526                policy: self.node.limit.full_policy,
527            })
528        })
529    }
530
531    pub(crate) fn record_budget_rejection(&self, error: &BudgetRejection) {
532        if let Some(node) = self
533            .chain
534            .iter()
535            .find(|node| node.path.as_ref() == error.exhausted_path())
536        {
537            self.record_node_rejection(node, error.reason());
538        }
539    }
540
541    fn record_node_rejection(&self, exhausted_node: &Arc<BudgetNode>, reason: BudgetRejectionReason) {
542        exhausted_node.record_rejection(reason);
543        if !Arc::ptr_eq(exhausted_node, &self.node) {
544            self.node.record_rejection(reason);
545        }
546    }
547
548    pub(crate) fn capacity_notify(&self) -> &CapacitySignal {
549        &self.capacity_notify
550    }
551
552    /// Returns whether a dynamic ancestor can close this budget's admission.
553    ///
554    /// A budget without dynamic ancestors never closes, so nothing needs to wait for that.
555    pub(crate) fn can_close(&self) -> bool {
556        !self.admission_gates.is_empty()
557    }
558
559    /// Attempts to acquire data.
560    ///
561    /// A [`BudgetRejection`] is a normal bounded outcome when data capacity is
562    /// unavailable; it is not an operational runtime failure.
563    pub fn try_acquire_data(&self, bytes: usize) -> Result<ResourcePermit, BudgetRejection> {
564        self.try_acquire(bytes, BudgetClass::Data)
565    }
566
567    /// Attempts to acquire control.
568    ///
569    /// A [`BudgetRejection`] is a normal bounded outcome when control capacity
570    /// is unavailable; it is not an operational runtime failure.
571    pub fn try_acquire_control(&self, bytes: usize) -> Result<ResourcePermit, BudgetRejection> {
572        self.try_acquire(bytes, BudgetClass::Control)
573    }
574
575    #[must_use]
576    /// Returns the snapshot.
577    pub fn snapshot(&self) -> BudgetSnapshot {
578        self.node.snapshot()
579    }
580
581    #[must_use]
582    /// Returns the path.
583    pub fn path(&self) -> &str {
584        &self.node.path
585    }
586
587    #[must_use]
588    /// Returns the limit.
589    pub fn limit(&self) -> BudgetLimit {
590        self.node.limit
591    }
592
593    /// Returns the current instant from this tree's injected monotonic clock.
594    #[must_use]
595    pub fn monotonic_now(&self) -> Duration {
596        self.node.clock.now()
597    }
598
599    /// Records items discarded by a queue or custom retention boundary.
600    pub fn record_dropped(&self, count: usize) {
601        self.node.record_dropped(count);
602    }
603
604    /// Records items folded into an already retained logical item.
605    pub fn record_coalesced(&self, count: usize) {
606        self.node.record_coalesced(count);
607    }
608
609    /// Records a slow consumer closed by this budget's full policy.
610    pub fn record_slow_consumer_closed(&self) {
611        self.node.record_slow_consumer_closed();
612    }
613}
614
615/// Whether a group with `limit` can never run out before one of `children` does.
616///
617/// Every reservation below the group is held by exactly one child subtree, and each child
618/// keeps its own total and data-class usage within its capacity, so the group's usage never
619/// exceeds the children's summed capacities. A rate cannot be derived from the children.
620fn children_fit_within(limit: BudgetLimit, children: impl Iterator<Item = BudgetLimit>) -> bool {
621    if limit.capacity.rate.is_some() {
622        return false;
623    }
624    let mut sums = Some([0usize; 4]);
625    for child in children {
626        sums = sums.and_then(|[count, bytes, data_count, data_bytes]| {
627            let data = data_capacity(child);
628            Some([
629                count.checked_add(child.capacity.count)?,
630                bytes.checked_add(child.capacity.bytes)?,
631                data_count.checked_add(data.0)?,
632                data_bytes.checked_add(data.1)?,
633            ])
634        });
635    }
636    let Some([count, bytes, data_count, data_bytes]) = sums else {
637        return false;
638    };
639    let (group_data_count, group_data_bytes) = data_capacity(limit);
640    count <= limit.capacity.count
641        && bytes <= limit.capacity.bytes
642        && data_count <= group_data_count
643        && data_bytes <= group_data_bytes
644}
645
646/// The count and bytes the data class may hold: capacity net of the control reserve.
647fn data_capacity(limit: BudgetLimit) -> (usize, usize) {
648    (
649        limit.capacity.count.saturating_sub(limit.control_reserve.count),
650        limit.capacity.bytes.saturating_sub(limit.control_reserve.bytes),
651    )
652}
653
654fn validated_name(name: String) -> Result<String, crate::RuntimeContractViolation> {
655    let name = name.trim();
656    if name.is_empty() {
657        return Err(crate::RuntimeContractViolation::EmptyBudgetName);
658    }
659    if name.contains('/') {
660        return Err(crate::RuntimeContractViolation::InvalidBudgetName);
661    }
662    Ok(name.to_owned())
663}
664
665/// Represents resource permit.
666///
667/// The permit holds one count and its `bytes` of its `class` at every node of `chain`, the
668/// chain of the budget it was acquired from or last rebound to, so a node needs no
669/// reservation record of its own and the permit shares the budget's chain instead of
670/// holding each level.
671pub struct ResourcePermit {
672    chain: Arc<[Arc<BudgetNode>]>,
673    bytes: usize,
674    class: BudgetClass,
675}
676
677impl fmt::Debug for ResourcePermit {
678    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
679        formatter
680            .debug_struct("ResourcePermit")
681            .field("path", &self.chain.last().map(|node| &node.path))
682            .field("bytes", &self.bytes)
683            .field("class", &self.class)
684            .finish()
685    }
686}
687
688impl ResourcePermit {
689    /// Changes the byte reservation without acquiring another count or rate token.
690    ///
691    /// Growth reserves only the difference at each ancestor. A rejection rolls
692    /// back every added byte and leaves this permit unchanged. Shrinking is
693    /// allowed after budget closure; callers release the removed payload before
694    /// shrinking its charge. This method does not block on available capacity.
695    ///
696    /// # Errors
697    ///
698    /// Returns a rejection if growth exceeds any ancestor's byte limit or a
699    /// dynamic ancestor has closed admission.
700    pub fn try_resize(&mut self, bytes: usize) -> Result<(), BudgetRejection> {
701        if bytes <= self.bytes {
702            self.shrink_to(bytes);
703            return Ok(());
704        }
705        let chain = &self.chain;
706        // Every budget chain starts at its tree root, so a permit always has a leaf.
707        let Some(leaf) = chain.last() else {
708            return Ok(());
709        };
710        let mut guards = SmallVec::<[MutexGuard<'_, bool>; 2]>::new();
711        for gate in leaf.admission_gates.iter() {
712            let guard = gate.closed.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
713            if *guard {
714                leaf.record_rejection(BudgetRejectionReason::Closed);
715                return Err(BudgetRejection {
716                    path: leaf.path.clone(),
717                    exhausted_path: gate.path.clone(),
718                    reason: BudgetRejectionReason::Closed,
719                    policy: leaf.limit.full_policy,
720                });
721            }
722            guards.push(guard);
723        }
724        let additional = bytes - self.bytes;
725        for (index, node) in chain.iter().enumerate() {
726            if !node.try_reserve_bytes(additional, self.class) {
727                for reserved in &chain[..index] {
728                    reserved.release_bytes(additional, self.class);
729                }
730                let reason = BudgetRejectionReason::Capacity(BudgetDimension::Bytes);
731                node.record_rejection(reason);
732                if !Arc::ptr_eq(node, leaf) {
733                    leaf.record_rejection(reason);
734                }
735                node.capacity_notify.signal();
736                return Err(BudgetRejection {
737                    path: leaf.path.clone(),
738                    exhausted_path: node.path.clone(),
739                    reason,
740                    policy: leaf.limit.full_policy,
741                });
742            }
743        }
744        drop(guards);
745        self.bytes = bytes;
746        Ok(())
747    }
748
749    pub(crate) fn shrink_to(&mut self, bytes: usize) {
750        let released = self.bytes.saturating_sub(bytes);
751        if released == 0 {
752            return;
753        }
754        for node in self.chain.iter() {
755            node.release_bytes(released, self.class);
756        }
757        self.bytes = bytes;
758        self.signal_capacity();
759    }
760
761    #[must_use]
762    /// Returns the bytes.
763    pub const fn bytes(&self) -> usize {
764        self.bytes
765    }
766
767    #[must_use]
768    /// Returns the class.
769    pub const fn class(&self) -> BudgetClass {
770        self.class
771    }
772
773    /// Promotes a data reservation to the control class without releasing capacity.
774    ///
775    /// The total count and byte ownership remain unchanged at every budget level. Data-only
776    /// counters and rate tokens are released before a same-tree rebind can use control reserve.
777    pub fn promote_to_control(&mut self) {
778        if self.class == BudgetClass::Control {
779            return;
780        }
781        for node in self.chain.iter() {
782            node.release_data_class(self.bytes);
783            if let Some(rate) = &node.rate {
784                BudgetNode::lock_rate(rate).restore_data(node.limit);
785            }
786        }
787        self.class = BudgetClass::Control;
788        self.signal_capacity();
789    }
790
791    /// Moves this reservation to another budget in the same resource tree.
792    ///
793    /// Reservations for the common ancestor chain remain owned throughout the
794    /// transfer. Target-only reservations are acquired before source-only
795    /// reservations are released, so the payload is always covered without
796    /// charging common ancestors twice.
797    ///
798    /// Returns a normal rejection when the target is full. Contract failures
799    /// and rejections leave this permit unchanged and valid for its source.
800    ///
801    /// # Errors
802    ///
803    /// Returns [`crate::RuntimeContractViolation::PermitTargetInDifferentTree`]
804    /// when `target` is outside this permit's resource-budget tree.
805    pub fn try_rebind(
806        &mut self,
807        target: &ResourceBudget,
808    ) -> Result<PermitBudgetTransferStatus, crate::RuntimeContractViolation> {
809        if !self.belongs_to_tree(target) {
810            return Err(crate::RuntimeContractViolation::PermitTargetInDifferentTree);
811        }
812        let admission = match target.admit() {
813            Ok(admission) => admission,
814            Err(rejection) => return Ok(PermitBudgetTransferStatus::Rejected(rejection)),
815        };
816        Ok(self.try_rebind_admitted(&admission))
817    }
818
819    pub(super) fn belongs_to_tree(&self, target: &ResourceBudget) -> bool {
820        self.chain
821            .first()
822            .zip(target.chain.first())
823            .is_some_and(|(held, node)| Arc::ptr_eq(held, node))
824    }
825
826    pub(super) fn try_rebind_admitted(&mut self, admission: &BudgetAdmission<'_>) -> PermitBudgetTransferStatus {
827        let target = admission.budget;
828        let common_ancestors = self
829            .chain
830            .iter()
831            .zip(target.chain.iter())
832            .take_while(|(held, target_node)| Arc::ptr_eq(held, target_node))
833            .count();
834        debug_assert!(
835            common_ancestors > 0,
836            "caller validates the permit tree before admission"
837        );
838        if common_ancestors == self.chain.len() && common_ancestors == target.chain.len() {
839            return PermitBudgetTransferStatus::Unchanged;
840        }
841
842        let mut target_reservations =
843            PendingReservations::new(&target.chain[common_ancestors..], self.bytes, self.class);
844        if let Err((node, dimension)) = target_reservations.reserve_all() {
845            target.record_node_rejection(node, BudgetRejectionReason::Capacity(dimension));
846            return PermitBudgetTransferStatus::Rejected(BudgetRejection {
847                path: Arc::clone(&target.node.path),
848                exhausted_path: Arc::clone(&node.path),
849                reason: BudgetRejectionReason::Capacity(dimension),
850                policy: target.node.limit.full_policy,
851            });
852        }
853        target_reservations.commit();
854
855        for node in &self.chain[common_ancestors..] {
856            node.release_held(self.bytes, self.class);
857        }
858        // The target chain starts with the common ancestors this permit keeps holding.
859        self.chain = Arc::clone(&target.chain);
860        self.signal_capacity();
861        PermitBudgetTransferStatus::Rebound
862    }
863
864    fn signal_capacity(&self) {
865        if let Some(root) = self.chain.first() {
866            root.capacity_notify.signal();
867        }
868    }
869}
870
871impl Drop for ResourcePermit {
872    fn drop(&mut self) {
873        for node in self.chain.iter() {
874            node.release_held(self.bytes, self.class);
875        }
876        self.signal_capacity();
877    }
878}
879
880/// One budget level.
881///
882/// Count and byte capacity is reserved with atomic read-modify-writes on packed
883/// [`PackedUsage`] words: one for all reservations and one for the data class.
884/// A request that fails at the data word, or at a later node of its chain,
885/// rolls back what it reserved, so no counter ever exceeds its limit. A
886/// concurrent request that observes capacity during such a rollback can be
887/// rejected even though the capacity is about to return.
888///
889/// A node of a [`ResourceBudget::child_group`] whose children fit within it
890/// can never be the first to run out, so it does not count at all.
891///
892/// Only a node that configures a rate takes a lock, around its token buckets.
893struct BudgetNode {
894    path: Arc<str>,
895    limit: BudgetLimit,
896    clock: Arc<dyn MonotonicClock>,
897    counted: bool,
898    total: PackedUsage,
899    data: PackedUsage,
900    total_limit: PackedLimit,
901    data_limit: PackedLimit,
902    counters: BudgetCounters,
903    rate: Option<Mutex<RateState>>,
904    // Resize uses the leaf node's gates, including after rebind. Keep this
905    // shared state out of every ResourcePermit and its downstream containers.
906    admission_gates: Arc<[Arc<AdmissionGate>]>,
907    // Every node of a tree shares the tree's signal, so a permit reaches it through its chain.
908    capacity_notify: Arc<CapacitySignal>,
909}
910
911/// Released counts follow from `admitted` minus what is held, so only admissions are counted.
912#[derive(Default)]
913struct BudgetCounters {
914    admitted: AtomicU64,
915    rejected: AtomicU64,
916    throttled: AtomicU64,
917    dropped: AtomicU64,
918    coalesced: AtomicU64,
919    closed_slow_consumer: AtomicU64,
920}
921
922/// Bits of a [`PackedUsage`] word that hold bytes; the count takes the rest.
923const PACKED_BYTE_BITS: u32 = 40;
924const PACKED_BYTE_MASK: u64 = (1 << PACKED_BYTE_BITS) - 1;
925/// Largest count one budget level holds: 16,777,215.
926const MAX_PACKED_COUNT: u64 = (1 << (u64::BITS - PACKED_BYTE_BITS)) - 1;
927/// Largest byte total one budget level holds: 1 TiB minus one byte.
928const MAX_PACKED_BYTES: u64 = PACKED_BYTE_MASK;
929
930/// A count and a byte limit as a [`PackedUsage`] word holds them.
931///
932/// A configured limit beyond a field's maximum is treated as that maximum; no
933/// process holds 16.7 million permits or a terabyte of reservations at once.
934#[derive(Clone, Copy)]
935struct PackedLimit {
936    count: u64,
937    bytes: u64,
938}
939
940impl PackedLimit {
941    fn new(count: usize, bytes: usize) -> Self {
942        Self {
943            count: packed_field(count).min(MAX_PACKED_COUNT),
944            bytes: packed_field(bytes).min(MAX_PACKED_BYTES),
945        }
946    }
947}
948
949fn packed_field(value: usize) -> u64 {
950    u64::try_from(value).unwrap_or(u64::MAX)
951}
952
953/// The count and bytes reserved at one budget level, in one word, so that one atomic
954/// read-modify-write reserves or releases both.
955///
956/// The count is in the high bits and the bytes in the low [`PACKED_BYTE_BITS`]. A reservation
957/// never takes either field past its [`PackedLimit`], and a release returns only what a
958/// reservation added, so subtracting a packed amount never borrows across the fields.
959#[derive(Default)]
960struct PackedUsage(AtomicU64);
961
962impl PackedUsage {
963    /// Adds `count` and `bytes` when both stay within `limit`; reports the count first.
964    fn try_reserve(&self, count: u64, bytes: usize, limit: PackedLimit) -> Result<(), BudgetDimension> {
965        let bytes = packed_field(bytes);
966        let mut current = self.0.load(Ordering::Acquire);
967        loop {
968            let held_count = current >> PACKED_BYTE_BITS;
969            let held_bytes = current & PACKED_BYTE_MASK;
970            let next_count = held_count + count;
971            if next_count > limit.count {
972                return Err(BudgetDimension::Count);
973            }
974            let Some(next_bytes) = held_bytes.checked_add(bytes).filter(|total| *total <= limit.bytes) else {
975                return Err(BudgetDimension::Bytes);
976            };
977            match self.0.compare_exchange_weak(
978                current,
979                (next_count << PACKED_BYTE_BITS) | next_bytes,
980                Ordering::AcqRel,
981                Ordering::Acquire,
982            ) {
983                Ok(_) => return Ok(()),
984                Err(actual) => current = actual,
985            }
986        }
987    }
988
989    /// Returns `count` and `bytes` that an earlier reservation added.
990    fn release(&self, count: u64, bytes: usize) {
991        let bytes = packed_field(bytes);
992        debug_assert!(
993            bytes <= MAX_PACKED_BYTES,
994            "a reservation never holds more than the packed maximum"
995        );
996        let previous = self.0.fetch_sub((count << PACKED_BYTE_BITS) | bytes, Ordering::AcqRel);
997        debug_assert!(
998            previous >> PACKED_BYTE_BITS >= count && previous & PACKED_BYTE_MASK >= bytes,
999            "budget capacity released more than reserved"
1000        );
1001    }
1002
1003    fn load(&self) -> (usize, usize) {
1004        let current = self.0.load(Ordering::Acquire);
1005        (
1006            usize::try_from(current >> PACKED_BYTE_BITS).unwrap_or(usize::MAX),
1007            usize::try_from(current & PACKED_BYTE_MASK).unwrap_or(usize::MAX),
1008        )
1009    }
1010}
1011
1012impl BudgetNode {
1013    fn try_reserve_bytes(&self, bytes: usize, class: BudgetClass) -> bool {
1014        if !self.counted {
1015            return true;
1016        }
1017        if self.total.try_reserve(0, bytes, self.total_limit).is_err() {
1018            return false;
1019        }
1020        if class == BudgetClass::Data && self.data.try_reserve(0, bytes, self.data_limit).is_err() {
1021            self.total.release(0, bytes);
1022            return false;
1023        }
1024        true
1025    }
1026
1027    fn release_bytes(&self, bytes: usize, class: BudgetClass) {
1028        if !self.counted {
1029            return;
1030        }
1031        if class == BudgetClass::Data {
1032            self.data.release(0, bytes);
1033        }
1034        self.total.release(0, bytes);
1035    }
1036
1037    fn new(
1038        path: Arc<str>,
1039        limit: BudgetLimit,
1040        clock: Arc<dyn MonotonicClock>,
1041        admission_gates: Arc<[Arc<AdmissionGate>]>,
1042        capacity_notify: Arc<CapacitySignal>,
1043        counted: bool,
1044    ) -> Self {
1045        let rate = limit
1046            .capacity
1047            .rate
1048            .map(|_| Mutex::new(RateState::new(limit, clock.now())));
1049        let capacity = limit.capacity;
1050        let reserve = limit.control_reserve;
1051        Self {
1052            path,
1053            limit,
1054            clock,
1055            counted,
1056            total: PackedUsage::default(),
1057            data: PackedUsage::default(),
1058            total_limit: PackedLimit::new(capacity.count, capacity.bytes),
1059            data_limit: PackedLimit::new(
1060                capacity.count.saturating_sub(reserve.count),
1061                capacity.bytes.saturating_sub(reserve.bytes),
1062            ),
1063            counters: BudgetCounters::default(),
1064            rate,
1065            admission_gates,
1066            capacity_notify,
1067        }
1068    }
1069
1070    fn lock_rate(rate: &Mutex<RateState>) -> MutexGuard<'_, RateState> {
1071        rate.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
1072    }
1073
1074    /// Reserves one count and `bytes` of `class`, and a rate token where the node has a rate.
1075    /// [`PendingReservations`] owns the reservation until it is committed to a permit.
1076    fn try_reserve(&self, bytes: usize, class: BudgetClass) -> Result<(), BudgetDimension> {
1077        if !self.counted {
1078            return Ok(());
1079        }
1080        self.total.try_reserve(1, bytes, self.total_limit)?;
1081        if class == BudgetClass::Data {
1082            if let Err(dimension) = self.data.try_reserve(1, bytes, self.data_limit) {
1083                self.total.release(1, bytes);
1084                return Err(dimension);
1085            }
1086        }
1087        if let Some(rate) = &self.rate {
1088            let mut rate = Self::lock_rate(rate);
1089            rate.refill(self.limit, self.clock.now());
1090            if !rate.available(self.limit, class) {
1091                drop(rate);
1092                self.release_capacity(bytes, class);
1093                return Err(BudgetDimension::Rate);
1094            }
1095            rate.consume(self.limit, class);
1096        }
1097
1098        Ok(())
1099    }
1100
1101    /// Returns what a permit held at this node.
1102    fn release_held(&self, bytes: usize, class: BudgetClass) {
1103        self.release_capacity(bytes, class);
1104    }
1105
1106    /// Returns reserved count and bytes; data counters too for a data reservation.
1107    fn release_capacity(&self, bytes: usize, class: BudgetClass) {
1108        if !self.counted {
1109            return;
1110        }
1111        if class == BudgetClass::Data {
1112            self.data.release(1, bytes);
1113        }
1114        self.total.release(1, bytes);
1115    }
1116
1117    /// Moves a held data reservation to the control class: count and bytes stay held in total.
1118    fn release_data_class(&self, bytes: usize) {
1119        if self.counted {
1120            self.data.release(1, bytes);
1121        }
1122    }
1123
1124    fn permanent_exhaustion_dimension(&self, bytes: usize, class: BudgetClass) -> Option<BudgetDimension> {
1125        let limit = match class {
1126            BudgetClass::Data => self.data_limit,
1127            BudgetClass::Control => self.total_limit,
1128        };
1129        if limit.count == 0 {
1130            Some(BudgetDimension::Count)
1131        } else if packed_field(bytes) > limit.bytes {
1132            Some(BudgetDimension::Bytes)
1133        } else {
1134            None
1135        }
1136    }
1137
1138    fn record_rejection(&self, reason: BudgetRejectionReason) {
1139        self.counters.rejected.fetch_add(1, Ordering::Relaxed);
1140        if reason == BudgetRejectionReason::Capacity(BudgetDimension::Rate) {
1141            self.counters.throttled.fetch_add(1, Ordering::Relaxed);
1142        }
1143    }
1144
1145    fn record_dropped(&self, count: usize) {
1146        self.counters.dropped.fetch_add(count as u64, Ordering::Relaxed);
1147    }
1148
1149    fn record_coalesced(&self, count: usize) {
1150        self.counters.coalesced.fetch_add(count as u64, Ordering::Relaxed);
1151    }
1152
1153    fn record_slow_consumer_closed(&self) {
1154        self.counters.closed_slow_consumer.fetch_add(1, Ordering::Relaxed);
1155    }
1156
1157    /// Reads each counter atomically; the fields are not one consistent cut.
1158    ///
1159    /// The released count is the admitted count minus the count held now, so it is exact
1160    /// whenever no acquisition or release is in progress at this node.
1161    fn snapshot(&self) -> BudgetSnapshot {
1162        let (current_count, current_bytes) = self.total.load();
1163        let admitted_count = self.counters.admitted.load(Ordering::Acquire);
1164        BudgetSnapshot {
1165            path: Arc::clone(&self.path),
1166            current_count,
1167            current_bytes,
1168            admitted_count,
1169            released_count: admitted_count.saturating_sub(current_count as u64),
1170            rejected_count: self.counters.rejected.load(Ordering::Relaxed),
1171            throttled_count: self.counters.throttled.load(Ordering::Relaxed),
1172            dropped_count: self.counters.dropped.load(Ordering::Relaxed),
1173            coalesced_count: self.counters.coalesced.load(Ordering::Relaxed),
1174            closed_slow_consumer_count: self.counters.closed_slow_consumer.load(Ordering::Relaxed),
1175        }
1176    }
1177}
1178
1179/// Reservations taken on a run of nodes for one acquisition or rebind, rolled back unless
1180/// they are committed to a permit.
1181struct PendingReservations<'a> {
1182    nodes: &'a [Arc<BudgetNode>],
1183    reserved: usize,
1184    bytes: usize,
1185    class: BudgetClass,
1186}
1187
1188impl<'a> PendingReservations<'a> {
1189    fn new(nodes: &'a [Arc<BudgetNode>], bytes: usize, class: BudgetClass) -> Self {
1190        Self {
1191            nodes,
1192            reserved: 0,
1193            bytes,
1194            class,
1195        }
1196    }
1197
1198    /// Reserves at every node in order, and reports the first node that has no capacity.
1199    fn reserve_all(&mut self) -> Result<(), (&'a Arc<BudgetNode>, BudgetDimension)> {
1200        let nodes = self.nodes;
1201        for node in nodes {
1202            node.try_reserve(self.bytes, self.class)
1203                .map_err(|dimension| (node, dimension))?;
1204            self.reserved += 1;
1205        }
1206        Ok(())
1207    }
1208
1209    /// Counts the admissions; the caller's permit owns the reservations from now on.
1210    fn commit(mut self) {
1211        for node in &self.nodes[..self.reserved] {
1212            if node.counted {
1213                node.counters.admitted.fetch_add(1, Ordering::Relaxed);
1214            }
1215        }
1216        self.reserved = 0;
1217    }
1218}
1219
1220impl Drop for PendingReservations<'_> {
1221    fn drop(&mut self) {
1222        for node in &self.nodes[..self.reserved] {
1223            node.release_capacity(self.bytes, self.class);
1224            if let Some(rate) = &node.rate {
1225                // A rolled-back reservation returns the rate token it consumed.
1226                BudgetNode::lock_rate(rate).restore(node.limit, self.class);
1227            }
1228        }
1229    }
1230}
1231
1232/// Token buckets of a rate-limited node.
1233struct RateState {
1234    total_tokens: Option<TokenBucket>,
1235    data_tokens: Option<TokenBucket>,
1236}
1237
1238impl RateState {
1239    fn new(limit: BudgetLimit, now: Duration) -> Self {
1240        Self {
1241            total_tokens: limit.capacity.rate.map(|rate| TokenBucket::new(rate, now)),
1242            data_tokens: data_rate_limit(limit).map(|rate| TokenBucket::new(rate, now)),
1243        }
1244    }
1245
1246    fn refill(&mut self, limit: BudgetLimit, now: Duration) {
1247        if let (Some(bucket), Some(rate)) = (&mut self.total_tokens, limit.capacity.rate) {
1248            bucket.refill(rate, now);
1249        }
1250        if let (Some(bucket), Some(rate)) = (&mut self.data_tokens, data_rate_limit(limit)) {
1251            bucket.refill(rate, now);
1252        }
1253    }
1254
1255    fn available(&self, limit: BudgetLimit, class: BudgetClass) -> bool {
1256        let total_available = self.total_tokens.as_ref().is_none_or(TokenBucket::has_token);
1257        let data_available = class == BudgetClass::Control
1258            || data_rate_limit(limit).is_none()
1259            || self.data_tokens.as_ref().is_some_and(TokenBucket::has_token);
1260        total_available && data_available
1261    }
1262
1263    fn consume(&mut self, limit: BudgetLimit, class: BudgetClass) {
1264        if let Some(bucket) = &mut self.total_tokens {
1265            bucket.consume();
1266        }
1267        if class == BudgetClass::Data && data_rate_limit(limit).is_some() {
1268            if let Some(bucket) = &mut self.data_tokens {
1269                bucket.consume();
1270            }
1271        }
1272    }
1273
1274    fn restore(&mut self, limit: BudgetLimit, class: BudgetClass) {
1275        if let (Some(bucket), Some(rate)) = (&mut self.total_tokens, limit.capacity.rate) {
1276            bucket.restore(rate);
1277        }
1278        if class == BudgetClass::Data {
1279            self.restore_data(limit);
1280        }
1281    }
1282
1283    fn restore_data(&mut self, limit: BudgetLimit) {
1284        if let (Some(bucket), Some(rate)) = (&mut self.data_tokens, data_rate_limit(limit)) {
1285            bucket.restore(rate);
1286        }
1287    }
1288}
1289
1290fn data_rate_limit(limit: BudgetLimit) -> Option<RateLimit> {
1291    let total = limit.capacity.rate?;
1292    let reserve = limit.control_reserve.rate.unwrap_or(RateLimit::new(0, 0));
1293    Some(RateLimit::new(
1294        total.permits_per_second.saturating_sub(reserve.permits_per_second),
1295        total.burst.saturating_sub(reserve.burst),
1296    ))
1297}
1298
1299struct TokenBucket {
1300    tokens: f64,
1301    last_refill: Duration,
1302}
1303
1304impl TokenBucket {
1305    fn new(rate: RateLimit, now: Duration) -> Self {
1306        Self {
1307            tokens: rate.burst as f64,
1308            last_refill: now,
1309        }
1310    }
1311
1312    fn refill(&mut self, rate: RateLimit, now: Duration) {
1313        let elapsed = now.saturating_sub(self.last_refill).as_secs_f64();
1314        self.tokens = (self.tokens + elapsed * rate.permits_per_second as f64).min(rate.burst as f64);
1315        self.last_refill = now;
1316    }
1317
1318    fn has_token(&self) -> bool {
1319        self.tokens >= 1.0
1320    }
1321
1322    fn consume(&mut self) {
1323        self.tokens = (self.tokens - 1.0).max(0.0);
1324    }
1325
1326    fn restore(&mut self, rate: RateLimit) {
1327        self.tokens = (self.tokens + 1.0).min(rate.burst as f64);
1328    }
1329}