Skip to main content

uqa_sql/ir/
retained.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Immutable evaluated constants share storage without retaining every decoded payload.
8
9pub(crate) mod observation;
10
11use std::{fmt, sync::Arc};
12
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14use uqa_core::memory::{Produced, ProductionControl};
15use uqa_core::Value;
16
17use crate::{ast::ColumnType, SQLError};
18
19/// Storage for an already evaluated value. Reading must reproduce the original value without invoking SQL or changing it; implementations own their resource until the final shared handle is dropped.
20pub trait ConstantValueSource: fmt::Debug + Send + Sync {
21    fn read(&self, index: u64) -> Result<Value, SQLError>;
22
23    /// Borrow a resident immutable value when its owner exposes one. This never reads or decodes a spill record.
24    fn resident_value(&self, _index: u64) -> Option<&Value> {
25        None
26    }
27
28    /// External providers retain their completed output at this boundary. Built-in storage overrides this method to admit decoding before allocation.
29    fn read_with_control(
30        &self,
31        index: u64,
32        control: &ProductionControl<'_>,
33    ) -> Result<Produced<Value>, SQLError> {
34        control.check()?;
35        match self.resident_value(index) {
36            Some(value) => control.copy_value(value).map_err(Into::into),
37            None => control
38                .retain_external_value(self.read(index)?)
39                .map_err(Into::into),
40        }
41    }
42
43    /// Observe resident owner storage without decoding a constant or touching its spill files. External providers may have no exposed allocation observation.
44    fn observe_allocations<'a>(
45        &'a self,
46        _observer: &mut uqa_core::memory::AllocationObserver<'a, '_>,
47    ) -> Result<(), uqa_core::ValueRetentionError> {
48        Ok(())
49    }
50}
51
52/// An immutable positional value in a shared owner. Copying this handle never reads or copies the payload.
53#[derive(Clone)]
54pub struct RetainedConstantValue {
55    source: Arc<dyn ConstantValueSource>,
56    index: u64,
57}
58
59impl RetainedConstantValue {
60    pub fn new(source: Arc<dyn ConstantValueSource>, index: u64) -> Self {
61        Self { source, index }
62    }
63
64    /// Compare immutable source identity without decoding either value.
65    pub fn shares_value_with(&self, other: &Self) -> bool {
66        Arc::ptr_eq(&self.source, &other.source) && self.index == other.index
67    }
68
69    pub fn read(&self) -> Result<Value, SQLError> {
70        crate::expr::check_statement_cancellation()?;
71        let value = self.source.read(self.index)?;
72        crate::expr::check_statement_cancellation()?;
73        Ok(value)
74    }
75
76    /// Move an evaluated value into its immutable shared owner without copying it or dropping its constructor lease.
77    pub fn from_produced(
78        value: Produced<Value>,
79        control: &ProductionControl<'_>,
80    ) -> Result<Self, SQLError> {
81        Ok(Self::new(value.into_shared(control)?, 0))
82    }
83
84    pub fn resident_value(&self) -> Option<&Value> {
85        self.source.resident_value(self.index)
86    }
87
88    pub fn read_with_control(
89        &self,
90        control: &ProductionControl<'_>,
91    ) -> Result<Produced<Value>, SQLError> {
92        crate::expr::check_statement_cancellation()?;
93        control.check()?;
94        let value = self.source.read_with_control(self.index, control)?;
95        crate::expr::check_statement_cancellation()?;
96        control.check()?;
97        Ok(value)
98    }
99}
100
101impl fmt::Debug for RetainedConstantValue {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.debug_struct("RetainedConstantValue")
104            .field("index", &self.index)
105            .finish_non_exhaustive()
106    }
107}
108
109impl PartialEq for RetainedConstantValue {
110    fn eq(&self, other: &Self) -> bool {
111        if self.shares_value_with(other) {
112            return true;
113        }
114        if let (Some(left), Some(right)) = (self.resident_value(), other.resident_value()) {
115            return left.has_same_representation(right);
116        }
117        // IR representation comparison may conservatively decline a rewrite when a resource cannot be read. SQL evaluation retains the original fallible read and reports its error.
118        match (self.read(), other.read()) {
119            (Ok(left), Ok(right)) => left.has_same_representation(&right),
120            _ => false,
121        }
122    }
123}
124
125impl Serialize for RetainedConstantValue {
126    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
127        self.read()
128            .map_err(serde::ser::Error::custom)?
129            .serialize(serializer)
130    }
131}
132
133impl<'de> Deserialize<'de> for RetainedConstantValue {
134    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
135        let value = Value::deserialize(deserializer)?;
136        Ok(Self::new(Arc::new(OwnedConstant(value)), 0))
137    }
138}
139
140#[derive(Debug)]
141struct OwnedConstant(Value);
142
143impl ConstantValueSource for OwnedConstant {
144    fn resident_value(&self, index: u64) -> Option<&Value> {
145        (index == 0).then_some(&self.0)
146    }
147    fn observe_allocations<'a>(
148        &'a self,
149        observer: &mut uqa_core::memory::AllocationObserver<'a, '_>,
150    ) -> Result<(), uqa_core::ValueRetentionError> {
151        observer.allocation(size_of::<Self>(), size_of::<Self>())?;
152        observer.child(&self.0)
153    }
154
155    fn read(&self, index: u64) -> Result<Value, SQLError> {
156        if index != 0 {
157            return Err(SQLError::Internal(
158                "retained constant index is outside its owner".into(),
159            ));
160        }
161        Ok(self.0.clone())
162    }
163}
164
165impl ConstantValueSource for Produced<Value> {
166    fn resident_value(&self, index: u64) -> Option<&Value> {
167        (index == 0).then_some(self)
168    }
169
170    fn read(&self, index: u64) -> Result<Value, SQLError> {
171        self.resident_value(index).cloned().ok_or_else(|| {
172            SQLError::Internal("retained constant index is outside its owner".into())
173        })
174    }
175
176    fn observe_allocations<'a>(
177        &'a self,
178        observer: &mut uqa_core::memory::AllocationObserver<'a, '_>,
179    ) -> Result<(), uqa_core::ValueRetentionError> {
180        observer.allocation(size_of::<Self>(), size_of::<Self>())?;
181        observer.child(&**self)
182    }
183}
184
185impl uqa_core::memory::ObserveAllocations for RetainedConstantValue {
186    fn observe_allocations<'a>(
187        &'a self,
188        observer: &mut uqa_core::memory::AllocationObserver<'a, '_>,
189    ) -> Result<(), uqa_core::ValueRetentionError> {
190        if observer.shared_owner(self.source.as_ref())? {
191            self.source.observe_allocations(observer)?;
192        }
193        Ok(())
194    }
195}
196
197/// Selected result metadata shared with an already evaluated datum. Plan copies never duplicate its allocation or change its constructor lease.
198#[derive(Debug, Clone, PartialEq)]
199pub struct RetainedScalarLiteral(Arc<Produced<RetainedLiteralData>>);
200
201#[derive(Debug, PartialEq)]
202pub struct RetainedLiteralData {
203    pub value: RetainedConstantValue,
204    pub ty: Option<ColumnType>,
205    pub declaration: Option<String>,
206    pub collation_oid: Option<u32>,
207}
208
209impl std::ops::Deref for RetainedScalarLiteral {
210    type Target = RetainedLiteralData;
211    fn deref(&self) -> &Self::Target {
212        &self.0
213    }
214}
215
216impl Serialize for RetainedScalarLiteral {
217    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
218        self.materialize()
219            .map_err(serde::ser::Error::custom)?
220            .serialize(serializer)
221    }
222}
223
224impl RetainedScalarLiteral {
225    pub fn new(
226        value: RetainedConstantValue,
227        ty: Option<ColumnType>,
228        declaration: Option<String>,
229        collation_oid: Option<u32>,
230    ) -> Self {
231        let control = ProductionControl::uncontrolled();
232        Self(
233            control
234                .finish(
235                    RetainedLiteralData {
236                        value,
237                        ty,
238                        declaration,
239                        collation_oid,
240                    },
241                    None,
242                )
243                .expect("ordinary constant metadata")
244                .into_shared(&control)
245                .expect("ordinary shared constant metadata"),
246        )
247    }
248
249    /// The value source retains its own storage lease. Metadata constructors supply their existing leases and this owner admits the shared header before allocation.
250    pub fn with_control(
251        value: RetainedConstantValue,
252        ty: Option<Produced<ColumnType>>,
253        declaration: Option<Produced<String>>,
254        collation_oid: Option<u32>,
255        control: &ProductionControl<'_>,
256    ) -> Result<Self, SQLError> {
257        let (ty, ty_memory) = match ty {
258            Some(ty) => {
259                let (ty, memory) = ty.into_parts();
260                (Some(ty), memory)
261            }
262            None => (None, control.empty_reservation()),
263        };
264        let (declaration, declaration_memory) = match declaration {
265            Some(name) => {
266                let (name, memory) = name.into_parts();
267                (Some(name), memory)
268            }
269            None => (None, control.empty_reservation()),
270        };
271        let data = RetainedLiteralData {
272            value,
273            ty,
274            declaration,
275            collation_oid,
276        };
277        Ok(Self(
278            control
279                .finish(data, control.combine(ty_memory, declaration_memory))?
280                .into_shared(control)?,
281        ))
282    }
283
284    /// Materialize one value only at an interface that requires an owned literal. Cloning plans retains the shared owner instead.
285    pub fn materialize(&self) -> Result<crate::ScalarExpr, SQLError> {
286        let value = self.value.read()?;
287        let Some(declaration) = &self.declaration else {
288            return Ok(crate::ScalarExpr::Literal(value));
289        };
290        Ok(crate::ScalarExpr::TypedLiteral {
291            value,
292            ty: declaration.clone(),
293            bound_type: self.ty.clone(),
294            parameter_index: None,
295            composite_source: None,
296            collation_oid: self.collation_oid,
297        })
298    }
299}
300
301impl uqa_core::memory::ObserveAllocations for RetainedScalarLiteral {
302    fn observe_allocations<'a>(
303        &'a self,
304        observer: &mut uqa_core::memory::AllocationObserver<'a, '_>,
305    ) -> Result<(), uqa_core::ValueRetentionError> {
306        if observer.shared_owner(self.0.as_ref())? {
307            observer.allocation(
308                size_of::<Produced<RetainedLiteralData>>(),
309                size_of::<Produced<RetainedLiteralData>>(),
310            )?;
311            observer.child(&self.value)?;
312            observer.child(&self.ty)?;
313            observer.child(&self.declaration)?;
314        }
315        Ok(())
316    }
317}
318
319/// Planner supplies a successfully evaluated constant; execution supplies its bounded storage implementation.
320pub trait ConstantValueStorage: fmt::Debug + Send + Sync {
321    fn retain(&self, value: Value) -> Result<RetainedConstantValue, SQLError>;
322
323    /// Transfer an evaluated owner through the storage boundary. Native stores override this callback to admit encoding workspace and enforce cancellation inside atomic publication; the default adapts an external storage implementation.
324    fn retain_produced(
325        &self,
326        value: Produced<Value>,
327        control: &ProductionControl<'_>,
328    ) -> Result<RetainedConstantValue, SQLError> {
329        control.check()?;
330        let (value, memory) = value.into_parts();
331        let retained = self.retain(value);
332        drop(memory);
333        retained
334    }
335}
336
337#[cfg(test)]
338mod tests;