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