Skip to main content

glory_render/memory/
submission.rs

1//! Bounded speculative host preparation. Only touched fields and moved/retired
2//! nodes are retained; no model/descriptor snapshot or application callback.
3use super::*;
4use std::ops::Range;
5
6const LIMIT: usize = 256;
7const NODE_LIMIT: usize = 4096;
8
9#[derive(Clone, Copy)]
10struct Link {
11    parent: Option<NodeId>,
12    next: Option<NodeId>,
13    placed: bool,
14    suspended: bool,
15}
16impl Link {
17    fn read(node: &Node) -> Self {
18        Self {
19            parent: node.parent,
20            next: node.next,
21            placed: node.placed,
22            suspended: node.suspended,
23        }
24    }
25    fn restore(self, tree: &mut Memory, id: NodeId) {
26        tree.unlink(id);
27        let node = tree.nodes.get_mut(&id).expect("submission node");
28        node.placed = false;
29        node.suspended = false;
30        node.parent = self.parent;
31        node.next = self.next;
32        if self.placed {
33            tree.place(id, self.parent, self.next, false)
34                .expect("previous placement");
35        }
36        tree.nodes.get_mut(&id).expect("submission node").suspended = self.suspended;
37    }
38}
39enum Undo {
40    Create(Range<usize>),
41    Patch {
42        id: NodeId,
43        inverse: Patch,
44        fields: u8,
45    },
46    Place(NodeId, Link),
47    Dispose {
48        root: NodeId,
49        link: Link,
50        nodes: Range<usize>,
51    },
52}
53struct Record {
54    undo: Undo,
55    receipt: Receipt,
56    stats: Stats,
57    weight: usize,
58}
59
60/// A finite preparation segment for stateless Plan construction/fields/retirement.
61/// Unsupported operations form a host barrier. Drop restores all unconfirmed
62/// operations; `finish` keeps exactly the successful semantic prefix.
63pub struct Submission<'a> {
64    tree: &'a mut Memory,
65    records: Vec<Record>,
66    created: Vec<(NodeId, Option<(u32, bool)>)>,
67    retired: Vec<(NodeId, Node)>,
68    weight: usize,
69}
70impl Memory {
71    pub fn submission(&mut self) -> Result<Submission<'_>, Error> {
72        if !self.inputs.is_empty() || self.layers != 0 || !self.focus_scopes.is_empty() {
73            return Err(Error::Unsupported(
74                "submission requires no pending reference input or scopes",
75            ));
76        }
77        Ok(Submission {
78            tree: self,
79            records: Vec::new(),
80            created: Vec::new(),
81            retired: Vec::new(),
82            weight: 0,
83        })
84    }
85}
86impl Submission<'_> {
87    pub fn tree(&self) -> &Memory {
88        self.tree
89    }
90    pub fn len(&self) -> usize {
91        self.records.len()
92    }
93    pub fn is_empty(&self) -> bool {
94        self.records.is_empty()
95    }
96    pub fn discard_last(&mut self) {
97        self.rollback(self.records.len().saturating_sub(1));
98    }
99    pub fn supports(&self, mutation: &Mutation) -> bool {
100        if self.records.len() == LIMIT || self.weight == NODE_LIMIT {
101            return false;
102        }
103        match mutation {
104            Mutation::CreatePlan { plan, .. } => {
105                plan.nodes().len() <= NODE_LIMIT - self.weight && plan.supports_submission()
106            }
107            Mutation::Patch { patch, .. } => {
108                matches!(patch, Patch::Text(_) | Patch::Label(_) | Patch::Classes(_))
109            }
110            Mutation::Place { .. } => true,
111            Mutation::Dispose { .. } => true,
112            _ => false,
113        }
114    }
115    /// The mapper lowers the prepared field while the canonical guard is borrowed.
116    pub fn patch<T>(
117        &mut self,
118        id: NodeId,
119        patch: &Patch,
120        lower: impl FnOnce(DescriptorView<'_>, &Patch) -> T,
121    ) -> Result<T, Error> {
122        if self.records.len() == LIMIT
123            || self.weight == NODE_LIMIT
124            || !matches!(patch, Patch::Text(_) | Patch::Label(_) | Patch::Classes(_))
125        {
126            return Err(Error::Unsupported("submission field"));
127        }
128        let receipt = self.tree.receipt;
129        let stats = self.tree.stats;
130        let mut prepared = self.tree.prepare_patch(id, patch)?;
131        let value = lower(prepared.descriptor(), prepared.previous());
132        // These three fields have no registry side effects in accept(). Move
133        // the already-owned inverse into the journal; never copy the old body.
134        let inverse = prepared.inverse.take().expect("prepared field inverse");
135        let fields = prepared.fields_before;
136        prepared.commit();
137        self.records.push(Record {
138            undo: Undo::Patch {
139                id,
140                inverse,
141                fields,
142            },
143            receipt,
144            stats,
145            weight: 1,
146        });
147        self.weight += 1;
148        Ok(value)
149    }
150    pub fn apply(&mut self, mutation: &Mutation) -> Result<Option<Vec<NodeId>>, Error> {
151        if !self.supports(mutation) {
152            return Err(Error::Unsupported("submission operation"));
153        }
154        let receipt = self.tree.receipt;
155        let stats = self.tree.stats;
156        let mut retired = None;
157        let mut weight = 1;
158        let undo = match mutation {
159            Mutation::CreatePlan { ids, .. } => {
160                weight = ids.len();
161                let first = self.created.len();
162                self.created.extend(
163                    ids.iter()
164                        .map(|id| (*id, self.tree.generations.get(&id.slot()).copied())),
165                );
166                if let Err(error) = self.tree.apply(std::slice::from_ref(mutation)) {
167                    self.created.truncate(first);
168                    return Err(error);
169                }
170                Undo::Create(first..self.created.len())
171            }
172            Mutation::Place { id, .. } => {
173                let link = Link::read(self.tree.node(*id)?);
174                self.tree.apply(std::slice::from_ref(mutation))?;
175                Undo::Place(*id, link)
176            }
177            Mutation::Dispose { id } => {
178                let link = Link::read(self.tree.node(*id)?);
179                let mut pending = vec![*id];
180                let mut ids = Vec::new();
181                while let Some(id) = pending.pop() {
182                    if ids.len() == NODE_LIMIT - self.weight {
183                        return Err(Error::Unsupported("submission node budget"));
184                    }
185                    let node = self.tree.node(id)?;
186                    if node.descriptor.view().semantics.is_some()
187                        || node.clipboard.is_some()
188                        || node.files.is_some()
189                        || node.swipe.is_some()
190                    {
191                        return Err(Error::Unsupported("submission retirement facets"));
192                    }
193                    ids.push(id);
194                    pending.extend(node.children.iter().copied());
195                }
196                self.tree.unlink(*id);
197                weight = ids.len();
198                let first = self.retired.len();
199                self.retired.reserve(ids.len());
200                for id in &ids {
201                    self.tree
202                        .generations
203                        .get_mut(&id.slot())
204                        .expect("live generation")
205                        .1 = false;
206                    self.retired
207                        .push((*id, self.tree.nodes.remove(id).expect("retired node")));
208                }
209                self.tree.stats.disposed += ids.len() as u64;
210                self.tree.receipt.applied += 1;
211                retired = Some(ids);
212                Undo::Dispose {
213                    root: *id,
214                    link,
215                    nodes: first..self.retired.len(),
216                }
217            }
218            _ => return Err(Error::Unsupported("use submission patch")),
219        };
220        self.records.push(Record {
221            undo,
222            receipt,
223            stats,
224            weight,
225        });
226        self.weight += weight;
227        Ok(retired)
228    }
229    fn rollback(&mut self, accepted: usize) {
230        while self.records.len() > accepted {
231            let Record {
232                undo,
233                receipt,
234                stats,
235                weight,
236            } = self.records.pop().expect("suffix");
237            self.weight -= weight;
238            match undo {
239                Undo::Create(ids) => {
240                    assert_eq!(ids.end, self.created.len(), "creation journal suffix");
241                    self.tree
242                        .retire(self.created[ids.start].0, None)
243                        .expect("new subtree");
244                    for (id, generation) in self.created.drain(ids) {
245                        if let Some(generation) = generation {
246                            self.tree.generations.insert(id.slot(), generation);
247                        } else {
248                            self.tree.generations.remove(&id.slot());
249                        }
250                    }
251                }
252                Undo::Patch {
253                    id,
254                    mut inverse,
255                    fields,
256                } => {
257                    let descriptor = &mut self
258                        .tree
259                        .nodes
260                        .get_mut(&id)
261                        .expect("patched node")
262                        .descriptor;
263                    descriptor.swap_patch(&mut inverse).expect("field inverse");
264                    descriptor.restore_fields(fields);
265                }
266                Undo::Place(id, link) => link.restore(self.tree, id),
267                Undo::Dispose { root, link, nodes } => {
268                    assert_eq!(nodes.end, self.retired.len(), "retirement journal suffix");
269                    for (id, mut node) in self.retired.drain(nodes) {
270                        if id == root {
271                            node.placed = false;
272                        }
273                        self.tree
274                            .generations
275                            .get_mut(&id.slot())
276                            .expect("retired generation")
277                            .1 = true;
278                        self.tree.nodes.insert(id, node);
279                    }
280                    link.restore(self.tree, root);
281                }
282            }
283            self.tree.receipt = receipt;
284            self.tree.stats = stats;
285        }
286    }
287    pub fn confirm(&mut self, accepted: usize) -> Receipt {
288        assert!(accepted <= self.records.len());
289        self.rollback(accepted);
290        self.records.clear();
291        self.created.clear();
292        self.retired.clear();
293        self.weight = 0;
294        self.tree.receipt
295    }
296    pub fn finish(mut self, accepted: usize) -> Receipt {
297        self.confirm(accepted)
298    }
299}
300impl Drop for Submission<'_> {
301    fn drop(&mut self) {
302        self.rollback(0);
303    }
304}