draftwright 0.6.0

Dimensioned engineering drawings from STEP, with SVG, PDF and editable DXF output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Preparation shared by sheet-search candidates during one immutable planning call.
//! Exact cross-call results use bounded memos with short lock scopes.
//! Sessions may retain bounded preparation for the same Analysis across calls; each memo key
//! still describes all additional inputs, including the Spec for planned candidates.

use sha2::{Digest, Sha256};
use std::any::Any;
use std::cell::RefCell;
use std::collections::{BTreeMap, VecDeque};
use std::rc::Rc;
use std::sync::{Arc, Mutex};

use crate::model::Analysis;

type Values = BTreeMap<(&'static str, Vec<u8>), (u64, Box<dyn Any>)>;

#[derive(Clone)]
struct Active {
    analysis: usize,
    values: Rc<RefCell<Values>>,
}

thread_local! {
    static AGE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    static ACTIVE: RefCell<Option<Active>> = const { RefCell::new(None) };
    static FIXED_PAIR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static EXPLICIT_TRIAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static LANE_LADDER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static TRIAL_RADIUS_REFERENCE: RefCell<Option<(crate::model::Plan, [u8; 32])>> = const { RefCell::new(None) };
    static PIN_REFERENCE: RefCell<Option<(Arc<crate::model::Plan>, [u8; 32])>> = const { RefCell::new(None) };
    static DEFER_NOMINALS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static LANE_TRIAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// The second attempt at a sheet and scale as a trial ([`crate::sheet_policy::lane_attempt`]):
/// planning may stop as soon as its sizing finds the ladder at lane pitch no more room than the
/// slots, since the drawing would then be the first attempt's again. A replay of a drawing that
/// attempt made ([`lane_ladder`] alone) is not a trial, and is drawn through.
pub(crate) fn lane_trial<T>(run: impl FnOnce() -> T) -> T {
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            LANE_TRIAL.set(self.0);
        }
    }
    let _restore = Restore(LANE_TRIAL.replace(true));
    run()
}

pub(crate) fn is_lane_trial() -> bool {
    LANE_TRIAL.get()
}

/// Recovery helpers can compare intermediate presentations without polishing
/// each one. The public allocator finishes the selected presentation once.
pub(crate) fn defer_nominals<T>(run: impl FnOnce() -> T) -> T {
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            DEFER_NOMINALS.set(self.0);
        }
    }
    let _restore = Restore(DEFER_NOMINALS.replace(true));
    run()
}

pub(crate) fn nominals_deferred() -> bool {
    DEFER_NOMINALS.get()
}

/// A bounded automatic sheet trial: use the ordinary automatic candidate's
/// presentation, but do not search for a suggested paper/scale fix on rejection.
pub(crate) fn fixed_pair<T>(run: impl FnOnce() -> T) -> T {
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            FIXED_PAIR.set(self.0);
        }
    }
    let _restore = Restore(FIXED_PAIR.replace(true));
    run()
}

/// A sheet trial's second attempt at a sheet and scale its first drawing does not fit: the
/// height ladder is reserved at the lane pitch where draftwright's slots do not fit the pair
/// ([`crate::demand::size_with_details`]). Every planning memo is keyed by it.
pub(crate) fn lane_ladder<T>(run: impl FnOnce() -> T) -> T {
    with_lane_ladder(true, run)
}

/// Planning that is not that second attempt even when it is reached from one: the established
/// route template is one drawing, whatever ladder the candidate reserves.
pub(crate) fn slot_ladder<T>(run: impl FnOnce() -> T) -> T {
    with_lane_ladder(false, run)
}

fn with_lane_ladder<T>(on: bool, run: impl FnOnce() -> T) -> T {
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            LANE_LADDER.set(self.0);
        }
    }
    let _restore = Restore(LANE_LADDER.replace(on));
    run()
}

pub(crate) fn is_lane_ladder() -> bool {
    LANE_LADDER.get()
}

/// Replay the user's explicit-pair presentation within an automatic paper trial.
pub(crate) fn explicit_pair<T>(run: impl FnOnce() -> T) -> T {
    struct Restore(bool, bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            FIXED_PAIR.set(self.0);
            EXPLICIT_TRIAL.set(self.1);
        }
    }
    let _restore = Restore(FIXED_PAIR.replace(false), EXPLICIT_TRIAL.replace(true));
    run()
}

