Skip to main content

vvv_engine/
plan_store.rs

1//! Bounded session-local executable plans and terminal outcomes. Lock after operation exclusion.
2use crate::capabilities::plans::review::CapturedReview;
3use crate::capabilities::plans::{PendingPlan, RetainedPlan};
4use crate::{EngineError, Failure, PlanId, PlanReceipt, PlanReview, PlanStatus};
5use serde::{Deserialize, Serialize};
6use std::sync::Arc;
7use std::{
8    collections::BTreeMap,
9    hash::BuildHasher,
10    time::{Duration, Instant},
11};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
15pub struct PlanLimits {
16    pub max_plans: usize,
17    pub max_plan_bytes: usize,
18    pub max_total_bytes: usize,
19    pub lifetime_seconds: u64,
20}
21impl Default for PlanLimits {
22    fn default() -> Self {
23        Self {
24            max_plans: 16,
25            max_plan_bytes: 16 * 1024 * 1024,
26            max_total_bytes: 64 * 1024 * 1024,
27            lifetime_seconds: 600,
28        }
29    }
30}
31struct Entry {
32    plan: RetainedPlan,
33    created: Instant,
34}
35pub(crate) struct PlanStore {
36    nonce: String,
37    next: u64,
38    entries: BTreeMap<PlanId, Entry>,
39    limits: PlanLimits,
40}
41impl Default for PlanStore {
42    fn default() -> Self {
43        Self {
44            nonce: format!(
45                "{:016x}",
46                std::collections::hash_map::RandomState::new().hash_one("vvv plan store")
47            ),
48            next: 0,
49            entries: BTreeMap::new(),
50            limits: PlanLimits::default(),
51        }
52    }
53}
54impl PlanStore {
55    pub(crate) fn allocate(&mut self) -> PlanId {
56        self.next += 1;
57        PlanId(format!("p1.{}.{:016x}", self.nonce, self.next))
58    }
59    fn purge(&mut self, now: Instant) {
60        let ttl = Duration::from_secs(self.limits.lifetime_seconds);
61        self.entries
62            .retain(|_, entry| now.duration_since(entry.created) < ttl);
63    }
64    pub(crate) fn insert(&mut self, plan: RetainedPlan, now: Instant) -> Result<(), EngineError> {
65        self.purge(now);
66        // Reclaim discarded tombstones on preparation. Never evict
67        // prepared plans or successful receipts to make a new plan fit.
68        self.entries
69            .retain(|_, entry| !matches!(entry.plan.review.status, PlanStatus::Discarded));
70        let total = self
71            .entries
72            .values()
73            .map(|e| e.plan.bytes)
74            .fold(0usize, usize::saturating_add);
75        if plan.bytes > self.limits.max_plan_bytes
76            || total.saturating_add(plan.bytes) > self.limits.max_total_bytes
77            || self.entries.len() >= self.limits.max_plans
78        {
79            return Err(EngineError::PlanRetentionLimit);
80        }
81        self.entries
82            .insert(plan.review.plan_id.clone(), Entry { plan, created: now });
83        Ok(())
84    }
85    pub(crate) fn review(&mut self, id: &PlanId, now: Instant) -> Result<PlanReview, EngineError> {
86        Ok(self.entry(id, now)?.plan.review.clone())
87    }
88    fn entry(&mut self, id: &PlanId, now: Instant) -> Result<&Entry, EngineError> {
89        let parts: Vec<_> = id.0.split('.').collect();
90        if parts.len() != 3
91            || parts[0] != "p1"
92            || parts[1].len() != 16
93            || parts[2].len() != 16
94            || !parts[1..]
95                .iter()
96                .all(|part| part.bytes().all(|b| b.is_ascii_hexdigit()))
97        {
98            return Err(EngineError::InvalidPlan);
99        }
100        self.purge(now);
101        self.entries.get(id).ok_or(EngineError::PlanExpired)
102    }
103    pub(crate) fn captured(
104        &mut self,
105        id: &PlanId,
106        now: Instant,
107    ) -> Result<Arc<CapturedReview>, EngineError> {
108        self.entry(id, now)?
109            .plan
110            .captured
111            .clone()
112            .ok_or(EngineError::PlanConsumed)
113    }
114    pub(crate) fn take(&mut self, id: &PlanId) -> Result<PendingPlan, EngineError> {
115        self.entries
116            .get_mut(id)
117            .and_then(|entry| entry.plan.pending.take())
118            .ok_or(EngineError::PlanConsumed)
119    }
120    pub(crate) fn complete(&mut self, id: &PlanId, result: &Result<PlanReceipt, EngineError>) {
121        let entry = self
122            .entries
123            .get_mut(id)
124            .expect("operation exclusion protects active plan");
125        if result.is_err() {
126            entry.plan.baseline = None;
127        }
128        entry.plan.review.status = match result {
129            Ok(receipt) => PlanStatus::Applied {
130                receipt: receipt.clone(),
131            },
132            Err(error) => PlanStatus::Failed {
133                failure: Failure::from(error),
134            },
135        };
136        entry.plan.bytes = crate::query_store::QueryStore::weight(&entry.plan.review)
137            .saturating_add(crate::query_store::QueryStore::weight(&entry.plan.baseline))
138            .saturating_add(entry.plan.captured.as_ref().map_or(0, |r| r.weight()));
139    }
140    pub(crate) fn validation(
141        &mut self,
142        id: &PlanId,
143        now: Instant,
144    ) -> Result<
145        (
146            PlanReceipt,
147            Arc<crate::capabilities::validation::baseline::ValidationBaseline>,
148            u64,
149        ),
150        EngineError,
151    > {
152        let review = self.review(id, now)?;
153        let PlanStatus::Applied { receipt } = review.status else {
154            return Err(EngineError::InvalidValidation);
155        };
156        let baseline = self.entries[id]
157            .plan
158            .baseline
159            .clone()
160            .expect("applied plan retains inputs");
161        Ok((
162            receipt,
163            baseline,
164            review.validation.map_or(1, |report| report.run + 1),
165        ))
166    }
167    pub(crate) fn reserve_validation(
168        &self,
169        id: &PlanId,
170        max_bytes: usize,
171    ) -> Result<(), EngineError> {
172        let plan = &self.entries[id].plan;
173        let mut review = plan.review.clone();
174        review.validation = None;
175        let bytes = crate::query_store::QueryStore::weight(&review)
176            .saturating_add(crate::query_store::QueryStore::weight(&plan.baseline))
177            .saturating_add(plan.captured.as_ref().map_or(0, |r| r.weight()))
178            .saturating_add(max_bytes.saturating_mul(4))
179            .saturating_add(4096);
180        let total = self
181            .entries
182            .iter()
183            .filter(|(key, _)| *key != id)
184            .map(|(_, entry)| entry.plan.bytes)
185            .fold(bytes, usize::saturating_add);
186        if bytes > self.limits.max_plan_bytes || total > self.limits.max_total_bytes {
187            return Err(EngineError::PlanRetentionLimit);
188        }
189        Ok(())
190    }
191    pub(crate) fn record_validation(&mut self, id: &PlanId, report: crate::ValidationReport) {
192        let entry = self
193            .entries
194            .get_mut(id)
195            .expect("operation exclusion protects active validation");
196        entry.plan.review.validation = Some(report);
197        entry.plan.bytes = crate::query_store::QueryStore::weight(&entry.plan.review)
198            .saturating_add(crate::query_store::QueryStore::weight(&entry.plan.baseline))
199            .saturating_add(entry.plan.captured.as_ref().map_or(0, |r| r.weight()));
200    }
201    pub(crate) fn discard(&mut self, id: &PlanId, now: Instant) -> Result<PlanReview, EngineError> {
202        let review = self.review(id, now)?;
203        if matches!(review.status, PlanStatus::Prepared { .. }) {
204            let entry = self.entries.get_mut(id).expect("review checked existence");
205            entry.plan.pending = None;
206            entry.plan.captured = None;
207            entry.plan.baseline = None;
208            entry.plan.review.status = PlanStatus::Discarded;
209            entry.plan.bytes = crate::query_store::QueryStore::weight(&entry.plan.review)
210                .saturating_add(crate::query_store::QueryStore::weight(&entry.plan.baseline))
211                .saturating_add(entry.plan.captured.as_ref().map_or(0, |r| r.weight()));
212            return Ok(entry.plan.review.clone());
213        }
214        // Terminal receipts/failures remain inspectable and retryable until expiry.
215        Ok(review)
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::{
223        Engine, Intent, Languages, MemoryVfs, MutationState, Planned, Rename, RenameIntent,
224        Workspace,
225    };
226    use std::sync::Arc;
227    struct Fixture {
228        engine: Engine,
229        store: PlanStore,
230    }
231    impl Fixture {
232        fn new() -> Self {
233            Self {
234                engine: Engine::new(
235                    Workspace::new("/ws", Arc::new(MemoryVfs::new())),
236                    Languages::new(),
237                ),
238                store: PlanStore::default(),
239            }
240        }
241        fn plan(&mut self) -> RetainedPlan {
242            let rename = Rename {
243                intent: RenameIntent::new("a", "b"),
244                state: MutationState::Preview,
245                declarations: vec![],
246                occurrences: vec![],
247                files: vec![],
248            };
249            let review = PlanReview {
250                plan_id: self.store.allocate(),
251                validation: None,
252                lifetime_seconds: self.store.limits.lifetime_seconds,
253                status: PlanStatus::Prepared {
254                    preview: crate::PlanPreview::Rename(Arc::new(rename.clone())),
255                },
256            };
257            let planned = Planned::new(
258                Intent::Rename(rename.intent.clone()),
259                rename,
260                vec![],
261                vec![],
262            );
263            let (_, snapshot) =
264                crate::graph::query_snapshot::QuerySnapshot::capture(&self.engine).unwrap();
265            let baseline = crate::capabilities::validation::baseline::ValidationBaseline::capture(
266                &self.engine,
267                snapshot,
268                planned.preview(),
269            )
270            .unwrap();
271            RetainedPlan::new(review, planned.into_mutation(), baseline, 0)
272        }
273    }
274    #[test]
275    fn expiry_is_monotonic_fixed_and_includes_completed_receipts() {
276        let mut f = Fixture::new();
277        let now = Instant::now();
278        let plan = f.plan();
279        let id = plan.review.plan_id.clone();
280        f.store.insert(plan, now).unwrap();
281        let end = now + Duration::from_secs(f.store.limits.lifetime_seconds);
282        f.store.review(&id, end - Duration::from_secs(1)).unwrap();
283        f.store.complete(
284            &id,
285            &Ok(PlanReceipt {
286                plan_id: id.clone(),
287                history_id: 1,
288                files: vec![],
289            }),
290        );
291        assert!(matches!(
292            f.store.review(&id, end),
293            Err(EngineError::PlanExpired)
294        ));
295        assert!(matches!(
296            f.store.captured(&id, end),
297            Err(EngineError::PlanExpired)
298        ));
299        assert!(f.store.entries.is_empty());
300    }
301    #[test]
302    fn individual_and_total_memory_limits_reject_without_evicting_other_plans() {
303        let mut f = Fixture::new();
304        let now = Instant::now();
305        let plan = f.plan();
306        let weight = plan.bytes;
307        f.store.limits.max_plan_bytes = weight - 1;
308        assert!(matches!(
309            f.store.insert(plan, now),
310            Err(EngineError::PlanRetentionLimit)
311        ));
312        assert!(f.store.entries.is_empty());
313        f.store.limits.max_plan_bytes = weight * 2;
314        f.store.limits.max_total_bytes = weight;
315        let plan = f.plan();
316        let id = plan.review.plan_id.clone();
317        f.store.insert(plan, now).unwrap();
318        let second = f.plan();
319        assert!(matches!(
320            f.store.insert(second, now),
321            Err(EngineError::PlanRetentionLimit)
322        ));
323        f.store.review(&id, now).unwrap();
324        assert_eq!(f.store.entries.len(), 1);
325    }
326    #[test]
327    fn completed_reviews_remain_charged_and_validation_cannot_overrun_retention() {
328        let mut f = Fixture::new();
329        let now = Instant::now();
330        let plan = f.plan();
331        let id = plan.review.plan_id.clone();
332        let review_bytes = plan.captured.as_ref().unwrap().weight();
333        f.store.insert(plan, now).unwrap();
334        f.store.complete(
335            &id,
336            &Ok(PlanReceipt {
337                plan_id: id.clone(),
338                history_id: 1,
339                files: vec![],
340            }),
341        );
342        assert!(f.store.entries[&id].plan.bytes >= review_bytes);
343        f.store.captured(&id, now).unwrap();
344        f.store.limits.max_total_bytes = f.store.entries[&id].plan.bytes;
345        assert!(matches!(
346            f.store.reserve_validation(&id, 4096),
347            Err(EngineError::PlanRetentionLimit)
348        ));
349        f.store.captured(&id, now).unwrap();
350    }
351}