Skip to main content

ftui_layout/
pane_execution.rs

1//! Deterministic pane policy and live history execution.
2//!
3//! [`PaneExecutionEngine`] owns the operation journal and its selected history
4//! substrate. Persistent resize operations use path copying; structural edits
5//! use the canonical transaction once. Migration reconstructs every retained
6//! entry, including redo, before publishing a new substrate. Caller-measured
7//! observations drive selection and conservative fallback at gesture boundaries.
8//! Retained bytes are a structural model, not allocator measurements; samples
9//! describe operation execution and recording, excluding subsequent maintenance.
10
11use std::collections::VecDeque;
12use std::fmt;
13
14use crate::pane::{
15    PaneInteractionTimeline, PaneInteractionTimelineError, PaneOperation, PaneOperationError,
16    PaneOperationFamily, PaneOperationOutcome, PaneTree,
17};
18use crate::pane_memory::{PaneMemoryStrategy, baseline_footprint};
19use crate::pane_monitors::{
20    PaneMonitorThresholds, PaneMonitorVerdict, monitor_latency_envelope, monitor_retention_pressure,
21};
22use crate::pane_persistent::{PaneVersionStore, VersionedPaneTree};
23use crate::pane_retention::{PaneRetentionDecision, PaneRetentionOutcome, PaneRetentionPolicy};
24
25/// Failure before an edit or history transition can be published.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum PaneExecutionError {
28    /// Original operation failure, with its complete diagnostic payload.
29    Operation(Box<PaneOperationError>),
30    /// Canonical history replay failure.
31    Timeline(Box<PaneInteractionTimelineError>),
32    /// Imported history or the supplied live tree does not match the engine.
33    InvalidHistory(String),
34    /// The no-history strategy cannot serve an undo/redo consumer.
35    HistoryRequired,
36}
37
38impl fmt::Display for PaneExecutionError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::Operation(error) => error.fmt(f),
42            Self::Timeline(error) => error.fmt(f),
43            Self::InvalidHistory(reason) => write!(f, "invalid pane history: {reason}"),
44            Self::HistoryRequired => f.write_str("pane execution requires undo/redo history"),
45        }
46    }
47}
48
49impl std::error::Error for PaneExecutionError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Self::Operation(error) => Some(error.as_ref()),
53            Self::Timeline(error) => Some(error.as_ref()),
54            Self::InvalidHistory(_) | Self::HistoryRequired => None,
55        }
56    }
57}
58
59impl From<PaneOperationError> for PaneExecutionError {
60    fn from(error: PaneOperationError) -> Self {
61        Self::Operation(Box::new(error))
62    }
63}
64
65impl From<PaneInteractionTimelineError> for PaneExecutionError {
66    fn from(error: PaneInteractionTimelineError) -> Self {
67        Self::Timeline(Box::new(error))
68    }
69}
70
71/// One measurement supplied by the terminal or browser interaction adapter.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
73pub struct PaneExecutionSample {
74    /// Monotonic observation time, in nanoseconds from the adapter's origin.
75    pub timestamp_ns: u64,
76    /// Actual execution and journal-recording duration, excluding maintenance.
77    pub elapsed_ns: u64,
78    /// Whether the executed operation belongs to the local resize family.
79    pub local: bool,
80}
81
82/// Counters describe executed transitions, never proposed strategies.
83#[derive(Debug, Clone, PartialEq, serde::Serialize)]
84pub struct PaneExecutionStatus {
85    pub strategy: PaneMemoryStrategy,
86    pub conservative: bool,
87    pub applies: u64,
88    pub persistent_applies: u64,
89    pub checkpointed_applies: u64,
90    pub conservative_applies: u64,
91    pub undos: u64,
92    pub redos: u64,
93    pub switches: u64,
94    pub fallbacks: u64,
95    /// Journal, active persistent store, and canonical render projection bytes.
96    pub retained_bytes: usize,
97    pub last_maintenance_error: Option<String>,
98    pub last_retention: Option<PaneRetentionDecision>,
99    pub last_monitor: Option<PaneMonitorVerdict>,
100}
101
102/// Shared history interface for actual hosts and canonical comparison controls.
103pub trait PaneHistory {
104    fn apply_and_record(
105        &mut self,
106        tree: &mut PaneTree,
107        sequence: u64,
108        id: u64,
109        operation: PaneOperation,
110    ) -> Result<PaneOperationOutcome, PaneExecutionError>;
111    fn apply_and_record_coalesced_resize_delta(
112        &mut self,
113        tree: &mut PaneTree,
114        sequence: u64,
115        id: u64,
116        operation: PaneOperation,
117        boundary: u64,
118    ) -> Result<PaneOperationOutcome, PaneExecutionError>;
119    fn undo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError>;
120    fn redo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError>;
121    fn replay(&self) -> Result<PaneTree, PaneExecutionError>;
122    fn applied_len(&self) -> usize;
123    /// Maintenance errors are diagnostic: the preceding accepted edit remains accepted.
124    fn observe(
125        &mut self,
126        _tree: &PaneTree,
127        _sample: PaneExecutionSample,
128    ) -> Result<(), PaneExecutionError> {
129        Ok(())
130    }
131}
132
133impl PaneHistory for PaneInteractionTimeline {
134    fn apply_and_record(
135        &mut self,
136        tree: &mut PaneTree,
137        sequence: u64,
138        id: u64,
139        operation: PaneOperation,
140    ) -> Result<PaneOperationOutcome, PaneExecutionError> {
141        Ok(Self::apply_and_record(self, tree, sequence, id, operation)?)
142    }
143    fn apply_and_record_coalesced_resize_delta(
144        &mut self,
145        tree: &mut PaneTree,
146        sequence: u64,
147        id: u64,
148        operation: PaneOperation,
149        boundary: u64,
150    ) -> Result<PaneOperationOutcome, PaneExecutionError> {
151        Ok(Self::apply_and_record_coalesced_resize_delta(
152            self, tree, sequence, id, operation, boundary,
153        )?)
154    }
155    fn undo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError> {
156        Ok(Self::undo(self, tree)?)
157    }
158    fn redo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError> {
159        Ok(Self::redo(self, tree)?)
160    }
161    fn replay(&self) -> Result<PaneTree, PaneExecutionError> {
162        Ok(Self::replay(self)?)
163    }
164    fn applied_len(&self) -> usize {
165        Self::applied_len(self)
166    }
167}
168
169/// Journal and live substrate, paired with the host's canonical render tree.
170#[derive(Debug, Clone)]
171pub struct PaneExecutionEngine {
172    timeline: PaneInteractionTimeline,
173    persistent: Option<PaneVersionStore>,
174    policy: PaneExecutionPolicy,
175    status: PaneExecutionStatus,
176    expected_hash: u64,
177    samples: VecDeque<PaneExecutionSample>,
178    gesture_active: bool,
179    fallback_pending: bool,
180    fallback_latched: bool,
181    latency_envelope_ns: u64,
182}
183
184impl PaneExecutionEngine {
185    /// Start checkpointed history with a 4096-edit bound and an 8ms observation envelope.
186    /// Adaptive and persistent execution require an explicit policy: full-wrapper
187    /// comparisons currently show workload-dependent regressions in those modes.
188    #[must_use]
189    pub fn new(tree: &PaneTree) -> Self {
190        let timeline = PaneInteractionTimeline::with_baseline(tree).with_max_entries(0);
191        let bytes = timeline
192            .retention_diagnostics()
193            .estimated_total_retained_bytes
194            .saturating_add(baseline_footprint(tree).total_retained_bytes);
195        Self {
196            timeline,
197            persistent: None,
198            policy: PaneExecutionPolicy::adaptive(PaneRetentionPolicy::bounded(0, 4096))
199                .forcing(PaneMemoryStrategy::Checkpointed),
200            expected_hash: tree.history_state_hash(),
201            samples: VecDeque::new(),
202            gesture_active: false,
203            fallback_pending: false,
204            fallback_latched: false,
205            latency_envelope_ns: 8_000_000,
206            status: PaneExecutionStatus {
207                strategy: PaneMemoryStrategy::Checkpointed,
208                conservative: false,
209                applies: 0,
210                persistent_applies: 0,
211                checkpointed_applies: 0,
212                conservative_applies: 0,
213                undos: 0,
214                redos: 0,
215                switches: 0,
216                fallbacks: 0,
217                retained_bytes: bytes,
218                last_maintenance_error: None,
219                last_retention: None,
220                last_monitor: None,
221            },
222        }
223    }
224
225    /// Validate the complete imported journal and all checkpoints, including redo.
226    pub fn from_timeline(
227        tree: &PaneTree,
228        timeline: PaneInteractionTimeline,
229    ) -> Result<Self, PaneExecutionError> {
230        let mut engine = Self::new(tree);
231        let (timeline, persistent) =
232            Self::reconstruct(tree, &timeline, PaneMemoryStrategy::Checkpointed)?;
233        engine.timeline = timeline;
234        engine.persistent = persistent;
235        engine.status.retained_bytes = engine.retained_bytes(tree);
236        Ok(engine)
237    }
238
239    #[must_use]
240    pub const fn timeline(&self) -> &PaneInteractionTimeline {
241        &self.timeline
242    }
243    #[must_use]
244    pub const fn policy(&self) -> PaneExecutionPolicy {
245        self.policy
246    }
247    #[must_use]
248    pub const fn strategy(&self) -> PaneMemoryStrategy {
249        self.status.strategy
250    }
251    #[must_use]
252    pub const fn status(&self) -> &PaneExecutionStatus {
253        &self.status
254    }
255    #[must_use]
256    pub const fn applied_len(&self) -> usize {
257        self.timeline.cursor
258    }
259
260    /// Set the measured-operation envelope. Zero disables this monitor.
261    pub const fn set_latency_envelope_ns(&mut self, envelope: u64) {
262        self.latency_envelope_ns = envelope;
263    }
264
265    fn check_live(&self, tree: &PaneTree) -> Result<(), PaneExecutionError> {
266        if tree.history_state_hash() != self.expected_hash {
267            return Err(PaneExecutionError::InvalidHistory(
268                "live tree changed outside its history engine".into(),
269            ));
270        }
271        Ok(())
272    }
273
274    pub fn apply_and_record(
275        &mut self,
276        tree: &mut PaneTree,
277        sequence: u64,
278        id: u64,
279        operation: PaneOperation,
280    ) -> Result<PaneOperationOutcome, PaneExecutionError> {
281        self.apply(tree, sequence, id, operation, None)
282    }
283
284    pub fn apply_and_record_coalesced_resize_delta(
285        &mut self,
286        tree: &mut PaneTree,
287        sequence: u64,
288        id: u64,
289        operation: PaneOperation,
290        boundary: u64,
291    ) -> Result<PaneOperationOutcome, PaneExecutionError> {
292        self.apply(tree, sequence, id, operation, Some(boundary))
293    }
294
295    fn apply(
296        &mut self,
297        tree: &mut PaneTree,
298        sequence: u64,
299        id: u64,
300        operation: PaneOperation,
301        boundary: Option<u64>,
302    ) -> Result<PaneOperationOutcome, PaneExecutionError> {
303        self.check_live(tree)?;
304        let outcome = if let Some(store) = &mut self.persistent {
305            let (version, projection, outcome) = store.prepare_live_apply(tree, id, &operation)?;
306            let coalesced = self.timeline.record_applied(
307                &projection,
308                None,
309                sequence,
310                operation,
311                &outcome,
312                boundary,
313                false,
314            );
315            store.commit_prepared(version, coalesced);
316            *tree = projection;
317            self.status.persistent_applies = self.status.persistent_applies.saturating_add(1);
318            outcome
319        } else {
320            let outcome = if self.status.conservative {
321                tree.apply_operation_conservative(id, operation.clone())?
322            } else {
323                tree.apply_operation(id, operation.clone())?
324            };
325            self.timeline
326                .record_applied(tree, None, sequence, operation, &outcome, boundary, true);
327            if self.status.conservative {
328                self.status.conservative_applies =
329                    self.status.conservative_applies.saturating_add(1);
330            } else {
331                self.status.checkpointed_applies =
332                    self.status.checkpointed_applies.saturating_add(1);
333            }
334            outcome
335        };
336        self.expected_hash = tree.history_state_hash();
337        self.status.applies = self.status.applies.saturating_add(1);
338        Ok(outcome)
339    }
340
341    pub fn undo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError> {
342        self.navigate(tree, false)
343    }
344    pub fn redo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError> {
345        self.navigate(tree, true)
346    }
347
348    fn navigate(&mut self, tree: &mut PaneTree, forward: bool) -> Result<bool, PaneExecutionError> {
349        self.check_live(tree)?;
350        let cursor = self.timeline.cursor;
351        if (!forward && cursor == 0) || (forward && cursor == self.timeline.entries.len()) {
352            return Ok(false);
353        }
354        if let Some(store) = &mut self.persistent {
355            let target = if forward { cursor + 1 } else { cursor - 1 };
356            let version = store.version_at(target).ok_or_else(|| {
357                PaneExecutionError::InvalidHistory("missing persistent navigation target".into())
358            })?;
359            let projection = version
360                .to_pane_tree()
361                .map_err(|error| PaneExecutionError::InvalidHistory(error.to_string()))?;
362            store.seek(target);
363            self.timeline.cursor = target;
364            *tree = projection;
365        } else if forward {
366            self.timeline.redo(tree)?;
367        } else {
368            self.timeline.undo(tree)?;
369        }
370        self.expected_hash = tree.history_state_hash();
371        if forward {
372            self.status.redos = self.status.redos.saturating_add(1);
373        } else {
374            self.status.undos = self.status.undos.saturating_add(1);
375        }
376        Ok(true)
377    }
378
379    pub fn replay(&self) -> Result<PaneTree, PaneExecutionError> {
380        if let Some(store) = &self.persistent {
381            store
382                .current()
383                .to_pane_tree()
384                .map_err(|error| PaneExecutionError::InvalidHistory(error.to_string()))
385        } else {
386            Ok(self.timeline.replay()?)
387        }
388    }
389
390    /// Pin the pre-gesture cursor against migration and pruning until completion.
391    pub const fn begin_gesture(&mut self) {
392        self.gesture_active = true;
393    }
394    pub fn end_gesture(&mut self, tree: &PaneTree) -> Result<(), PaneExecutionError> {
395        self.gesture_active = false;
396        self.maintain_and_record(tree)
397    }
398
399    /// Install an override atomically. Active gestures defer substrate maintenance.
400    pub fn set_policy(
401        &mut self,
402        tree: &PaneTree,
403        policy: PaneExecutionPolicy,
404    ) -> Result<(), PaneExecutionError> {
405        self.check_live(tree)?;
406        if policy.forced_strategy == Some(PaneMemoryStrategy::Baseline) {
407            return Err(PaneExecutionError::HistoryRequired);
408        }
409        let mut candidate = self.clone();
410        candidate.policy = policy;
411        candidate.fallback_pending = false;
412        // An explicit reset clears a monitor latch; an operator override still wins.
413        candidate.fallback_latched = false;
414        if !candidate.gesture_active {
415            candidate.maintain(tree)?;
416        }
417        *self = candidate;
418        Ok(())
419    }
420
421    pub fn observe(
422        &mut self,
423        tree: &PaneTree,
424        sample: PaneExecutionSample,
425    ) -> Result<(), PaneExecutionError> {
426        self.check_live(tree)?;
427        if self
428            .samples
429            .back()
430            .is_some_and(|previous| sample.timestamp_ns < previous.timestamp_ns)
431        {
432            let error =
433                PaneExecutionError::InvalidHistory("observation clock moved backwards".into());
434            self.status.last_maintenance_error = Some(error.to_string());
435            return Err(error);
436        }
437        if self.samples.len() == 128 {
438            self.samples.pop_front();
439        }
440        self.samples.push_back(sample);
441        if self.latency_envelope_ns != 0 {
442            let verdict = monitor_latency_envelope(
443                self.strategy(),
444                sample.elapsed_ns as f64,
445                self.latency_envelope_ns as f64,
446                &PaneMonitorThresholds::default(),
447            );
448            self.fallback_pending |= verdict.status.is_violation();
449            self.status.last_monitor = Some(verdict);
450        }
451        self.maintain_and_record(tree)
452    }
453
454    fn profile(&self) -> PaneWorkloadProfile {
455        let mut peak = 0;
456        let mut previous = None;
457        for sample in &self.samples {
458            if let Some(timestamp) = previous {
459                let interval = sample.timestamp_ns.saturating_sub(timestamp);
460                if let Some(rate) = 1_000_000_000_u64.checked_div(interval) {
461                    peak = peak.max(u32::try_from(rate).unwrap_or(u32::MAX));
462                }
463            }
464            previous = Some(sample.timestamp_ns);
465        }
466        PaneWorkloadProfile::new(
467            self.samples.len(),
468            self.samples.iter().filter(|sample| sample.local).count(),
469            peak,
470            true,
471        )
472    }
473
474    fn maintain_and_record(&mut self, tree: &PaneTree) -> Result<(), PaneExecutionError> {
475        let result = self.maintain(tree);
476        self.status.last_maintenance_error = result.as_ref().err().map(ToString::to_string);
477        result
478    }
479
480    fn maintain(&mut self, tree: &PaneTree) -> Result<(), PaneExecutionError> {
481        self.check_live(tree)?;
482        if self.gesture_active {
483            return Ok(());
484        }
485        let conservative =
486            self.policy.conservative || self.fallback_latched || self.fallback_pending;
487        let desired = if conservative {
488            PaneMemoryStrategy::Checkpointed
489        } else {
490            self.policy
491                .reselect(self.profile(), self.strategy())
492                .strategy
493        };
494        let bytes = self.retained_bytes(tree);
495        let pressure = self
496            .policy
497            .retention
498            .budget
499            .is_exceeded_by(bytes, self.timeline.entries.len());
500        if desired != self.strategy() || pressure {
501            // Migration, pruning, and a possible pressure fallback form one
502            // publication boundary. Failure preserves the accepted edit and
503            // the substrate on which it ran.
504            let mut candidate = self.clone();
505            candidate.maintain_selected(tree, desired, conservative, bytes)?;
506            *self = candidate;
507            return Ok(());
508        }
509        self.maintain_selected(tree, desired, conservative, bytes)
510    }
511
512    fn maintain_selected(
513        &mut self,
514        tree: &PaneTree,
515        desired: PaneMemoryStrategy,
516        conservative: bool,
517        bytes_before_switch: usize,
518    ) -> Result<(), PaneExecutionError> {
519        let changed = desired != self.strategy();
520        self.switch(tree, desired, conservative)?;
521        let bytes = if changed {
522            self.retained_bytes(tree)
523        } else {
524            bytes_before_switch
525        };
526        self.retain(tree, bytes)?;
527        if self.status.last_retention.as_ref().is_some_and(|decision| {
528            matches!(
529                decision.outcome,
530                PaneRetentionOutcome::FloorReached | PaneRetentionOutcome::PruningBlocked
531            )
532        }) {
533            self.switch(tree, PaneMemoryStrategy::Checkpointed, true)?;
534            self.status.retained_bytes = self.retained_bytes(tree);
535        }
536        self.fallback_pending = false;
537        Ok(())
538    }
539
540    fn switch(
541        &mut self,
542        tree: &PaneTree,
543        strategy: PaneMemoryStrategy,
544        conservative: bool,
545    ) -> Result<(), PaneExecutionError> {
546        if strategy != self.strategy() {
547            let (timeline, persistent) = Self::reconstruct(tree, &self.timeline, strategy)?;
548            self.timeline = timeline;
549            self.persistent = persistent;
550            self.status.strategy = strategy;
551            self.status.switches = self.status.switches.saturating_add(1);
552        }
553        if conservative && !self.status.conservative {
554            self.status.fallbacks = self.status.fallbacks.saturating_add(1);
555        }
556        self.status.conservative = conservative;
557        self.fallback_latched = conservative && !self.policy.conservative;
558        Ok(())
559    }
560
561    fn retained_bytes(&self, tree: &PaneTree) -> usize {
562        self.timeline
563            .retention_diagnostics()
564            .estimated_total_retained_bytes
565            .saturating_add(baseline_footprint(tree).total_retained_bytes)
566            .saturating_add(
567                self.persistent
568                    .as_ref()
569                    .map_or(0, PaneVersionStore::retained_bytes),
570            )
571    }
572
573    fn retain(&mut self, tree: &PaneTree, bytes_before: usize) -> Result<(), PaneExecutionError> {
574        let policy = self.policy.retention;
575        let units_before = self.timeline.entries.len();
576        let mut bytes_after = bytes_before;
577        if !policy.conservative_debug
578            && policy.budget.is_exceeded_by(bytes_before, units_before)
579            && self.timeline.cursor > 0
580        {
581            // Stage both representations together. A failed baseline advance cannot
582            // leave the store at a different cursor from the operation journal.
583            let mut candidate = self.clone();
584            while policy
585                .budget
586                .is_exceeded_by(bytes_after, candidate.timeline.entries.len())
587                && candidate.timeline.cursor > 0
588            {
589                let count = candidate.timeline.entries.len();
590                // Zero means unbounded in the timeline API, so advance the last
591                // entry explicitly when pruning reaches the irreducible baseline.
592                if count == 1 {
593                    candidate.timeline =
594                        PaneInteractionTimeline::with_baseline(tree).with_max_entries(0);
595                    candidate.timeline.checkpoint_interval = self.timeline.checkpoint_interval;
596                    if candidate.persistent.is_some() {
597                        candidate.persistent = Some(PaneVersionStore::with_max_versions(
598                            VersionedPaneTree::from_pane_tree(tree),
599                            0,
600                        ));
601                    }
602                } else {
603                    if candidate.timeline.set_max_entries(count - 1) != 1 {
604                        return Err(PaneExecutionError::InvalidHistory(
605                            "retention could not advance the baseline".into(),
606                        ));
607                    }
608                    candidate.timeline.set_max_entries(0);
609                    if let Some(store) = &mut candidate.persistent {
610                        if store.set_max_versions(count) != 1 {
611                            return Err(PaneExecutionError::InvalidHistory(
612                                "persistent retention diverged from journal".into(),
613                            ));
614                        }
615                        store.set_max_versions(0);
616                    }
617                }
618                bytes_after = candidate.retained_bytes(tree);
619            }
620            self.timeline = candidate.timeline;
621            self.persistent = candidate.persistent;
622        }
623        let units_after = self.timeline.entries.len();
624        let over = policy.budget.is_exceeded_by(bytes_after, units_after);
625        let outcome = if over && policy.conservative_debug {
626            PaneRetentionOutcome::ConservativeHold
627        } else if over && units_after == 0 {
628            PaneRetentionOutcome::FloorReached
629        } else if over {
630            PaneRetentionOutcome::PruningBlocked
631        } else if units_after < units_before {
632            PaneRetentionOutcome::PrunedToFit
633        } else {
634            PaneRetentionOutcome::WithinBudget
635        };
636        let decision = PaneRetentionDecision {
637            strategy: self.strategy(),
638            budget: policy.budget,
639            conservative_debug: policy.conservative_debug,
640            units_before,
641            units_after,
642            units_pruned: units_before - units_after,
643            bytes_before,
644            bytes_after,
645            current_state_hash: tree.state_hash(),
646            outcome,
647            log: format!(
648                "live pane retention: {outcome:?}; edits {units_before}->{units_after}, modeled bytes {bytes_before}->{bytes_after}"
649            ),
650        };
651        let verdict = monitor_retention_pressure(&decision, &PaneMonitorThresholds::default());
652        if self
653            .status
654            .last_monitor
655            .as_ref()
656            .is_none_or(|previous| !previous.status.is_violation())
657            || verdict.status.is_violation()
658        {
659            self.status.last_monitor = Some(verdict);
660        }
661        self.status.last_retention = Some(decision);
662        self.status.retained_bytes = bytes_after;
663        Ok(())
664    }
665
666    fn reconstruct(
667        live: &PaneTree,
668        source: &PaneInteractionTimeline,
669        strategy: PaneMemoryStrategy,
670    ) -> Result<(PaneInteractionTimeline, Option<PaneVersionStore>), PaneExecutionError> {
671        if strategy == PaneMemoryStrategy::Baseline {
672            return Err(PaneExecutionError::HistoryRequired);
673        }
674        if source.cursor > source.entries.len() {
675            return Err(PaneExecutionError::InvalidHistory(
676                "cursor exceeds journal".into(),
677            ));
678        }
679        let baseline = source
680            .baseline
681            .clone()
682            .ok_or(PaneInteractionTimelineError::MissingBaseline)?;
683        let mut tree = PaneTree::from_snapshot(baseline)
684            .map_err(|source| PaneInteractionTimelineError::BaselineInvalid { source })?;
685        let mut timeline = PaneInteractionTimeline::with_baseline(&tree).with_max_entries(0);
686        timeline.checkpoint_interval = source.checkpoint_interval;
687        let mut persistent = (strategy == PaneMemoryStrategy::Persistent).then(|| {
688            PaneVersionStore::with_max_versions(VersionedPaneTree::from_pane_tree(&tree), 0)
689        });
690        let mut current = (source.cursor == 0).then(|| tree.to_snapshot());
691        let mut checkpoint_indices = std::collections::BTreeSet::new();
692        for checkpoint in &source.checkpoints {
693            if checkpoint.applied_len > source.entries.len()
694                || !checkpoint_indices.insert(checkpoint.applied_len)
695            {
696                return Err(PaneExecutionError::InvalidHistory(
697                    "duplicate or out-of-range checkpoint".into(),
698                ));
699            }
700        }
701        for index in 0..=source.entries.len() {
702            for checkpoint in source
703                .checkpoints
704                .iter()
705                .filter(|checkpoint| checkpoint.applied_len == index)
706            {
707                let restored = PaneTree::from_snapshot(checkpoint.snapshot.clone())
708                    .map_err(|source| PaneInteractionTimelineError::BaselineInvalid { source })?;
709                if restored.to_snapshot() != tree.to_snapshot() {
710                    return Err(PaneExecutionError::InvalidHistory(format!(
711                        "checkpoint {index} differs from journal"
712                    )));
713                }
714            }
715            let Some(entry) = source.entries.get(index) else {
716                break;
717            };
718            let outcome = if let Some(store) = &mut persistent {
719                let (version, projection, outcome) =
720                    store.prepare_live_apply(&tree, entry.operation_id, &entry.operation)?;
721                store.commit_prepared(version, false);
722                tree = projection;
723                outcome
724            } else {
725                tree.apply_operation(entry.operation_id, entry.operation.clone())?
726            };
727            if outcome.before_hash != entry.before_hash || outcome.after_hash != entry.after_hash {
728                return Err(PaneExecutionError::InvalidHistory(format!(
729                    "entry {index} hashes differ from replay"
730                )));
731            }
732            timeline.record_applied(
733                &tree,
734                None,
735                entry.sequence,
736                entry.operation.clone(),
737                &outcome,
738                None,
739                persistent.is_none(),
740            );
741            if index + 1 == source.cursor {
742                current = Some(tree.to_snapshot());
743            }
744        }
745        if current.as_ref() != Some(&live.to_snapshot()) {
746            return Err(PaneExecutionError::InvalidHistory(
747                "current snapshot differs from journal cursor".into(),
748            ));
749        }
750        timeline.cursor = source.cursor;
751        if let Some(store) = &mut persistent {
752            store.seek(source.cursor);
753        }
754        Ok((timeline, persistent))
755    }
756}
757
758impl PaneHistory for PaneExecutionEngine {
759    fn apply_and_record(
760        &mut self,
761        tree: &mut PaneTree,
762        sequence: u64,
763        id: u64,
764        operation: PaneOperation,
765    ) -> Result<PaneOperationOutcome, PaneExecutionError> {
766        Self::apply_and_record(self, tree, sequence, id, operation)
767    }
768    fn apply_and_record_coalesced_resize_delta(
769        &mut self,
770        tree: &mut PaneTree,
771        sequence: u64,
772        id: u64,
773        operation: PaneOperation,
774        boundary: u64,
775    ) -> Result<PaneOperationOutcome, PaneExecutionError> {
776        Self::apply_and_record_coalesced_resize_delta(self, tree, sequence, id, operation, boundary)
777    }
778    fn undo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError> {
779        Self::undo(self, tree)
780    }
781    fn redo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneExecutionError> {
782        Self::redo(self, tree)
783    }
784    fn replay(&self) -> Result<PaneTree, PaneExecutionError> {
785        Self::replay(self)
786    }
787    fn applied_len(&self) -> usize {
788        Self::applied_len(self)
789    }
790    fn observe(
791        &mut self,
792        tree: &PaneTree,
793        sample: PaneExecutionSample,
794    ) -> Result<(), PaneExecutionError> {
795        Self::observe(self, tree, sample)
796    }
797}
798
799/// Observed shape of a pane-interaction workload window — the deterministic
800/// input to strategy selection.
801#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
802pub struct PaneWorkloadProfile {
803    /// Operations observed in the window.
804    pub operation_count: usize,
805    /// Of those, how many are `Local` (resize / `SetSplitRatio`) — the hot path
806    /// where the persistent store's structural sharing and O(1) navigation win.
807    pub local_operation_count: usize,
808    /// Peak operations-per-second observed (burstiness, e.g. a live drag-resize).
809    pub peak_ops_per_sec: u32,
810    /// Whether undo/redo history is required at all. If not, no history substrate
811    /// is needed and the baseline path is selected.
812    pub history_required: bool,
813}
814
815impl PaneWorkloadProfile {
816    /// Construct a profile from explicit counts.
817    #[must_use]
818    pub const fn new(
819        operation_count: usize,
820        local_operation_count: usize,
821        peak_ops_per_sec: u32,
822        history_required: bool,
823    ) -> Self {
824        Self {
825            operation_count,
826            local_operation_count,
827            peak_ops_per_sec,
828            history_required,
829        }
830    }
831
832    /// Derive a profile from an observed operation window. Local operations are
833    /// classified by [`PaneOperation::family`] (`Local` = `SetSplitRatio`).
834    #[must_use]
835    pub fn observe(ops: &[PaneOperation], peak_ops_per_sec: u32, history_required: bool) -> Self {
836        let local_operation_count = ops
837            .iter()
838            .filter(|op| op.family() == PaneOperationFamily::Local)
839            .count();
840        Self::new(
841            ops.len(),
842            local_operation_count,
843            peak_ops_per_sec,
844            history_required,
845        )
846    }
847
848    /// Local-operation fraction as an integer percentage in `[0, 100]`.
849    #[must_use]
850    pub const fn local_fraction_pct(self) -> u32 {
851        if self.operation_count == 0 {
852            return 0;
853        }
854        ((self.local_operation_count.saturating_mul(100)) / self.operation_count) as u32
855    }
856}
857
858/// Why a strategy was selected — the auditable rationale in every decision.
859#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
860pub enum PaneStrategyReason {
861    /// An operator/debug override forced this strategy.
862    ForcedOverride,
863    /// Conservative mode forced the certified checkpointed path.
864    ConservativeFallback,
865    /// History is not required, so the baseline (no-history) path was chosen.
866    NoHistoryRequired,
867    /// A resize-dominated, bursty, deep workload favored the persistent store.
868    ResizeDominatedBurst,
869    /// No strategy clearly won, so the conservative checkpointed default was used.
870    GeneralDefault,
871    /// A hysteresis margin held the previous strategy to avoid thrashing.
872    HysteresisHold,
873}
874
875impl PaneStrategyReason {
876    /// Stable identifier for logs/artifacts.
877    #[must_use]
878    pub const fn as_str(self) -> &'static str {
879        match self {
880            Self::ForcedOverride => "forced_override",
881            Self::ConservativeFallback => "conservative_fallback",
882            Self::NoHistoryRequired => "no_history_required",
883            Self::ResizeDominatedBurst => "resize_dominated_burst",
884            Self::GeneralDefault => "general_default",
885            Self::HysteresisHold => "hysteresis_hold",
886        }
887    }
888}
889
890/// Deterministic policy that selects among the three pane execution strategies.
891///
892/// The thresholds are explicit and tunable; defaults are derived from the
893/// persistence spike (`bd-1k7ek.5`) and the memory telemetry (`bd-25wj7.1`): the
894/// persistent store earns its keep on resize-dominated bursts deep enough that
895/// O(1) navigation and structural sharing pay off, while the checkpointed
896/// timeline is the safe default everywhere else.
897#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
898pub struct PaneExecutionPolicy {
899    /// Force a specific strategy (operator/debug override). `None` = adaptive.
900    pub forced_strategy: Option<PaneMemoryStrategy>,
901    /// Force the conservative certified path (checkpointed). Overrides adaptation.
902    pub conservative: bool,
903    /// Minimum operations before the persistent store is considered.
904    pub persistent_min_operations: usize,
905    /// Minimum local-op fraction (percent) for the persistent store.
906    pub persistent_local_fraction_pct: u32,
907    /// Minimum peak ops/sec (burstiness) for the persistent store.
908    pub persistent_burst_ops_per_sec: u32,
909    /// Hysteresis margin (percent, on the local fraction) used by
910    /// [`reselect`](Self::reselect) to avoid thrashing near a threshold.
911    pub hysteresis_pct: u32,
912    /// The retention policy carried alongside the selected strategy.
913    pub retention: PaneRetentionPolicy,
914}
915
916impl PaneExecutionPolicy {
917    /// Default: persistent only past the spike's bounded-window depth.
918    pub const DEFAULT_PERSISTENT_MIN_OPERATIONS: usize = 64;
919    /// Default: persistent only when the workload is resize-dominated.
920    pub const DEFAULT_PERSISTENT_LOCAL_FRACTION_PCT: u32 = 80;
921    /// Default: persistent only under a drag-resize burst.
922    pub const DEFAULT_PERSISTENT_BURST_OPS_PER_SEC: u32 = 60;
923    /// Default hysteresis margin.
924    pub const DEFAULT_HYSTERESIS_PCT: u32 = 10;
925
926    /// An adaptive policy with the default thresholds, carrying `retention`.
927    #[must_use]
928    pub const fn adaptive(retention: PaneRetentionPolicy) -> Self {
929        Self {
930            forced_strategy: None,
931            conservative: false,
932            persistent_min_operations: Self::DEFAULT_PERSISTENT_MIN_OPERATIONS,
933            persistent_local_fraction_pct: Self::DEFAULT_PERSISTENT_LOCAL_FRACTION_PCT,
934            persistent_burst_ops_per_sec: Self::DEFAULT_PERSISTENT_BURST_OPS_PER_SEC,
935            hysteresis_pct: Self::DEFAULT_HYSTERESIS_PCT,
936            retention,
937        }
938    }
939
940    /// Return this policy forced to the conservative certified path (checkpointed).
941    #[must_use]
942    pub const fn conservative(mut self) -> Self {
943        self.conservative = true;
944        self
945    }
946
947    /// Return this policy forced to a specific strategy.
948    #[must_use]
949    pub const fn forcing(mut self, strategy: PaneMemoryStrategy) -> Self {
950        self.forced_strategy = Some(strategy);
951        self
952    }
953
954    /// Select a strategy for `profile` (stateless, deterministic).
955    #[must_use]
956    pub fn select(&self, profile: PaneWorkloadProfile) -> PaneExecutionDecision {
957        let (strategy, reason, forced) = self.decide(profile);
958        self.decision(strategy, reason, forced, profile)
959    }
960
961    /// Re-select with hysteresis given the `previous` strategy: keep `previous`
962    /// unless the workload favors a different strategy by a clear margin. This
963    /// prevents thrashing when the local-op fraction jitters near a threshold.
964    /// Forced/conservative overrides ignore hysteresis.
965    #[must_use]
966    pub fn reselect(
967        &self,
968        profile: PaneWorkloadProfile,
969        previous: PaneMemoryStrategy,
970    ) -> PaneExecutionDecision {
971        if self.forced_strategy.is_some() || self.conservative {
972            return self.select(profile);
973        }
974        let (fresh, reason, forced) = self.decide(profile);
975        if fresh == previous {
976            return self.decision(fresh, reason, forced, profile);
977        }
978        // The history requirement is a hard functional flag, not a tunable
979        // threshold: honor it immediately (no hysteresis on entering/leaving
980        // the baseline path).
981        if matches!(reason, PaneStrategyReason::NoHistoryRequired)
982            || previous == PaneMemoryStrategy::Baseline
983        {
984            return self.decision(fresh, reason, forced, profile);
985        }
986        let decisive = if fresh == PaneMemoryStrategy::Persistent {
987            // Entering persistent: EVERY gate must clear by a margin, not just
988            // the local-fraction threshold. Leaving is decisive on any failed
989            // hard gate, so a marginless entry would let burst/op-count jitter
990            // right at a hard gate flip the strategy every window — the exact
991            // oscillation hysteresis exists to prevent. Hard-gate margins are
992            // proportional (10%).
993            let burst_margin = self.persistent_burst_ops_per_sec / 10;
994            let ops_margin = self.persistent_min_operations / 10;
995            self.favors_persistent(profile, self.hysteresis_pct)
996                && profile.peak_ops_per_sec
997                    >= self
998                        .persistent_burst_ops_per_sec
999                        .saturating_add(burst_margin)
1000                && profile.operation_count
1001                    >= self.persistent_min_operations.saturating_add(ops_margin)
1002        } else {
1003            // Leaving persistent: a failed hard gate is decisive; otherwise the
1004            // local fraction must drop below the threshold by the margin.
1005            profile.operation_count < self.persistent_min_operations
1006                || profile.peak_ops_per_sec < self.persistent_burst_ops_per_sec
1007                || profile.local_fraction_pct()
1008                    < self
1009                        .persistent_local_fraction_pct
1010                        .saturating_sub(self.hysteresis_pct)
1011        };
1012        if decisive {
1013            self.decision(fresh, reason, forced, profile)
1014        } else {
1015            self.decision(previous, PaneStrategyReason::HysteresisHold, false, profile)
1016        }
1017    }
1018
1019    fn decide(
1020        &self,
1021        profile: PaneWorkloadProfile,
1022    ) -> (PaneMemoryStrategy, PaneStrategyReason, bool) {
1023        if let Some(forced) = self.forced_strategy {
1024            return (forced, PaneStrategyReason::ForcedOverride, true);
1025        }
1026        if self.conservative {
1027            return (
1028                PaneMemoryStrategy::Checkpointed,
1029                PaneStrategyReason::ConservativeFallback,
1030                true,
1031            );
1032        }
1033        if !profile.history_required {
1034            return (
1035                PaneMemoryStrategy::Baseline,
1036                PaneStrategyReason::NoHistoryRequired,
1037                false,
1038            );
1039        }
1040        if self.favors_persistent(profile, 0) {
1041            return (
1042                PaneMemoryStrategy::Persistent,
1043                PaneStrategyReason::ResizeDominatedBurst,
1044                false,
1045            );
1046        }
1047        (
1048            PaneMemoryStrategy::Checkpointed,
1049            PaneStrategyReason::GeneralDefault,
1050            false,
1051        )
1052    }
1053
1054    fn favors_persistent(&self, profile: PaneWorkloadProfile, local_margin_pct: u32) -> bool {
1055        profile.operation_count >= self.persistent_min_operations
1056            && profile.local_fraction_pct()
1057                >= self
1058                    .persistent_local_fraction_pct
1059                    .saturating_add(local_margin_pct)
1060            && profile.peak_ops_per_sec >= self.persistent_burst_ops_per_sec
1061    }
1062
1063    fn decision(
1064        &self,
1065        strategy: PaneMemoryStrategy,
1066        reason: PaneStrategyReason,
1067        forced: bool,
1068        profile: PaneWorkloadProfile,
1069    ) -> PaneExecutionDecision {
1070        let log = format!(
1071            "execution[{}] {}: ops={} local={}% burst={}/s history={} (thresholds: min_ops={} local>={}% burst>={}/s hysteresis={}%{}); retention budget bytes={} units={}",
1072            strategy.as_str(),
1073            reason.as_str(),
1074            profile.operation_count,
1075            profile.local_fraction_pct(),
1076            profile.peak_ops_per_sec,
1077            profile.history_required,
1078            self.persistent_min_operations,
1079            self.persistent_local_fraction_pct,
1080            self.persistent_burst_ops_per_sec,
1081            self.hysteresis_pct,
1082            if forced { ", forced" } else { "" },
1083            self.retention.budget.max_retained_bytes,
1084            self.retention.budget.max_retained_units,
1085        );
1086        PaneExecutionDecision {
1087            strategy,
1088            reason,
1089            forced,
1090            profile,
1091            retention: self.retention,
1092            log,
1093        }
1094    }
1095}
1096
1097/// A deterministic, auditable strategy-selection decision.
1098#[derive(Debug, Clone, PartialEq, serde::Serialize)]
1099pub struct PaneExecutionDecision {
1100    /// The selected execution strategy.
1101    pub strategy: PaneMemoryStrategy,
1102    /// Why it was selected.
1103    pub reason: PaneStrategyReason,
1104    /// Whether an operator override produced this decision.
1105    pub forced: bool,
1106    /// The workload profile the decision was made against.
1107    pub profile: PaneWorkloadProfile,
1108    /// The retention policy to apply alongside the selected strategy.
1109    pub retention: PaneRetentionPolicy,
1110    /// Human-readable one-line decision trace.
1111    pub log: String,
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116    use super::*;
1117    use crate::pane::{
1118        PaneId, PaneInteractionTimeline, PaneLeaf, PaneOperation, PanePlacement, PaneSplitRatio,
1119        PaneTree, SplitAxis,
1120    };
1121    use crate::pane_persistent::{PaneVersionStore, VersionedPaneTree};
1122
1123    fn policy() -> PaneExecutionPolicy {
1124        PaneExecutionPolicy::adaptive(PaneRetentionPolicy::bounded(500_000, 64))
1125    }
1126
1127    fn resize_storm_profile() -> PaneWorkloadProfile {
1128        // 512 ops, all local (a pure drag-resize storm), bursty.
1129        PaneWorkloadProfile::new(512, 512, 240, true)
1130    }
1131
1132    fn mixed_profile() -> PaneWorkloadProfile {
1133        // 384 ops, ~55% local, moderate rate.
1134        PaneWorkloadProfile::new(384, 211, 40, true)
1135    }
1136
1137    #[test]
1138    fn live_policy_change_is_deferred_until_gesture_ends() {
1139        let mut tree = PaneTree::singleton("live");
1140        let mut engine = PaneExecutionEngine::new(&tree);
1141        let forced = PaneExecutionPolicy::adaptive(PaneRetentionPolicy::unbounded())
1142            .forcing(PaneMemoryStrategy::Persistent);
1143        engine.set_policy(&tree, forced).unwrap();
1144        engine.begin_gesture();
1145        engine.set_policy(&tree, forced.conservative()).unwrap();
1146        assert_eq!(engine.strategy(), PaneMemoryStrategy::Persistent);
1147        assert!(!engine.status().conservative);
1148        let root = tree.root();
1149        engine
1150            .apply_and_record(
1151                &mut tree,
1152                1,
1153                1,
1154                PaneOperation::SplitLeaf {
1155                    target: root,
1156                    axis: SplitAxis::Horizontal,
1157                    ratio: PaneSplitRatio::new(1, 1).unwrap(),
1158                    new_leaf: PaneLeaf::new("second"),
1159                    placement: PanePlacement::ExistingFirst,
1160                },
1161            )
1162            .unwrap();
1163        assert_eq!(engine.status().persistent_applies, 1);
1164        let accepted = tree.to_snapshot();
1165        engine.end_gesture(&tree).unwrap();
1166        assert_eq!(tree.to_snapshot(), accepted);
1167        assert_eq!(engine.strategy(), PaneMemoryStrategy::Checkpointed);
1168        assert!(engine.status().conservative);
1169        assert!(engine.undo(&mut tree).unwrap());
1170        assert_eq!(
1171            tree.to_snapshot(),
1172            PaneTree::singleton("live").to_snapshot()
1173        );
1174    }
1175
1176    #[test]
1177    fn failed_maintenance_preserves_accepted_edit_and_previous_substrate() {
1178        let mut tree = PaneTree::singleton("live");
1179        let mut engine = PaneExecutionEngine::new(&tree);
1180        engine.set_latency_envelope_ns(1);
1181        engine
1182            .set_policy(
1183                &tree,
1184                PaneExecutionPolicy::adaptive(PaneRetentionPolicy::unbounded())
1185                    .forcing(PaneMemoryStrategy::Persistent),
1186            )
1187            .unwrap();
1188        engine
1189            .apply_and_record(&mut tree, 1, 1, PaneOperation::NormalizeRatios)
1190            .unwrap();
1191        let accepted = tree.to_snapshot();
1192        // A corrupted journal hash must prevent fallback publication rather
1193        // than blessing the journal or rolling back the already accepted edit.
1194        engine.timeline.entries[0].after_hash ^= 1;
1195        let journal = engine.timeline.clone();
1196        let status = engine.status.clone();
1197        assert!(
1198            engine
1199                .observe(
1200                    &tree,
1201                    PaneExecutionSample {
1202                        timestamp_ns: 1,
1203                        elapsed_ns: 2,
1204                        local: false
1205                    }
1206                )
1207                .is_err()
1208        );
1209        assert_eq!(tree.to_snapshot(), accepted);
1210        assert_eq!(engine.timeline, journal);
1211        assert_eq!(engine.strategy(), PaneMemoryStrategy::Persistent);
1212        assert_eq!(engine.status.applies, status.applies);
1213        assert_eq!(engine.status.switches, status.switches);
1214        assert!(engine.status.last_maintenance_error.is_some());
1215        assert_eq!(engine.replay().unwrap().to_snapshot(), accepted);
1216    }
1217
1218    #[test]
1219    fn equal_observation_timestamps_do_not_invent_a_burst_rate() {
1220        let tree = PaneTree::singleton("live");
1221        let mut engine = PaneExecutionEngine::new(&tree);
1222        for _ in 0..128 {
1223            engine
1224                .observe(
1225                    &tree,
1226                    PaneExecutionSample {
1227                        timestamp_ns: 1,
1228                        elapsed_ns: 0,
1229                        local: true,
1230                    },
1231                )
1232                .unwrap();
1233        }
1234        assert_eq!(engine.profile().peak_ops_per_sec, 0);
1235        assert_eq!(engine.strategy(), PaneMemoryStrategy::Checkpointed);
1236    }
1237
1238    #[test]
1239    fn live_pairing_distinguishes_raw_ratios_with_equal_semantic_hashes() {
1240        let mut original = PaneTree::singleton("original");
1241        for id in 1..=2 {
1242            original
1243                .apply_operation(
1244                    id,
1245                    PaneOperation::SplitLeaf {
1246                        target: PaneId::MIN,
1247                        axis: SplitAxis::Horizontal,
1248                        ratio: PaneSplitRatio::new(1, 1).unwrap(),
1249                        placement: PanePlacement::ExistingFirst,
1250                        new_leaf: PaneLeaf::new(format!("sibling-{id}")),
1251                    },
1252                )
1253                .unwrap();
1254        }
1255        let untouched_split = original.root();
1256        let mut alias = original.to_snapshot();
1257        let record = alias
1258            .nodes
1259            .iter_mut()
1260            .find(|record| record.id == untouched_split)
1261            .unwrap();
1262        let crate::pane::PaneNodeKind::Split(split) = &mut record.kind else {
1263            panic!("split root");
1264        };
1265        split.ratio = serde_json::from_str(r#"{"numerator":0,"denominator":1}"#).unwrap();
1266        let alias = PaneTree::from_snapshot(alias).unwrap();
1267        assert_eq!(original.state_hash(), alias.state_hash());
1268        assert_ne!(original.to_snapshot(), alias.to_snapshot());
1269        let resized = original
1270            .nodes()
1271            .find(|record| {
1272                record.id != untouched_split
1273                    && matches!(record.kind, crate::pane::PaneNodeKind::Split(_))
1274            })
1275            .unwrap()
1276            .id;
1277        let operation = PaneOperation::SetSplitRatio {
1278            split: resized,
1279            ratio: PaneSplitRatio::new(2, 3).unwrap(),
1280        };
1281        for strategy in [
1282            PaneMemoryStrategy::Persistent,
1283            PaneMemoryStrategy::Checkpointed,
1284        ] {
1285            let policy =
1286                PaneExecutionPolicy::adaptive(PaneRetentionPolicy::unbounded()).forcing(strategy);
1287            let mut engine = PaneExecutionEngine::new(&original);
1288            engine.set_policy(&original, policy).unwrap();
1289            let mut substituted = alias.clone();
1290            let before = engine.timeline().clone();
1291            assert!(matches!(
1292                engine.apply_and_record(&mut substituted, 3, 3, operation.clone()),
1293                Err(PaneExecutionError::InvalidHistory(_))
1294            ));
1295            assert_eq!(substituted, alias);
1296            assert_eq!(engine.timeline(), &before);
1297            assert_eq!(engine.status().applies, 0);
1298
1299            // The same raw state is valid when imported as the actual baseline.
1300            // Editing a different split must retain its exact representation.
1301            let mut engine = PaneExecutionEngine::new(&alias);
1302            engine.set_policy(&alias, policy).unwrap();
1303            let mut live = alias.clone();
1304            let mut canonical = alias.clone();
1305            let expected = canonical.apply_operation(3, operation.clone()).unwrap();
1306            assert_eq!(
1307                engine
1308                    .apply_and_record(&mut live, 3, 3, operation.clone())
1309                    .unwrap(),
1310                expected
1311            );
1312            assert_eq!(live.to_snapshot(), canonical.to_snapshot());
1313            assert_eq!(
1314                engine.replay().unwrap().to_snapshot(),
1315                canonical.to_snapshot()
1316            );
1317        }
1318    }
1319
1320    #[test]
1321    fn selection_is_deterministic() {
1322        let p = policy();
1323        let profile = resize_storm_profile();
1324        assert_eq!(p.select(profile), p.select(profile));
1325    }
1326
1327    #[test]
1328    fn resize_storm_selects_persistent() {
1329        let d = policy().select(resize_storm_profile());
1330        assert_eq!(d.strategy, PaneMemoryStrategy::Persistent);
1331        assert_eq!(d.reason, PaneStrategyReason::ResizeDominatedBurst);
1332        assert!(!d.forced);
1333    }
1334
1335    #[test]
1336    fn mixed_workload_falls_back_to_checkpointed() {
1337        let d = policy().select(mixed_profile());
1338        assert_eq!(d.strategy, PaneMemoryStrategy::Checkpointed);
1339        assert_eq!(d.reason, PaneStrategyReason::GeneralDefault);
1340    }
1341
1342    #[test]
1343    fn no_history_selects_baseline() {
1344        let profile = PaneWorkloadProfile::new(512, 512, 240, false);
1345        let d = policy().select(profile);
1346        assert_eq!(d.strategy, PaneMemoryStrategy::Baseline);
1347        assert_eq!(d.reason, PaneStrategyReason::NoHistoryRequired);
1348    }
1349
1350    #[test]
1351    fn shallow_resize_storm_stays_checkpointed() {
1352        // Resize-dominated and bursty, but below the depth where persistent pays.
1353        let profile = PaneWorkloadProfile::new(32, 32, 240, true);
1354        assert_eq!(
1355            policy().select(profile).strategy,
1356            PaneMemoryStrategy::Checkpointed
1357        );
1358    }
1359
1360    #[test]
1361    fn forced_strategy_overrides_adaptation() {
1362        // A mixed workload would pick checkpointed, but force persistent.
1363        let forced = policy().forcing(PaneMemoryStrategy::Persistent);
1364        let d = forced.select(mixed_profile());
1365        assert_eq!(d.strategy, PaneMemoryStrategy::Persistent);
1366        assert_eq!(d.reason, PaneStrategyReason::ForcedOverride);
1367        assert!(d.forced);
1368    }
1369
1370    #[test]
1371    fn conservative_forces_checkpointed_even_on_resize_storm() {
1372        let conservative = policy().conservative();
1373        let d = conservative.select(resize_storm_profile());
1374        assert_eq!(d.strategy, PaneMemoryStrategy::Checkpointed);
1375        assert_eq!(d.reason, PaneStrategyReason::ConservativeFallback);
1376        assert!(d.forced);
1377    }
1378
1379    #[test]
1380    fn hysteresis_prevents_thrashing_near_threshold() {
1381        let p = policy();
1382        // Local fraction exactly at the entry threshold (80%): a fresh select
1383        // would pick persistent, but reselect from checkpointed needs +margin.
1384        let at_threshold = PaneWorkloadProfile::new(512, 410, 240, true); // 80%
1385        assert_eq!(
1386            p.select(at_threshold).strategy,
1387            PaneMemoryStrategy::Persistent
1388        );
1389        assert_eq!(
1390            p.reselect(at_threshold, PaneMemoryStrategy::Checkpointed)
1391                .strategy,
1392            PaneMemoryStrategy::Checkpointed,
1393            "should not enter persistent without clearing the hysteresis margin"
1394        );
1395
1396        // A decisive resize storm (95% local) does enter persistent.
1397        let decisive = PaneWorkloadProfile::new(512, 487, 240, true); // 95%
1398        let entered = p.reselect(decisive, PaneMemoryStrategy::Checkpointed);
1399        assert_eq!(entered.strategy, PaneMemoryStrategy::Persistent);
1400        assert_eq!(entered.reason, PaneStrategyReason::ResizeDominatedBurst);
1401
1402        // Once persistent, a mild dip (75% — within the margin) holds persistent.
1403        let mild_dip = PaneWorkloadProfile::new(512, 384, 240, true); // 75%
1404        let held = p.reselect(mild_dip, PaneMemoryStrategy::Persistent);
1405        assert_eq!(held.strategy, PaneMemoryStrategy::Persistent);
1406        assert_eq!(held.reason, PaneStrategyReason::HysteresisHold);
1407
1408        // A decisive drop (65% — below threshold - margin) leaves persistent.
1409        let decisive_drop = PaneWorkloadProfile::new(512, 332, 240, true); // 64%
1410        assert_eq!(
1411            p.reselect(decisive_drop, PaneMemoryStrategy::Persistent)
1412                .strategy,
1413            PaneMemoryStrategy::Checkpointed
1414        );
1415    }
1416
1417    #[test]
1418    fn hard_gate_jitter_does_not_oscillate() {
1419        // Burst rate jittering right at the hard gate (59 <-> 60/s) must not
1420        // flip Persistent <-> Checkpointed every window: leaving on a failed
1421        // hard gate is decisive, so re-entry must clear the gate by a margin
1422        // (>= 66/s at the default 60/s threshold), not merely touch it.
1423        let p = policy();
1424        let below_gate = PaneWorkloadProfile::new(512, 512, 59, true);
1425        let at_gate = PaneWorkloadProfile::new(512, 512, 60, true);
1426        let clears_gate = PaneWorkloadProfile::new(512, 512, 66, true);
1427
1428        // Below the gate: leaving persistent is decisive.
1429        assert_eq!(
1430            p.reselect(below_gate, PaneMemoryStrategy::Persistent)
1431                .strategy,
1432            PaneMemoryStrategy::Checkpointed
1433        );
1434        // Back at (but not clearing) the gate: re-entry is refused — held.
1435        let held = p.reselect(at_gate, PaneMemoryStrategy::Checkpointed);
1436        assert_eq!(held.strategy, PaneMemoryStrategy::Checkpointed);
1437        assert_eq!(held.reason, PaneStrategyReason::HysteresisHold);
1438        // Clearing the gate by the 10% margin enters persistent.
1439        assert_eq!(
1440            p.reselect(clears_gate, PaneMemoryStrategy::Checkpointed)
1441                .strategy,
1442            PaneMemoryStrategy::Persistent
1443        );
1444    }
1445
1446    #[test]
1447    fn observe_classifies_local_operations() {
1448        let ops = vec![
1449            PaneOperation::SetSplitRatio {
1450                split: PaneId::new(2).unwrap(),
1451                ratio: PaneSplitRatio::new(1, 1).unwrap(),
1452            },
1453            PaneOperation::SetSplitRatio {
1454                split: PaneId::new(2).unwrap(),
1455                ratio: PaneSplitRatio::new(2, 1).unwrap(),
1456            },
1457            PaneOperation::CloseNode {
1458                target: PaneId::new(3).unwrap(),
1459            },
1460        ];
1461        let profile = PaneWorkloadProfile::observe(&ops, 120, true);
1462        assert_eq!(profile.operation_count, 3);
1463        assert_eq!(profile.local_operation_count, 2);
1464        assert_eq!(profile.local_fraction_pct(), 66);
1465    }
1466
1467    /// The headline safety guarantee: whichever strategy the selector picks, the
1468    /// observable result (final state hash) is identical — the candidates are
1469    /// proven equivalent, so selection changes cost, never behavior.
1470    #[test]
1471    fn strategy_choice_never_diverges_behavior() {
1472        let ratio = |n, d| PaneSplitRatio::new(n, d).expect("ratio");
1473        let mut ops = vec![
1474            PaneOperation::SplitLeaf {
1475                target: PaneId::MIN,
1476                axis: SplitAxis::Horizontal,
1477                ratio: ratio(1, 1),
1478                placement: PanePlacement::ExistingFirst,
1479                new_leaf: PaneLeaf::new("b"),
1480            },
1481            PaneOperation::SplitLeaf {
1482                target: PaneId::MIN,
1483                axis: SplitAxis::Vertical,
1484                ratio: ratio(2, 1),
1485                placement: PanePlacement::ExistingFirst,
1486                new_leaf: PaneLeaf::new("c"),
1487            },
1488        ];
1489        let split = PaneId::new(4).expect("id");
1490        for n in 1..=12u32 {
1491            ops.push(PaneOperation::SetSplitRatio {
1492                split,
1493                ratio: ratio(n % 5 + 1, 1),
1494            });
1495        }
1496
1497        // Baseline: a plain tree.
1498        let mut baseline = PaneTree::singleton("root");
1499        for (i, op) in ops.iter().enumerate() {
1500            baseline
1501                .apply_operation_conservative(i as u64 + 1, op.clone())
1502                .expect("baseline apply");
1503        }
1504        // Checkpointed timeline.
1505        let mut tree = PaneTree::singleton("root");
1506        let mut timeline = PaneInteractionTimeline::default();
1507        for (i, op) in ops.iter().enumerate() {
1508            let id = i as u64;
1509            timeline
1510                .apply_and_record(&mut tree, id, id, op.clone())
1511                .expect("timeline apply");
1512        }
1513        // Persistent store.
1514        let mut store = PaneVersionStore::new(VersionedPaneTree::singleton("root"));
1515        for op in &ops {
1516            store.apply(op).expect("store apply");
1517        }
1518
1519        let baseline_hash = baseline.state_hash();
1520        let timeline_hash = tree.state_hash();
1521        let store_hash = store.current().state_hash().expect("hash");
1522        assert_eq!(baseline_hash, timeline_hash);
1523        assert_eq!(baseline_hash, store_hash);
1524
1525        // And the selector picks among exactly these equivalent substrates.
1526        let profile = PaneWorkloadProfile::observe(&ops, 240, true);
1527        let strategy = policy().select(profile).strategy;
1528        assert!(matches!(
1529            strategy,
1530            PaneMemoryStrategy::Baseline
1531                | PaneMemoryStrategy::Checkpointed
1532                | PaneMemoryStrategy::Persistent
1533        ));
1534    }
1535}