pub(crate) fn bounded_pair() -> bool {
    is_fixed_pair() || EXPLICIT_TRIAL.get()
}

/// A paper trial retains the author's unedited radius corridors. Rebuilding
/// that reference with the trial's forced paper would choose different anchors.
pub(crate) fn fixed_pair_with_radius_reference<T>(
    reference: Option<&crate::model::Plan>,
    run: impl FnOnce() -> T,
) -> T {
    struct Restore(Option<(crate::model::Plan, [u8; 32])>);
    impl Drop for Restore {
        fn drop(&mut self) {
            TRIAL_RADIUS_REFERENCE.with(|r| *r.borrow_mut() = self.0.take());
        }
    }
    let reference = reference.map(|reference| {
        let key: [u8; 32] =
            Sha256::digest(serde_json::to_vec(reference).expect("radius reference serializes"))
                .into();
        (reference.clone(), key)
    });
    let _restore = Restore(TRIAL_RADIUS_REFERENCE.with(|r| r.replace(reference)));
    fixed_pair(run)
}

pub(crate) fn trial_radius_reference() -> Option<crate::model::Plan> {
    TRIAL_RADIUS_REFERENCE.with(|r| r.borrow().as_ref().map(|r| r.0.clone()))
}

/// A pin replay keeps the published schedule while its forced paper trials
/// replan the remaining annotations. Restore the reference on every exit.
pub(crate) fn with_pin_reference<T>(reference: crate::model::Plan, run: impl FnOnce() -> T) -> T {
    struct Restore(Option<(Arc<crate::model::Plan>, [u8; 32])>);
    impl Drop for Restore {
        fn drop(&mut self) {
            PIN_REFERENCE.with(|r| *r.borrow_mut() = self.0.take());
        }
    }
    let key =
        Sha256::digest(serde_json::to_vec(&reference).expect("pin reference serializes")).into();
    let _restore = Restore(PIN_REFERENCE.with(|r| r.replace(Some((Arc::new(reference), key)))));
    run()
}

pub(crate) struct SuspendedReference(Option<(Arc<crate::model::Plan>, [u8; 32])>);
pub(crate) fn suspend_pin_reference() -> SuspendedReference {
    SuspendedReference(PIN_REFERENCE.with(|r| r.take()))
}
impl Drop for SuspendedReference {
    fn drop(&mut self) {
        PIN_REFERENCE.with(|r| *r.borrow_mut() = self.0.take());
    }
}

pub(crate) fn pin_reference_shared() -> Option<Arc<crate::model::Plan>> {
    PIN_REFERENCE.with(|r| r.borrow().as_ref().map(|r| r.0.clone()))
}

pub(crate) fn pin_reference() -> Option<Arc<crate::model::Plan>> {
    pin_reference_shared()
}

pub(crate) fn is_fixed_pair() -> bool {
    FIXED_PAIR.get() && !crate::nominal::comparison()
}

type Retained = VecDeque<([u8; 32], Rc<RefCell<Values>>)>;
thread_local! {
    // Four complete input sets, only for interactive sessions. Ordinary planning and its
    // timing calibration keep the existing per-call lifetime. No raw pointer survives a call.
    static RETAINED: RefCell<Retained> = const { RefCell::new(VecDeque::new()) };
}

