Skip to main content

causa_kernel/context/material/state/
edit.rs

1//! Atomic, identity-preserving edits to context material.
2
3use super::Context;
4use crate::context::block::ContextBlock;
5use crate::context::ids::BlockId;
6use std::collections::{HashMap, HashSet};
7use std::ops::Range;
8
9/// One replacement expressed in coordinates of the original block sequence.
10#[derive(Debug, Clone, PartialEq)]
11pub struct Replacement {
12    /// The original half-open block range to replace.
13    pub range: Range<usize>,
14    /// Blocks inserted at the replacement range.
15    pub with: Vec<ContextBlock>,
16}
17
18/// Why an atomic context edit could not be committed.
19#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20#[non_exhaustive]
21pub enum EditError {
22    /// A replacement range is outside the original block sequence.
23    #[error("replacement {replacement_index} range {range:?} is invalid for length {len}")]
24    #[non_exhaustive]
25    InvalidRange {
26        /// The replacement's position in the submitted list.
27        replacement_index: usize,
28        /// The invalid original-coordinate range.
29        range: Range<usize>,
30        /// The original block count.
31        len: usize,
32    },
33    /// The resulting block sequence would contain the ID more than once.
34    #[error("duplicate block id: {0:?}")]
35    DuplicateBlockId(BlockId),
36    /// An existing ID was reused for different content or metadata.
37    #[error("block identity reused with different content or metadata: {0:?}")]
38    BlockIdentityMismatch(BlockId),
39}
40
41/// An edit failure together with every submitted block of edit material.
42#[derive(Debug, Clone, PartialEq, thiserror::Error)]
43#[error("context edit failed")]
44#[non_exhaustive]
45pub struct EditFailure {
46    /// The validation failure.
47    #[source]
48    pub reason: EditError,
49    /// Every submitted replacement, including replacements invalidated by overlap.
50    pub replacements: Vec<Replacement>,
51    /// Blocks submitted for insertion after all replacements.
52    pub appended: Vec<ContextBlock>,
53}
54
55/// An exclusive, uncommitted edit builder for a context.
56#[derive(Debug)]
57pub struct ContextEdit<'a> {
58    context: &'a mut Context,
59    replacements: Vec<Replacement>,
60    appended: Vec<ContextBlock>,
61}
62
63impl<'a> ContextEdit<'a> {
64    /// Returns the original block sequence while this edit is being prepared.
65    pub fn blocks(&self) -> &[ContextBlock] {
66        self.context.blocks()
67    }
68
69    /// Adds a replacement expressed against the original block sequence.
70    pub fn replace(
71        mut self,
72        range: Range<usize>,
73        with: impl IntoIterator<Item = ContextBlock>,
74    ) -> Self {
75        self.replacements.push(Replacement {
76            range,
77            with: with.into_iter().collect(),
78        });
79        self
80    }
81
82    /// Adds blocks to the end, after all replacement insertions.
83    pub fn append(mut self, blocks: impl IntoIterator<Item = ContextBlock>) -> Self {
84        self.appended.extend(blocks);
85        self
86    }
87
88    /// Validates and applies the complete edit atomically.
89    pub fn commit(self) -> Result<(), EditFailure> {
90        self.context.apply(self.replacements, self.appended)
91    }
92}
93
94impl Context {
95    /// Applies replacements and tail appends as one atomic edit.
96    ///
97    /// Every range is validated against the original block sequence before overlap
98    /// resolution. Later overlapping operations invalidate earlier operations in
99    /// full, and invalidated operations are not reconsidered. Ranges are half-open:
100    /// an insertion at `p` conflicts with `[start, end)` when `start <= p < end`,
101    /// while an insertion at `end` may coexist. Two insertions at the same point
102    /// conflict. Even an empty replacement with no inserted blocks participates in
103    /// overlap resolution.
104    ///
105    /// An empty edit succeeds. Effective replacement blocks and appended blocks are
106    /// checked against every original block, including originals removed by this
107    /// edit: an ID may be reused only when its content and metadata are unchanged.
108    /// The final sequence must have unique IDs. General edits permit partial tool
109    /// material; execution-specific validators enforce pairing. On failure,
110    /// the context is unchanged and all input material is returned in
111    /// [`EditFailure`].
112    pub fn apply(
113        &mut self,
114        mut replacements: Vec<Replacement>,
115        appended: Vec<ContextBlock>,
116    ) -> Result<(), EditFailure> {
117        let effective = match self.validate_edit(&replacements, &appended) {
118            Ok(effective) => effective,
119            Err(reason) => {
120                return Err(EditFailure {
121                    reason,
122                    replacements,
123                    appended,
124                });
125            }
126        };
127
128        if replacements.is_empty() {
129            self.blocks.extend(appended);
130            return Ok(());
131        }
132
133        let removed = effective
134            .iter()
135            .map(|index| replacements[*index].range.end - replacements[*index].range.start)
136            .sum::<usize>();
137        let capacity = self.blocks.len() - removed
138            + appended.len()
139            + effective
140                .iter()
141                .map(|index| replacements[*index].with.len())
142                .sum::<usize>();
143        let mut output = Vec::with_capacity(capacity);
144        let original = std::mem::take(&mut self.blocks);
145        let mut source = original.into_iter();
146        let mut source_index = 0;
147        for index in effective {
148            let replacement = &mut replacements[index];
149            while source_index < replacement.range.start {
150                output.push(source.next().expect("range validated"));
151                source_index += 1;
152            }
153            while source_index < replacement.range.end {
154                source.next().expect("range validated");
155                source_index += 1;
156            }
157            output.extend(std::mem::take(&mut replacement.with));
158        }
159        output.extend(source);
160        output.extend(appended);
161        self.blocks = output;
162        Ok(())
163    }
164
165    /// Starts an exclusive edit builder. Dropping it leaves this context unchanged.
166    pub fn edit(&mut self) -> ContextEdit<'_> {
167        ContextEdit {
168            context: self,
169            replacements: Vec::new(),
170            appended: Vec::new(),
171        }
172    }
173
174    fn validate_edit(
175        &self,
176        replacements: &[Replacement],
177        appended: &[ContextBlock],
178    ) -> Result<Vec<usize>, EditError> {
179        let len = self.blocks.len();
180        for (replacement_index, replacement) in replacements.iter().enumerate() {
181            if replacement.range.start > replacement.range.end || replacement.range.end > len {
182                return Err(EditError::InvalidRange {
183                    replacement_index,
184                    range: replacement.range.clone(),
185                    len,
186                });
187            }
188        }
189
190        let mut effective: Vec<usize> = Vec::with_capacity(replacements.len());
191        for (index, replacement) in replacements.iter().enumerate() {
192            effective.retain(|&previous| {
193                !(ranges_conflict(&replacement.range, &replacements[previous].range))
194            });
195            effective.push(index);
196        }
197        effective.sort_by_key(|index| replacements[*index].range.start);
198
199        let originals = self
200            .blocks
201            .iter()
202            .map(|block| (block.id(), block))
203            .collect::<HashMap<_, _>>();
204        for &index in &effective {
205            for block in &replacements[index].with {
206                validate_identity(&originals, block)?;
207            }
208        }
209        for block in appended {
210            validate_identity(&originals, block)?;
211        }
212
213        let mut ids = HashSet::with_capacity(len + appended.len());
214        let mut source_index = 0;
215        for &index in &effective {
216            let range = &replacements[index].range;
217            while source_index < range.start {
218                let id = self.blocks[source_index].id();
219                if !ids.insert(id) {
220                    return Err(EditError::DuplicateBlockId(id));
221                }
222                source_index += 1;
223            }
224            for block in &replacements[index].with {
225                if !ids.insert(block.id()) {
226                    return Err(EditError::DuplicateBlockId(block.id()));
227                }
228            }
229            source_index = range.end;
230        }
231        while source_index < len {
232            let id = self.blocks[source_index].id();
233            if !ids.insert(id) {
234                return Err(EditError::DuplicateBlockId(id));
235            }
236            source_index += 1;
237        }
238        for block in appended {
239            if !ids.insert(block.id()) {
240                return Err(EditError::DuplicateBlockId(block.id()));
241            }
242        }
243        Ok(effective)
244    }
245}
246
247fn validate_identity(
248    originals: &HashMap<BlockId, &ContextBlock>,
249    incoming: &ContextBlock,
250) -> Result<(), EditError> {
251    if let Some(existing) = originals.get(&incoming.id())
252        && *existing != incoming
253    {
254        return Err(EditError::BlockIdentityMismatch(incoming.id()));
255    }
256    Ok(())
257}
258
259fn ranges_conflict(left: &Range<usize>, right: &Range<usize>) -> bool {
260    match (left.is_empty(), right.is_empty()) {
261        (true, true) => left.start == right.start,
262        (true, false) => right.start <= left.start && left.start < right.end,
263        (false, true) => left.start <= right.start && right.start < left.end,
264        (false, false) => left.start < right.end && right.start < left.end,
265    }
266}