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