/// Preview and commit often have identical inputs. Keep their pure preparation bounded and
/// bound to the entire Analysis, including recognition. Spec-dependent candidates already
/// key on the complete Spec; Analysis-only preparation can also survive a title edit. Every
/// invocation still runs the recovered planner. Oversized scopes are cleared on re-entry,
/// bounding retention by 256 entries plus the existing single-call planning budget.
pub(crate) fn with_retained<T>(analysis: &Analysis, run: impl FnOnce() -> T) -> T {
    let key: [u8; 32] =
        // Invariant: Document fields and map keys have JSON representations; serialization performs no external I/O.
        Sha256::digest(serde_json::to_vec(analysis).expect("analysis serializes")).into();
    let values = RETAINED.with(|retained| {
        let mut retained = retained.borrow_mut();
        let values = retained
            .iter()
            .position(|(k, _)| *k == key)
            .and_then(|i| retained.remove(i))
            .map(|(_, values)| values)
            .unwrap_or_else(|| Rc::new(RefCell::new(BTreeMap::new())));
        if values.borrow().len() > 256 {
            // Keep at most four paper choices/bounded result-cache containers,
            // dropping larger per-trial preparation. Each pin container owns at
            // most four exact results, independently of preparation eviction.
            let mut values = values.borrow_mut();
            values.retain(|(name, _), _| matches!(*name, "selected-paper" | "engine-pins-plan"));
            while values.len() > 4 {
                let oldest = values
                    .iter()
                    .min_by_key(|(_, (age, _))| age)
                    .map(|(key, _)| key.clone())
                    .expect("nonempty retained preparation");
                values.remove(&oldest);
            }
        }
        // These are policies activated by this invocation, not immutable preparation.
        // Keeping them from a previous automatic plan changes explicit-scale edits.
        // The expensive prepared reference remains cached under its separate key.
        values.borrow_mut().retain(|(name, _), _| !activated(name));
        retained.push_front((key, values.clone()));
        retained.truncate(4);
        values
    });
    let previous = ACTIVE.with(|active| {
        active.replace(Some(Active {
            analysis: analysis as *const Analysis as usize,
            values,
        }))
    });
    let _scope = Scope(previous);
    crate::geometry_ids::with(analysis, run)
}

struct Scope(Option<Active>);

impl Drop for Scope {
    fn drop(&mut self) {
        ACTIVE.with(|active| *active.borrow_mut() = self.0.take());
    }
}

pub(crate) fn with<T>(analysis: &Analysis, run: impl FnOnce() -> T) -> T {
    let identity = analysis as *const Analysis as usize;
    let previous = ACTIVE.with(|active| {
        let mut active = active.borrow_mut();
        let previous = active.clone();
        if active.as_ref().is_none_or(|a| a.analysis != identity) {
            *active = Some(Active {
                analysis: identity,
                values: Rc::new(RefCell::new(BTreeMap::new())),
            });
        }
        previous
    });
    let _scope = Scope(previous);
    crate::geometry_ids::with(analysis, run)
}

/// A comparison has different printed wants and layout policy even though its
/// geometric input is identical. Keep its preparation out of the live scope.
pub(crate) fn isolated<T>(analysis: &Analysis, run: impl FnOnce() -> T) -> T {
    let previous = ACTIVE.with(|active| active.replace(None));
    let _scope = Scope(previous);
    with(analysis, run)
}

fn next_age() -> u64 {
    AGE.with(|age| {
        let next = age.get() + 1;
        age.set(next);
        next
    })
}

/// The address is used only while `with` borrows that Analysis, never across calls.
/// Keys describe every additional input. Ordinary scopes end with the call; session scopes
/// retain only entries bound to the complete Analysis, with all other inputs in each key.
pub(crate) fn memo<T: Clone + 'static>(
    analysis: &Analysis,
    name: &'static str,
    key: Vec<u8>,
    prepare: impl FnOnce() -> T,
) -> T {
    let values = ACTIVE.with(|active| {
        active
            .borrow()
            .as_ref()
            .filter(|a| a.analysis == analysis as *const Analysis as usize)
            .map(|a| a.values.clone())
    });
    let Some(values) = values else {
        return prepare();
    };
    let key = (name, held(name, key));
    if let Some(value) = values.borrow().get(&key) {
        // Invariant: Preparation keys include TypeId::of::<T>(); only T is stored for that key.
        return value
            .1
            .downcast_ref::<T>()
            .expect("preparation type")
            .clone();
    }
    let value = prepare();
    values
        .borrow_mut()
        .insert(key, (next_age(), Box::new(value.clone())));
    value
}

pub(crate) fn lookup<T: Clone + 'static>(
    analysis: &Analysis,
    name: &'static str,
    key: &[u8],
) -> Option<T> {
    ACTIVE.with(|active| {
        let active = active.borrow();
        let active = active
            .as_ref()
            .filter(|a| a.analysis == analysis as *const Analysis as usize)?;
        active
            .values
            .borrow()
            .get(&(name, held(name, key.to_vec())))
            // Invariant: Preparation keys include TypeId::of::<T>(); only T is stored for that key.
            .map(|v| v.1.downcast_ref::<T>().expect("preparation type").clone())
    })
}

