Skip to main content

reddb_engine/query/unified/
memory.rs

1//! Retained result capacity, including spare slots and nested model payloads.
2//! Shared values are charged per result owner, independently of Arc counts.
3use super::*;
4use std::alloc::Layout;
5use std::mem::size_of;
6
7impl UnifiedRecord {
8    /// Conservative retained heap estimate, charging the schema to this owner.
9    pub fn retained_heap_bytes(&self) -> usize {
10        record_heap_bytes(self).saturating_add(schema_bytes(&self.schema))
11    }
12}
13
14impl UnifiedResult {
15    /// Conservative retained heap estimate without allocating scratch. This is
16    /// admission for a completed result, not accounting for executor workspaces.
17    pub fn retained_memory_bytes(&self) -> usize {
18        let mut bytes = vector_slots(&self.columns)
19            .saturating_add(
20                self.columns
21                    .iter()
22                    .map(String::capacity)
23                    .fold(0, usize::saturating_add),
24            )
25            .saturating_add(vector_slots(&self.records))
26            .saturating_add(
27                self.pre_serialized_json
28                    .as_ref()
29                    .map_or(0, String::capacity),
30            );
31        let first_schema = self.records.first().map(|record| &record.schema);
32        for (index, record) in self.records.iter().enumerate() {
33            bytes = bytes.saturating_add(record_heap_bytes(record));
34            // The common shared schema is counted once, with no HashSet or
35            // per-row scratch. Other schemas are conservatively charged per row.
36            if index == 0 || first_schema.is_none_or(|schema| !Arc::ptr_eq(schema, &record.schema))
37            {
38                bytes = bytes.saturating_add(schema_bytes(&record.schema));
39            }
40        }
41        if let Some(stats) = &self.stats.vector {
42            bytes = bytes
43                .saturating_add(vector_slots(&stats.operators))
44                .saturating_add(
45                    stats
46                        .operators
47                        .iter()
48                        .map(|operator| operator.operator.capacity())
49                        .fold(0, usize::saturating_add),
50                )
51                .saturating_add(stats.mode_requested.capacity())
52                .saturating_add(stats.mode_executed.capacity())
53                .saturating_add(stats.access_path.capacity())
54                .saturating_add(stats.fallback_reason.as_ref().map_or(0, String::capacity));
55        }
56        bytes
57    }
58}
59
60fn vector_slots<T>(values: &Vec<T>) -> usize {
61    values.capacity().saturating_mul(size_of::<T>())
62}
63
64fn arc_text_bytes(value: &Arc<str>) -> usize {
65    Layout::array::<u8>(value.len())
66        .map(arc_allocation_bytes)
67        .unwrap_or(usize::MAX)
68}
69
70fn arc_allocation_bytes(payload: Layout) -> usize {
71    // Arc's strong/weak counters precede its payload. Include the trailing
72    // alignment: e.g. one UTF-8 byte requests 24 bytes on a 64-bit host, not 17.
73    Layout::new::<[usize; 2]>()
74        .extend(payload)
75        .map(|(layout, _)| layout.pad_to_align().size())
76        .unwrap_or(usize::MAX)
77}
78
79fn schema_bytes(schema: &Arc<Vec<Arc<str>>>) -> usize {
80    arc_allocation_bytes(Layout::new::<Vec<Arc<str>>>())
81        .saturating_add(vector_slots(schema))
82        .saturating_add(
83            schema
84                .iter()
85                .map(arc_text_bytes)
86                .fold(0, usize::saturating_add),
87        )
88}
89
90fn map_bytes<K, V>(map: &HashMap<K, V>, mut payload: impl FnMut(&K, &V) -> usize) -> usize {
91    // Capacity is the usable entry count, not the raw bucket count. Twice the
92    // usable slots plus control/alignment space conservatively covers sparse
93    // SwissTable allocations, including the smallest nonempty table.
94    let slots = if map.capacity() == 0 {
95        0
96    } else {
97        map.capacity()
98            .saturating_mul(2)
99            .saturating_mul(size_of::<(K, V)>().saturating_add(1))
100            .saturating_add(64)
101    };
102    map.iter().fold(slots, |bytes, (key, value)| {
103        bytes.saturating_add(payload(key, value))
104    })
105}
106
107fn properties_bytes(properties: &HashMap<String, Value>) -> usize {
108    map_bytes(properties, |key, value| {
109        key.capacity().saturating_add(value_heap_bytes(value))
110    })
111}
112
113fn edge_heap_bytes(edge: &MatchedEdge) -> usize {
114    edge.from
115        .capacity()
116        .saturating_add(edge.to.capacity())
117        .saturating_add(edge.edge_label.capacity())
118        .saturating_add(properties_bytes(&edge.properties))
119}
120
121fn record_heap_bytes(record: &UnifiedRecord) -> usize {
122    let mut bytes = vector_slots(&record.values).saturating_add(
123        record
124            .values
125            .iter()
126            .map(value_heap_bytes)
127            .fold(0, usize::saturating_add),
128    );
129    if let Some(overflow) = &record.overflow {
130        bytes = bytes.saturating_add(map_bytes(overflow, |key, value| {
131            arc_text_bytes(key).saturating_add(value_heap_bytes(value))
132        }));
133    }
134    bytes = bytes
135        .saturating_add(map_bytes(&record.nodes, |key, node| {
136            key.capacity()
137                .saturating_add(node.id.capacity())
138                .saturating_add(node.label.capacity())
139                .saturating_add(node.node_label.capacity())
140                .saturating_add(properties_bytes(&node.properties))
141        }))
142        .saturating_add(map_bytes(&record.edges, |key, edge| {
143            key.capacity().saturating_add(edge_heap_bytes(edge))
144        }))
145        .saturating_add(vector_slots(&record.paths))
146        .saturating_add(vector_slots(&record.vector_results));
147    for path in &record.paths {
148        bytes = bytes
149            .saturating_add(vector_slots(&path.nodes))
150            .saturating_add(
151                path.nodes
152                    .iter()
153                    .map(String::capacity)
154                    .fold(0, usize::saturating_add),
155            )
156            .saturating_add(vector_slots(&path.edges))
157            .saturating_add(
158                path.edges
159                    .iter()
160                    .map(edge_heap_bytes)
161                    .fold(0, usize::saturating_add),
162            );
163    }
164    for vector in &record.vector_results {
165        bytes = bytes
166            .saturating_add(vector.collection.capacity())
167            .saturating_add(vector.vector.as_ref().map_or(0, vector_slots))
168            .saturating_add(vector.metadata.as_ref().map_or(0, properties_bytes))
169            .saturating_add(vector.linked_node.as_ref().map_or(0, String::capacity))
170            .saturating_add(
171                vector
172                    .linked_row
173                    .as_ref()
174                    .map_or(0, |(table, _)| table.capacity()),
175            );
176    }
177    bytes
178}
179
180fn value_heap_bytes(value: &Value) -> usize {
181    // Bounded explicit stack: API-supplied values deeper than the parser's
182    // maximum cannot receive a representable retained-memory allowance.
183    const LEVELS: usize = reddb_rql::limits::JSON_LITERAL_MAX_DEPTH as usize + 1;
184    let mut stack: [std::slice::Iter<'_, Value>; LEVELS] = std::array::from_fn(|_| [].iter());
185    let mut depth = 0;
186    let mut current = Some(value);
187    let mut bytes = 0usize;
188    loop {
189        if let Some(value) = current.take() {
190            if let Value::Array(values) = value {
191                if depth == LEVELS {
192                    return usize::MAX;
193                }
194                bytes = bytes.saturating_add(vector_slots(values));
195                stack[depth] = values.iter();
196                depth += 1;
197            } else {
198                bytes = bytes.saturating_add(scalar_heap_bytes(value));
199            }
200        }
201        if depth == 0 {
202            return bytes;
203        }
204        current = stack[depth - 1].next();
205        if current.is_none() {
206            depth -= 1;
207        }
208    }
209}
210
211fn scalar_heap_bytes(value: &Value) -> usize {
212    match value {
213        Value::Text(value) => arc_text_bytes(value),
214        Value::Blob(value) | Value::Json(value) | Value::Secret(value) => value.capacity(),
215        Value::Vector(value) => vector_slots(value),
216        Value::NodeRef(value)
217        | Value::EdgeRef(value)
218        | Value::VectorRef(value, _)
219        | Value::RowRef(value, _)
220        | Value::DocRef(value, _)
221        | Value::TableRef(value)
222        | Value::Email(value)
223        | Value::Url(value)
224        | Value::Password(value)
225        | Value::DecimalText(value)
226        | Value::AssetCode(value) => value.capacity(),
227        Value::KeyRef(collection, key) => collection.capacity().saturating_add(key.capacity()),
228        Value::Money { asset_code, .. } => asset_code.capacity(),
229        Value::Array(_) => unreachable!("arrays use the bounded stack"),
230        Value::Null
231        | Value::Integer(_)
232        | Value::UnsignedInteger(_)
233        | Value::Float(_)
234        | Value::Boolean(_)
235        | Value::Timestamp(_)
236        | Value::Duration(_)
237        | Value::IpAddr(_)
238        | Value::MacAddr(_)
239        | Value::Uuid(_)
240        | Value::Color(_)
241        | Value::Phone(_)
242        | Value::Semver(_)
243        | Value::Cidr(_, _)
244        | Value::Date(_)
245        | Value::Time(_)
246        | Value::Decimal(_)
247        | Value::EnumValue(_)
248        | Value::TimestampMs(_)
249        | Value::Ipv4(_)
250        | Value::Ipv6(_)
251        | Value::Subnet(_, _)
252        | Value::Port(_)
253        | Value::Latitude(_)
254        | Value::Longitude(_)
255        | Value::GeoPoint(_, _)
256        | Value::Country2(_)
257        | Value::Country3(_)
258        | Value::Lang2(_)
259        | Value::Lang5(_)
260        | Value::Currency(_)
261        | Value::ColorAlpha(_)
262        | Value::BigInt(_)
263        | Value::PageRef(_)
264        | Value::Temperature(_) => 0,
265        Value::Cron(value) => {
266            std::mem::size_of::<reddb_types::CronSchedule>() + value.as_str().len()
267        }
268    }
269}