Skip to main content

uqa_sql/plan/
owned.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Immutable executable roots keep their constructors' reservations through query projection and sharing.
8
9use super::{QueryPlan, UnifiedPlan};
10use crate::SQLError;
11use std::sync::Arc;
12use uqa_core::memory::{MemoryReservation, Produced, ProductionControl};
13
14/// An executable and the reservations transferred by its allocation owners. Moving an existing input into this owner performs no allocation and does not retroactively charge that input. Native producers must admit their new allocations before transferring them. The tree is read-only after publication; preparation that constructs additional storage must retain its output reservations too.
15#[derive(Debug)]
16pub struct OwnedExecutablePlan {
17    plan: UnifiedPlan,
18    // Drop the complete tree before releasing its constructor reservations.
19    memory: ExecutableMemory,
20}
21
22/// A relational executable projected from its statement owner. Retaining the original root box avoids copying its payload or releasing a charged box while its reservation is still attached to the query.
23#[derive(Debug)]
24pub struct OwnedQueryPlan {
25    query: Box<QueryPlan>,
26    memory: ExecutableMemory,
27}
28
29/// Shared immutable execution storage. Keeping the Arc private prevents unwrapping its payload while leaving the shared allocation's reservation attached to an unboxed value.
30#[derive(Debug, Clone)]
31pub struct SharedExecutablePlan(SharedStorage);
32
33#[derive(Debug, Clone)]
34enum SharedStorage {
35    Ordinary(Arc<UnifiedPlan>),
36    Admitted(Arc<OwnedExecutablePlan>),
37}
38
39/// Allocation leases transferred with an executable. The root box is kept separate so projecting an unboxed query releases exactly that allocation, while attached child roots become ordinary tree storage.
40#[derive(Debug, Default)]
41pub struct ExecutableMemory {
42    storage: Option<MemoryReservation>,
43    root: Option<MemoryReservation>,
44}
45
46impl From<Option<MemoryReservation>> for ExecutableMemory {
47    fn from(storage: Option<MemoryReservation>) -> Self {
48        Self {
49            storage,
50            root: None,
51        }
52    }
53}
54
55impl ExecutableMemory {
56    pub fn reserved_bytes(&self) -> usize {
57        self.storage.as_ref().map_or(0, MemoryReservation::bytes)
58            + self.root.as_ref().map_or(0, MemoryReservation::bytes)
59    }
60
61    /// A newly attached executable retains its complete allocation ownership in its enclosing tree.
62    pub fn absorb(&mut self, child: Self) {
63        self.absorb_storage(child.storage);
64        self.absorb_storage(child.root);
65    }
66
67    fn absorb_storage(&mut self, memory: Option<MemoryReservation>) {
68        if let Some(memory) = memory {
69            if let Some(storage) = &mut self.storage {
70                storage.absorb(memory);
71            } else {
72                self.storage = Some(memory);
73            }
74        }
75    }
76}
77
78impl OwnedExecutablePlan {
79    /// Transfer existing storage and the reservations already acquired by its constructors. This is an ownership transfer, not an admission operation.
80    pub fn from_parts(plan: UnifiedPlan, memory: impl Into<ExecutableMemory>) -> Self {
81        Self {
82            plan,
83            memory: memory.into(),
84        }
85    }
86
87    pub fn reserved_bytes(&self) -> usize {
88        self.memory.reserved_bytes()
89    }
90
91    /// Transfer the tree and its leases together to a specialized owning operation. That operation must keep them alive until their corresponding storage is destroyed or transferred; it must admit any new allocation before construction.
92    pub fn into_parts(self) -> (UnifiedPlan, ExecutableMemory) {
93        (self.plan, self.memory)
94    }
95
96    /// Project a query without unboxing, copying or changing any reservation. A command is returned intact to its caller.
97    pub fn into_query(self) -> Result<OwnedQueryPlan, Self> {
98        let UnifiedPlan::Query(query) = self.plan else {
99            return Err(self);
100        };
101        Ok(OwnedQueryPlan {
102            query,
103            memory: self.memory,
104        })
105    }
106
107    /// Admit only the new shared payload; all existing tree allocations retain their original leases. Cloning the returned handle does not allocate or copy the executable.
108    pub fn into_shared(
109        mut self,
110        control: &ProductionControl<'_>,
111    ) -> Result<SharedExecutablePlan, SQLError> {
112        for memory in [&self.memory.storage, &self.memory.root]
113            .into_iter()
114            .flatten()
115        {
116            assert!(
117                control
118                    .budget()
119                    .is_some_and(|budget| budget.shares_allowance(memory.budget())),
120                "executable sharing preserves its constructor allowance"
121            );
122        }
123        let wrapper = control.reserve(size_of::<Self>())?;
124        self.memory.absorb_storage(wrapper);
125        Ok(SharedExecutablePlan(SharedStorage::Admitted(Arc::new(
126            self,
127        ))))
128    }
129}
130
131impl From<UnifiedPlan> for OwnedExecutablePlan {
132    fn from(plan: UnifiedPlan) -> Self {
133        Self::from_parts(plan, None)
134    }
135}
136
137impl From<Produced<UnifiedPlan>> for OwnedExecutablePlan {
138    fn from(plan: Produced<UnifiedPlan>) -> Self {
139        let (plan, mut memory) = plan.into_parts();
140        let root_bytes = match &plan {
141            UnifiedPlan::Query(_) => size_of::<QueryPlan>(),
142            UnifiedPlan::Command(_) => size_of::<super::CommandPlan>(),
143        };
144        let root = memory.as_mut().map(|memory| memory.split(root_bytes));
145        Self::from_parts(
146            plan,
147            ExecutableMemory {
148                storage: memory,
149                root,
150            },
151        )
152    }
153}
154
155impl AsRef<UnifiedPlan> for OwnedExecutablePlan {
156    fn as_ref(&self) -> &UnifiedPlan {
157        &self.plan
158    }
159}
160
161impl std::ops::Deref for OwnedExecutablePlan {
162    type Target = UnifiedPlan;
163
164    fn deref(&self) -> &Self::Target {
165        self.as_ref()
166    }
167}
168
169impl OwnedQueryPlan {
170    /// Admit the enclosing box for an existing query without retroactively charging its payload.
171    pub fn from_query(query: QueryPlan, control: &ProductionControl<'_>) -> Result<Self, SQLError> {
172        let root = control.reserve(size_of::<QueryPlan>())?;
173        Ok(Self {
174            query: Box::new(query),
175            memory: ExecutableMemory {
176                storage: control.empty_reservation(),
177                root,
178            },
179        })
180    }
181
182    /// Preserve an admitted query body and admit its enclosing box before allocating it.
183    pub fn from_produced(
184        query: Produced<QueryPlan>,
185        control: &ProductionControl<'_>,
186    ) -> Result<Self, SQLError> {
187        let root = control.reserve(size_of::<QueryPlan>())?;
188        let (query, memory) = query.into_parts();
189        // Validate the original and destination allowance without merging the separately owned box.
190        let memory = control.combine(memory, control.empty_reservation());
191        Ok(Self {
192            query: Box::new(query),
193            memory: ExecutableMemory {
194                storage: memory,
195                root,
196            },
197        })
198    }
199
200    /// Transfer an existing root box together with its constructor reservations.
201    pub fn from_parts(query: Box<QueryPlan>, memory: impl Into<ExecutableMemory>) -> Self {
202        Self {
203            query,
204            memory: memory.into(),
205        }
206    }
207
208    pub fn reserved_bytes(&self) -> usize {
209        self.memory.reserved_bytes()
210    }
211
212    /// Specialized query preparation must keep this pair together and admit its additional source attachments before construction.
213    pub fn into_parts(self) -> (Box<QueryPlan>, ExecutableMemory) {
214        (self.query, self.memory)
215    }
216
217    /// Move the query into an enclosing owner whose representation has no root box. Release that box's own lease only after freeing it; the caller must retain the returned storage leases with the query.
218    pub fn into_unboxed(self) -> (QueryPlan, ExecutableMemory) {
219        let query = *self.query;
220        drop(self.memory.root);
221        (
222            query,
223            ExecutableMemory {
224                storage: self.memory.storage,
225                root: None,
226            },
227        )
228    }
229
230    /// Transfer the existing root allocation and all of its original leases into an enclosing SQL constructor, without copying or reallocating the box.
231    pub(in crate::plan) fn into_produced_box(
232        self,
233        control: &ProductionControl<'_>,
234    ) -> Result<Produced<Box<QueryPlan>>, SQLError> {
235        Ok(control.finish(
236            self.query,
237            control.combine(self.memory.storage, self.memory.root),
238        )?)
239    }
240
241    pub fn into_executable(self) -> OwnedExecutablePlan {
242        OwnedExecutablePlan::from_parts(UnifiedPlan::Query(self.query), self.memory)
243    }
244}
245
246impl AsRef<QueryPlan> for OwnedQueryPlan {
247    fn as_ref(&self) -> &QueryPlan {
248        &self.query
249    }
250}
251
252impl std::ops::Deref for OwnedQueryPlan {
253    type Target = QueryPlan;
254
255    fn deref(&self) -> &Self::Target {
256        self.as_ref()
257    }
258}
259
260impl SharedExecutablePlan {
261    pub fn strong_count(&self) -> usize {
262        match &self.0 {
263            SharedStorage::Ordinary(plan) => Arc::strong_count(plan),
264            SharedStorage::Admitted(plan) => Arc::strong_count(plan),
265        }
266    }
267
268    pub fn ptr_eq(&self, other: &Self) -> bool {
269        match (&self.0, &other.0) {
270            (SharedStorage::Ordinary(left), SharedStorage::Ordinary(right)) => {
271                Arc::ptr_eq(left, right)
272            }
273            (SharedStorage::Admitted(left), SharedStorage::Admitted(right)) => {
274                Arc::ptr_eq(left, right)
275            }
276            _ => false,
277        }
278    }
279
280    pub fn reserved_bytes(&self) -> usize {
281        match &self.0 {
282            SharedStorage::Ordinary(_) => 0,
283            SharedStorage::Admitted(plan) => plan.reserved_bytes(),
284        }
285    }
286}
287
288impl AsRef<UnifiedPlan> for SharedExecutablePlan {
289    fn as_ref(&self) -> &UnifiedPlan {
290        match &self.0 {
291            SharedStorage::Ordinary(plan) => plan,
292            SharedStorage::Admitted(plan) => plan,
293        }
294    }
295}
296
297impl std::ops::Deref for SharedExecutablePlan {
298    type Target = UnifiedPlan;
299
300    fn deref(&self) -> &Self::Target {
301        self.as_ref()
302    }
303}
304
305#[cfg(test)]
306mod tests;
307
308impl From<UnifiedPlan> for SharedExecutablePlan {
309    /// Share an ordinary input without claiming admission for allocations its constructors did not reserve.
310    fn from(plan: UnifiedPlan) -> Self {
311        Self(SharedStorage::Ordinary(Arc::new(plan)))
312    }
313}
314
315impl From<Arc<UnifiedPlan>> for SharedExecutablePlan {
316    fn from(plan: Arc<UnifiedPlan>) -> Self {
317        Self(SharedStorage::Ordinary(plan))
318    }
319}