pub(crate) fn store<T: 'static>(analysis: &Analysis, name: &'static str, key: Vec<u8>, value: T) {
    ACTIVE.with(|active| {
        if let Some(active) = active
            .borrow()
            .as_ref()
            .filter(|a| a.analysis == analysis as *const Analysis as usize)
        {
            active
                .values
                .borrow_mut()
                .insert((name, held(name, key)), (next_age(), Box::new(value)));
        }
    });
}

pub(crate) fn enabled(analysis: &Analysis) -> bool {
    ACTIVE.with(|active| {
        active
            .borrow()
            .as_ref()
            .is_some_and(|a| a.analysis == analysis as *const Analysis as usize)
    })
}

/// The policies a planning invocation activates, as opposed to its immutable preparation.
fn activated(name: &str) -> bool {
    matches!(
        name,
        "established-drawing"
            | "established-route-policy"
            | "established-clear-witnesses"
            | "canonical-interior-statements"
    )
}

/// The key a looked-up or stored value is held under. A second attempt at a sheet and scale
/// ([`lane_ladder`]) changes that attempt's sizing, not what the selection established, so it
/// reads and writes the selection's policies: a first attempt read from the shared memos
/// activates none of its own, and the two attempts must not then be routed differently.
fn held(name: &str, key: Vec<u8>) -> Vec<u8> {
    // These readers consume only Analysis and their explicit geometric keys.
    // A published layout reference changes placement, never this preparation.
    if matches!(
        name,
        "analysis_digest"
            | "lowered-pmi"
            | "v_notches"
            | "inspection-datum"
            | "projected-model-index"
            | "projected-feature-footprints"
    ) {
        return key;
    }
    if activated(name) {
        slot_ladder(|| spaced(key, name == "radius-edit-reference"))
    } else {
        spaced(key, name == "radius-edit-reference")
    }
}

/// Compact dimension spacing ([`crate::dims::compact`]) and a non-default frame gutter
/// ([`crate::layout::gutter`]) change placements, so they key every planning memo: default
/// keys are unchanged and the others are kept apart.
fn spaced(mut key: Vec<u8>, reference_matters: bool) -> Vec<u8> {
    if let Some(pins) = crate::engine_pins::digest() {
        key.extend_from_slice(b"\xffengine-pins");
        key.extend_from_slice(&pins);
    }
    if let Some(context) = retained_digest(reference_matters) {
        key.extend_from_slice(b"\xffretained-layout");
        key.extend_from_slice(&context);
    }
    if crate::dims::compact() {
        // 0xFF never occurs in the UTF-8 JSON keys, and closes any raw byte key.
        key.extend_from_slice(b"\xffcompact-spacing");
    }
    let gutter = crate::layout::gutter();
    if gutter != crate::layout::FRAME_GUTTER {
        key.extend_from_slice(b"\xffframe-gutter");
        key.extend_from_slice(&gutter.to_bits().to_le_bytes());
    }
    if is_lane_ladder() {
        key.extend_from_slice(b"\xfflane-ladder");
    }
    key
}

/// All policies that can alter a retained solve, without changing ordinary keys.
fn retained_digest(reference_matters: bool) -> Option<[u8; 32]> {
    // Ordinary preparation already states its layout dependencies explicitly:
    // candidate/finished-plan/dimension placement include policy_key (the reference
    // digest), while geometry and idle-view selection do not consume that reference.
    // Radius-reference preparation predates policy_key and opts in separately.
    // Incremental preparation must still distinguish every hidden retained input.
    let retained = crate::incremental::active() || crate::engine_pins::loading();
    let reference = (reference_matters || retained)
        .then(|| PIN_REFERENCE.with(|r| r.borrow().as_ref().map(|r| r.1)))
        .flatten();
    let intent = crate::incremental::context_digest();
    let proof = crate::engine_pins::reader_digest();
    if !crate::incremental::active() && reference.is_none() && intent.is_none() && proof.is_none() {
        return None;
    }
    let mut h = Sha256::new();
    h.update([u8::from(crate::incremental::active())]);
    for value in [reference, intent, proof] {
        h.update([u8::from(value.is_some())]);
        if let Some(value) = value {
            h.update(value);
        }
    }
    Some(h.finalize().into())
}

/// A cross-call digest key for a placement result, kept apart under compact spacing or a
/// non-default frame gutter. Geometric caches (projections, wrapped label text) do not use it
/// and stay shared.
pub(crate) fn spaced_digest(key: &[u8; 32]) -> [u8; 32] {
    result_digest(key, true)
}

/// A solve without authored pins cannot consume an ordinary published reference.
/// Hidden incremental state and engine-pin loading still always key its result.
pub(crate) fn unreferenced_digest(key: &[u8; 32]) -> [u8; 32] {
    result_digest(key, false)
}

fn result_digest(key: &[u8; 32], reference_matters: bool) -> [u8; 32] {
    let gutter = crate::layout::gutter();
    if !crate::dims::compact()
        && gutter == crate::layout::FRAME_GUTTER
        && !is_lane_ladder()
        && crate::engine_pins::digest().is_none()
        && retained_digest(reference_matters).is_none()
    {
        return *key;
    }
    let mut hasher = Sha256::new();
    hasher.update(key);
    if let Some(context) = retained_digest(reference_matters) {
        hasher.update(b"retained-layout");
        hasher.update(context);
    }
    if let Some(pins) = crate::engine_pins::digest() {
        hasher.update(b"engine-pins");
        hasher.update(pins);
    }
    if crate::dims::compact() {
        hasher.update(b"compact-spacing");
    }
    if gutter != crate::layout::FRAME_GUTTER {
        hasher.update(b"frame-gutter");
        hasher.update(gutter.to_bits().to_le_bytes());
    }
    if is_lane_ladder() {
        hasher.update(b"lane-ladder");
    }
    hasher.finalize().into()
}

/// Placement policies held in the planning scope are inputs to exact result caches too, as is
/// the idle view decided for the plan being made ([`crate::dims::idle_decided`]).
#[allow(clippy::type_complexity)]
pub(crate) fn policy_key(
    analysis: &Analysis,
) -> (
    bool,
    bool,
    bool,
    Option<[u8; 32]>,
    Option<[u8; 32]>,
    bool,
    Option<Option<&'static str>>,
    bool,
    bool,
    bool,
) {
    (
        lookup::<bool>(analysis, "canonical-circular-recipes", &[]).unwrap_or(false),
        lookup::<bool>(analysis, "established-route-policy", &[]).unwrap_or(false),
        crate::nominal::comparison(),
        TRIAL_RADIUS_REFERENCE.with(|r| r.borrow().as_ref().map(|r| r.1)),
        PIN_REFERENCE.with(|r| r.borrow().as_ref().map(|r| r.1)),
        crate::dims::compact(),
        crate::dims::idle_given(),
        EXPLICIT_TRIAL.get(),
        is_lane_ladder(),
        crate::incremental::active(),
    )
}

type SharedValues<T> = VecDeque<([u8; 32], Arc<T>)>;

/// Bounded exact results across immutable calls. Only reference/queue updates hold
/// the lock: cloning and destroying a large Plan must not stall other planners.
/// Pure caches use their immutable input keys directly. Placement caches must use
/// `spaced_digest`, which includes all retained-layout policies and references.
pub(crate) struct BoundedMemo<T> {
    capacity: usize,
    values: Mutex<SharedValues<T>>,
}

impl<T: Clone> BoundedMemo<T> {
    pub(crate) const fn new(capacity: usize) -> Self {
        // Invariant: Memo capacities are positive constants at all construction sites.
        assert!(capacity > 0);
        Self {
            capacity,
            values: Mutex::new(VecDeque::new()),
        }
    }

    pub(crate) fn get(&self, key: &[u8; 32]) -> Option<T> {
        let stored = self
            .values
            .lock()
            // Invariant: The memo lock protects only fixed-key lookup and Arc cloning, without user callbacks.
            .expect("planning memo lock")
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, value)| Arc::clone(value));
        stored.map(|value| value.as_ref().clone())
    }

    pub(crate) fn insert(&self, key: [u8; 32], value: T) {
        let value = Arc::new(value);
        // Invariant: The memo lock protects fixed-key deque updates; evicted values are dropped after unlocking.
        let mut values = self.values.lock().expect("planning memo lock");
        let previous = values.iter().position(|(k, _)| *k == key);
        let replaced = previous.and_then(|at| values.remove(at));
        let evicted = if values.len() == self.capacity {
            values.pop_front()
        } else {
            None
        };
        values.push_back((key, value));
        drop(values);
        drop((replaced, evicted));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Spec;

    #[test]
    fn ordinary_reference_reuses_pure_preparation_but_separates_placement() {
        let bytes = include_bytes!("../tests/fixtures/parts/plate.step");
        let (_, a) = crate::model::analyse_native_bytes("plate", bytes).unwrap();
        let reference = crate::model::plan_recovered(&a, &Spec::default()).unwrap();
        with(&a, || {
            let key = vec![37];
            assert_eq!(memo(&a, "analysis_digest", key.clone(), || 1_u8), 1);
            assert_eq!(memo(&a, "candidate", key.clone(), || 2_u8), 2);
            let candidate_key = serde_json::to_vec(&policy_key(&a)).unwrap();
            assert_eq!(memo(&a, "candidate", candidate_key.clone(), || 4_u8), 4);
            assert_eq!(memo(&a, "idle-view", key.clone(), || 5_u8), 5);
            let digest = spaced_digest(&[37; 32]);
            let unreferenced = unreferenced_digest(&[37; 32]);
            with_pin_reference(reference, || {
                assert_eq!(
                    memo::<u8>(&a, "analysis_digest", key.clone(), || panic!(
                        "pure preparation was lost"
                    )),
                    1_u8
                );
                assert_eq!(
                    memo::<u8>(&a, "idle-view", key.clone(), || panic!(
                        "idle-view preparation was lost"
                    )),
                    5
                );
                assert_ne!(
                    spaced_digest(&[37; 32]),
                    digest,
                    "shared result caches must still distinguish the reference"
                );
                assert_eq!(unreferenced_digest(&[37; 32]), unreferenced);
                let different_key = serde_json::to_vec(&policy_key(&a)).unwrap();
                assert_ne!(candidate_key, different_key);
                assert_eq!(memo(&a, "candidate", different_key, || 3_u8), 3);
            });
            assert_eq!(
                memo::<u8>(&a, "candidate", key, || panic!(
                    "ordinary placement was lost"
                )),
                2_u8
            );
        });
    }

    #[test]
    fn retained_preparation_evicts_oldest_not_largest_key() {
        let a = analysis();
        with_retained(&a, || {
            // Ascending keys make alphabetical eviction discard the newest entries.
            for i in 0_u16..6 {
                store(&a, "selected-paper", i.to_le_bytes().to_vec(), i);
            }
            for i in 0_u16..260 {
                store(&a, "discard", i.to_le_bytes().to_vec(), i);
            }
        });
        with_retained(&a, || {
            assert_eq!(
                lookup::<u16>(&a, "selected-paper", &0_u16.to_le_bytes()),
                None
            );
            assert_eq!(
                lookup::<u16>(&a, "selected-paper", &1_u16.to_le_bytes()),
                None
            );
            for i in 2_u16..6 {
                assert_eq!(
                    lookup::<u16>(&a, "selected-paper", &i.to_le_bytes()),
                    Some(i)
                );
            }
        });
    }

    #[test]
    fn shared_memo_clones_and_drops_values_outside_its_lock() {
        use std::sync::{Arc, Weak};
        struct Probe {
            cache: Weak<BoundedMemo<Probe>>,
            value: u8,
        }
        impl Clone for Probe {
            fn clone(&self) -> Self {
                assert!(self.cache.upgrade().unwrap().values.try_lock().is_ok());
                Self {
                    cache: self.cache.clone(),
                    value: self.value,
                }
            }
        }
        impl Drop for Probe {
            fn drop(&mut self) {
                if let Some(cache) = self.cache.upgrade() {
                    assert!(cache.values.try_lock().is_ok());
                }
            }
        }
        let cache = Arc::new(BoundedMemo::new(2));
        let value = |n| Probe {
            cache: Arc::downgrade(&cache),
            value: n,
        };
        cache.insert([1; 32], value(1));
        cache.insert([2; 32], value(2));
        let mut owned = cache.get(&[1; 32]).unwrap();
        owned.value = 99;
        assert_eq!(cache.get(&[1; 32]).unwrap().value, 1);
        cache.insert([1; 32], value(3));
        cache.insert([3; 32], value(4));
        assert!(cache.get(&[2; 32]).is_none());
        assert_eq!(cache.get(&[1; 32]).unwrap().value, 3);
    }

    fn analysis() -> Analysis {
        serde_json::from_value(serde_json::json!({
            "schema": crate::model::ANALYSIS_SCHEMA,
            "binding": {"source_sha256": "test", "part": "test", "face_count": 0, "loader": "test"},
            "envelope": [[0, 0, 0], [10, 10, 10]], "iso_bounds": [0, 0, 10, 10],
            "features": [], "levels": [], "level_supports": [], "risers": [], "principal_profiles": []
        })).unwrap()
    }

    #[test]
    fn retained_preparation_binds_the_complete_analysis_and_spec() {
        let mut a = analysis();
        let mut s = Spec::default();
        let preparations = std::cell::Cell::new(0);
        let pure_preparations = std::cell::Cell::new(0);
        let read = |a: &Analysis, s: &Spec| {
            with_retained(a, || {
                memo(a, "retained-pure", Vec::new(), || {
                    pure_preparations.set(pure_preparations.get() + 1);
                    a.envelope
                });
                memo(a, "retained-test", serde_json::to_vec(s).unwrap(), || {
                    preparations.set(preparations.get() + 1);
                    (a.envelope, s.sheet.scale.clone())
                })
            })
        };
        assert_eq!(read(&a, &s), (a.envelope, None));
        assert_eq!(read(&a.clone(), &s), (a.envelope, None));
        assert_eq!(preparations.get(), 1);
        assert!(!enabled(&a));
        // The STEP binding stays the same: changed consumed evidence must still invalidate.
        a.envelope[1][0] = 20.0;
        assert_eq!(read(&a, &s), (a.envelope, None));
        assert_eq!(preparations.get(), 2);
        s.sheet.scale = Some("2:1".into());
        assert_eq!(read(&a, &s), (a.envelope, s.sheet.scale.clone()));
        assert_eq!(preparations.get(), 3);
        assert_eq!(read(&a, &s), (a.envelope, s.sheet.scale.clone()));
        assert_eq!(preparations.get(), 3);
        assert_eq!(
            pure_preparations.get(),
            2,
            "title/scale edits reuse only Analysis-dependent preparation"
        );
        assert!(!enabled(&a));
    }

    #[test]
    fn nested_calls_share_preparation_and_a_later_analysis_edit_does_not() {
        let mut a = analysis();
        let preparations = std::cell::Cell::new(0);
        let read = |a: &Analysis| {
            memo(a, "test", Vec::new(), || {
                preparations.set(preparations.get() + 1);
                a.envelope
            })
        };
        with(&a, || {
            assert_eq!(read(&a), a.envelope);
            with(&a, || assert_eq!(read(&a), a.envelope));
            assert_eq!(preparations.get(), 1);
            let b = a.clone();
            with(&b, || assert_eq!(read(&b), b.envelope));
            assert_eq!(read(&a), a.envelope);
            assert_eq!(preparations.get(), 2);
        });
        assert!(!enabled(&a));
        a.envelope[1][0] = 20.0;
        with(&a, || assert_eq!(read(&a), a.envelope));
        assert_eq!(preparations.get(), 3);
    }

    #[test]
    fn unwinding_restores_the_outer_scope_and_cached_values_are_owned() {
        let a = analysis();
        let b = a.clone();
        with(&a, || {
            let mut first = memo(&a, "test", Vec::new(), || vec![1]);
            first.push(2);
            let refused = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                with(&b, || {
                    store(&b, "test", Vec::new(), vec![3]);
                    panic!("refused candidate");
                });
            }));
            assert!(refused.is_err());
            assert_eq!(lookup::<Vec<i32>>(&a, "test", &[]), Some(vec![1]));
        });
        assert!(!enabled(&a));
    }
}