oxiproj-transformations 0.1.2

Datum transformations and coordinate conversions for OxiProj.
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
//! `push` and `pop` pipeline coordinate-stack operations.
//!
//! Ported from PROJ `src/conversions/push_pop.cpp` (part of the pipeline
//! implementation in `src/pipeline.cpp`).
//!
//! # Overview
//!
//! Within a PROJ pipeline, `push` saves selected coordinate components onto a
//! stack and `pop` restores them. This lets the pipeline temporarily
//! overwrite components for an intermediate step and then recover the originals.
//!
//! Example pipeline (preserve X/Y, do a vertical-only transform):
//!
//! ```text
//! +proj=pipeline
//!   +step +proj=push +v_1 +v_2
//!   +step +proj=somevert ...
//!   +step +proj=pop  +v_1 +v_2
//! ```
//!
//! # Component selection
//!
//! The parameters `+v_1`, `+v_2`, `+v_3`, `+v_4` select which of the four
//! coordinate slots (X/Y/Z/T) are pushed or popped. If **none** of the four
//! flags is present the operation applies to **all four** components, mirroring
//! PROJ's default behaviour.
//!
//! # Directionality
//!
//! | operation | forward  | inverse  |
//! |-----------|----------|----------|
//! | `push`    | save      | restore  |
//! | `pop`     | restore   | save     |
//!
//! # Stack ownership and pipeline scoping
//!
//! PROJ stores the four push/pop stacks in each pipeline's own opaque state
//! (`struct Pipeline::stack[4]` in `pipeline.cpp`); a `push`/`pop` step reaches
//! it via `P->parent->opaque`, i.e. the specific `Pipeline` object that
//! contains it. A nested `+proj=pipeline` step gets its *own* `Pipeline`
//! object (and therefore its own, isolated stack) — two unrelated pipelines,
//! or a pipeline nested inside another, never see each other's pushed values.
//!
//! This crate's [`Operation`] trait has no notion of "the pipeline object that
//! owns me" (that ownership lives in `oxiproj-engine`'s `Pipeline`, outside
//! this crate), so per-object storage is not directly available here. Instead
//! this module reproduces the same isolation with an explicit, opt-in dynamic
//! scope: [`enter_pipeline_scope`] opens a fresh, empty stack frame that every
//! `push`/`pop` call on the current thread sees until the returned
//! [`PipelineStackScope`] guard is dropped; dropping discards that frame
//! (and anything left on it — e.g. a value pushed by a step whose sibling
//! step, between the `push` and its matching `pop`, errored out and aborted
//! the pipeline before the `pop` ran) and restores the enclosing frame.
//! Nested scopes layer naturally with ordinary Rust call/return nesting,
//! exactly mirroring nested `Pipeline` objects each getting their own stack.
//!
//! A single base frame always exists per thread and is never dropped, so
//! callers that do not open an explicit scope keep the previous, unscoped
//! behaviour (one shared frame for the life of the thread) — this is the
//! degraded fallback used until `oxiproj-engine`'s pipeline driver is wired to
//! call `enter_pipeline_scope()` around each pipeline object's per-point
//! traversal.
//!
//! # Thread safety
//!
//! The stack frames are stored in a `thread_local!` `RefCell`, which is never
//! shared across threads. The operation structs themselves contain only
//! `[bool; 4]` and are therefore `Send + Sync`. [`PipelineStackScope`] is
//! deliberately `!Send`/`!Sync` (it carries a `PhantomData<*const ()>`
//! marker): the frame it opens and the frame it pops on `Drop` both live in
//! *this thread's* `thread_local`, so moving the guard to another thread and
//! dropping it there would pop a frame that thread never opened.

use std::cell::RefCell;
use std::marker::PhantomData;

use crate::{TransBuild, TransParams};
use oxiproj_core::{Coord, IoUnits, Operation, ProjError, ProjResult};

// ---------------------------------------------------------------------------
// Thread-local coordinate stack frames
// ---------------------------------------------------------------------------

/// One frame of the four coordinate-component stacks: index 0 → X (or λ),
/// 1 → Y (or φ), 2 → Z, 3 → T.
type StackFrame = [Vec<f64>; 4];

fn empty_frame() -> StackFrame {
    [Vec::new(), Vec::new(), Vec::new(), Vec::new()]
}

thread_local! {
    /// Per-thread stack of `push`/`pop` coordinate-stack frames. See the
    /// module-level "Stack ownership and pipeline scoping" section for the
    /// full rationale. Frame 0 (the base frame) always exists.
    ///
    /// Using `RefCell` is safe here because each thread owns its own instance;
    /// there is never cross-thread aliasing. The operation structs do **not**
    /// hold a reference to this `RefCell`; they access it only via the
    /// `thread_local!` key, so they remain `Send + Sync`.
    static COORD_STACK_FRAMES: RefCell<Vec<StackFrame>> = RefCell::new(vec![empty_frame()]);
}

// ---------------------------------------------------------------------------
// Pipeline-scoped stack isolation
// ---------------------------------------------------------------------------

/// RAII guard returned by [`enter_pipeline_scope`]. Dropping it discards the
/// stack frame it opened — including any value left on it by an unmatched
/// `push` — and restores the enclosing frame as current.
#[must_use = "the pipeline stack scope is only active while this guard is alive; \
              binding it to `_` drops it immediately and closes the scope"]
#[derive(Debug)]
pub struct PipelineStackScope {
    // Not constructible outside this module; also forces `!Send`/`!Sync` so
    // the guard cannot be dropped on a thread other than the one that opened
    // its frame (see the module-level "Thread safety" section).
    _marker: PhantomData<*const ()>,
}

/// Open a fresh, isolated `push`/`pop` coordinate-stack frame for the current
/// thread, returning a guard that closes the frame (discarding anything left
/// on it) when dropped.
///
/// Intended to be called once per constructed pipeline object, around each
/// point it transforms — mirroring PROJ giving every `Pipeline` its own
/// opaque `stack[4]`. Doing so gives two guarantees beyond a single shared
/// thread-wide stack:
///
/// * **Cross-pipeline isolation** — two unrelated pipelines (or
///   `Transformer`s) that both contain `push`/`pop`, used alternately on the
///   same thread, can never see each other's stacked values, because each
///   opens its own frame.
/// * **Error-path cleanup** — if a step between `push` and its matching `pop`
///   returns an error and the pipeline aborts before reaching the `pop`, the
///   orphaned value is discarded when the scope guard drops instead of
///   lingering on a shared stack for a later, unrelated point to pop.
///
/// Nested pipelines layer correctly: entering a nested scope while an outer
/// one is still open (as happens when a nested pipeline's
/// `forward_4d`/`inverse_4d` runs inside an outer pipeline's step loop)
/// pushes an additional frame on top and restores the outer frame on drop.
///
/// Callers that never invoke this function are unaffected: all `push`/`pop`
/// operations keep sharing the single base frame, exactly as before this
/// scoping mechanism was introduced.
pub fn enter_pipeline_scope() -> PipelineStackScope {
    COORD_STACK_FRAMES.with(|cell| {
        cell.borrow_mut().push(empty_frame());
    });
    PipelineStackScope {
        _marker: PhantomData,
    }
}

impl Drop for PipelineStackScope {
    fn drop(&mut self) {
        COORD_STACK_FRAMES.with(|cell| {
            let mut frames = cell.borrow_mut();
            // Never drop the base frame: it is the fallback shared frame used
            // by callers that don't open an explicit scope.
            if frames.len() > 1 {
                frames.pop();
            }
        });
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Push selected components of `c` onto the current thread-local stack frame
/// (the innermost frame opened by [`enter_pipeline_scope`], or the shared
/// base frame if no scope is open).
///
/// Returns `c` unmodified; `push` is a pure side-effect on the stack.
fn do_push(c: Coord, which: [bool; 4]) -> ProjResult<Coord> {
    let v = c.v();
    COORD_STACK_FRAMES.with(|cell| {
        let mut frames = cell.borrow_mut();
        if let Some(frame) = frames.last_mut() {
            for i in 0..4 {
                if which[i] {
                    frame[i].push(v[i]);
                }
            }
        }
        // `frames` is never empty (the base frame is never popped), so the
        // `None` arm is unreachable in practice; it is handled as a no-op
        // rather than a panic to uphold the no-panics production policy.
    });
    Ok(c)
}

/// Pop selected components from the current thread-local stack frame into
/// `c`.
///
/// Components not selected by `which` are passed through unchanged.
/// If a stack is empty for a selected component (underflow), that component
/// is left at its current value — this matches PROJ's silent behaviour.
fn do_pop(c: Coord, which: [bool; 4]) -> ProjResult<Coord> {
    let mut v = c.v();
    COORD_STACK_FRAMES.with(|cell| {
        let mut frames = cell.borrow_mut();
        if let Some(frame) = frames.last_mut() {
            for i in 0..4 {
                if which[i] {
                    if let Some(val) = frame[i].pop() {
                        v[i] = val;
                    }
                    // Stack underflow: leave `v[i]` unchanged (PROJ silent pass-through)
                }
            }
        }
    });
    Ok(Coord::new(v[0], v[1], v[2], v[3]))
}

// ---------------------------------------------------------------------------
// Operation structs
// ---------------------------------------------------------------------------

/// `push` pipeline operation — saves coordinate components onto the thread-local stack.
///
/// Forward direction: push (save). Inverse direction: pop (restore).
#[derive(Debug)]
struct PushOp {
    /// Which of the four coordinate components to push/pop.
    which: [bool; 4],
}

/// `pop` pipeline operation — restores coordinate components from the thread-local stack.
///
/// Forward direction: pop (restore). Inverse direction: push (save).
#[derive(Debug)]
struct PopOp {
    /// Which of the four coordinate components to push/pop.
    which: [bool; 4],
}

// SAFETY: `PushOp`/`PopOp` contain only `[bool; 4]`, which is `Send + Sync`.
// The thread-local `COORD_STACK_FRAMES` is never stored in the struct; it is
// accessed only at call time via the `thread_local!` key. Therefore the
// structs are safe to move and share across threads even though the backing
// storage is thread-local.

impl Operation for PushOp {
    /// Forward: save selected components onto the stack, return `c` unchanged.
    fn forward_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_push(c, self.which)
    }

    /// Inverse: restore selected components from the stack into `c`.
    fn inverse_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_pop(c, self.which)
    }

    fn has_inverse(&self) -> bool {
        true
    }
}

impl Operation for PopOp {
    /// Forward: restore selected components from the stack into `c`.
    fn forward_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_pop(c, self.which)
    }

    /// Inverse: save selected components onto the stack, return `c` unchanged.
    fn inverse_4d(&self, c: Coord) -> ProjResult<Coord> {
        do_push(c, self.which)
    }

    fn has_inverse(&self) -> bool {
        true
    }
}

// ---------------------------------------------------------------------------
// Parameter parsing
// ---------------------------------------------------------------------------

/// Parse `+v_1` … `+v_4` flags from the parameter block.
///
/// If **none** of the four flags is present, all four components are selected
/// (PROJ default: push/pop everything when no component filter is given).
fn parse_which(p: &TransParams) -> [bool; 4] {
    let v1 = p.params.exists("v_1");
    let v2 = p.params.exists("v_2");
    let v3 = p.params.exists("v_3");
    let v4 = p.params.exists("v_4");
    if !v1 && !v2 && !v3 && !v4 {
        // No filter → apply to all four components (PROJ default behaviour)
        [true, true, true, true]
    } else {
        [v1, v2, v3, v4]
    }
}

// ---------------------------------------------------------------------------
// Public constructors
// ---------------------------------------------------------------------------

/// Construct the `push` coordinate-stack operation.
///
/// Reads `+v_1` … `+v_4` flags to determine which components are saved.
/// If none are specified all four components are saved.
pub fn new_push(p: &TransParams) -> ProjResult<TransBuild> {
    let _ = ProjError::InvalidOp; // ensure error type is used (suppress lint)
    Ok(TransBuild::new(
        Box::new(PushOp {
            which: parse_which(p),
        }),
        IoUnits::Whatever,
        IoUnits::Whatever,
    ))
}

/// Construct the `pop` coordinate-stack operation.
///
/// Reads `+v_1` … `+v_4` flags to determine which components are restored.
/// If none are specified all four components are restored.
pub fn new_pop(p: &TransParams) -> ProjResult<TransBuild> {
    Ok(TransBuild::new(
        Box::new(PopOp {
            which: parse_which(p),
        }),
        IoUnits::Whatever,
        IoUnits::Whatever,
    ))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use oxiproj_core::{Coord, Ellipsoid};

    // Minimal no-op parameter set for constructors that don't need params.
    struct NoParams;
    impl crate::TransParamLookup for NoParams {
        fn get_dms(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_f64(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_int(&self, _key: &str) -> Option<i64> {
            None
        }
        fn get_str(&self, _key: &str) -> Option<&str> {
            None
        }
        fn get_bool(&self, _key: &str) -> bool {
            false
        }
        fn exists(&self, _key: &str) -> bool {
            false
        }
    }

    // Parameter set that marks v_1 and v_2 as present.
    struct V1V2Params;
    impl crate::TransParamLookup for V1V2Params {
        fn get_dms(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_f64(&self, _key: &str) -> Option<f64> {
            None
        }
        fn get_int(&self, _key: &str) -> Option<i64> {
            None
        }
        fn get_str(&self, _key: &str) -> Option<&str> {
            None
        }
        fn get_bool(&self, _key: &str) -> bool {
            false
        }
        fn exists(&self, key: &str) -> bool {
            key == "v_1" || key == "v_2"
        }
    }

    fn wgs84() -> Ellipsoid {
        Ellipsoid::named("WGS84").expect("WGS84 ellipsoid must be available")
    }

    /// Reset the thread-local stack frames to a single empty base frame
    /// before each test, avoiding state leakage across tests that may share
    /// a thread (e.g. under `cargo nextest`'s thread reuse).
    fn clear_stacks() {
        COORD_STACK_FRAMES.with(|cell| {
            *cell.borrow_mut() = vec![empty_frame()];
        });
    }

    /// Number of frames currently open on this thread (1 == just the base
    /// frame, i.e. no [`enter_pipeline_scope`] guard is alive).
    fn frame_count() -> usize {
        COORD_STACK_FRAMES.with(|cell| cell.borrow().len())
    }

    #[test]
    fn push_all_then_pop_all_round_trips() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp {
            which: [true, true, true, true],
        };
        let pop = PopOp {
            which: [true, true, true, true],
        };
        let original = Coord::new(1.0, 2.0, 3.0, 4.0);
        let after_push = push.forward_4d(original)?;
        // push does not modify coordinates
        assert_eq!(after_push.v(), [1.0, 2.0, 3.0, 4.0]);

        // Overwrite the coordinate
        let modified = Coord::new(9.0, 8.0, 7.0, 6.0);
        let restored = pop.forward_4d(modified)?;
        // pop should restore all four components
        assert_eq!(restored.v(), [1.0, 2.0, 3.0, 4.0]);
        Ok(())
    }

    #[test]
    fn push_v1_v2_only_preserves_v3_v4() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp {
            which: [true, true, false, false],
        };
        let pop = PopOp {
            which: [true, true, false, false],
        };
        let original = Coord::new(10.0, 20.0, 30.0, 40.0);
        push.forward_4d(original)?;

        // After modification only v3/v4 changed on the current coord
        let modified = Coord::new(99.0, 88.0, 77.0, 66.0);
        let restored = pop.forward_4d(modified)?;
        // v_1 and v_2 restored; v_3 and v_4 come from `modified`
        assert_eq!(restored.v()[0], 10.0);
        assert_eq!(restored.v()[1], 20.0);
        assert_eq!(restored.v()[2], 77.0);
        assert_eq!(restored.v()[3], 66.0);
        Ok(())
    }

    #[test]
    fn push_inverse_acts_as_pop() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp {
            which: [true, true, true, true],
        };
        // Save via forward (push)
        let saved = Coord::new(5.0, 6.0, 7.0, 8.0);
        push.forward_4d(saved)?;

        // Restore via inverse (pop)
        let modified = Coord::new(0.0, 0.0, 0.0, 0.0);
        let restored = push.inverse_4d(modified)?;
        assert_eq!(restored.v(), [5.0, 6.0, 7.0, 8.0]);
        Ok(())
    }

    #[test]
    fn pop_inverse_acts_as_push() -> ProjResult<()> {
        clear_stacks();
        let pop = PopOp {
            which: [true, true, true, true],
        };
        // Save via inverse (push)
        let saved = Coord::new(11.0, 22.0, 33.0, 44.0);
        pop.inverse_4d(saved)?;

        // Restore via forward (pop)
        let modified = Coord::new(0.0, 0.0, 0.0, 0.0);
        let restored = pop.forward_4d(modified)?;
        assert_eq!(restored.v(), [11.0, 22.0, 33.0, 44.0]);
        Ok(())
    }

    #[test]
    fn no_params_defaults_to_all_components() {
        let which = parse_which(&TransParams {
            ellipsoid: &wgs84(),
            params: &NoParams,
            registry: None,
        });
        assert_eq!(which, [true, true, true, true]);
    }

    #[test]
    fn v1_v2_params_selects_first_two() {
        let which = parse_which(&TransParams {
            ellipsoid: &wgs84(),
            params: &V1V2Params,
            registry: None,
        });
        assert_eq!(which, [true, true, false, false]);
    }

    #[test]
    fn new_push_builds_successfully() {
        let ell = wgs84();
        let p = TransParams {
            ellipsoid: &ell,
            params: &NoParams,
            registry: None,
        };
        assert!(new_push(&p).is_ok());
    }

    #[test]
    fn new_pop_builds_successfully() {
        let ell = wgs84();
        let p = TransParams {
            ellipsoid: &ell,
            params: &NoParams,
            registry: None,
        };
        assert!(new_pop(&p).is_ok());
    }

    #[test]
    fn stack_underflow_leaves_component_unchanged() -> ProjResult<()> {
        clear_stacks();
        let pop = PopOp {
            which: [true, false, false, false],
        };
        // Stack is empty; component should remain as-is (no panic, no error)
        let c = Coord::new(99.0, 1.0, 2.0, 3.0);
        let result = pop.forward_4d(c)?;
        assert_eq!(result.v()[0], 99.0); // unchanged since stack was empty
        Ok(())
    }

    #[test]
    fn push_and_pop_have_inverse() {
        let push = PushOp { which: [true; 4] };
        let pop = PopOp { which: [true; 4] };
        assert!(push.has_inverse());
        assert!(pop.has_inverse());
    }

    // ---- Pipeline-scoped stack isolation (cross-pipeline / error-path) ----

    #[test]
    fn enter_pipeline_scope_opens_and_closes_a_frame() {
        clear_stacks();
        assert_eq!(frame_count(), 1);
        {
            let _scope = enter_pipeline_scope();
            assert_eq!(frame_count(), 2);
            {
                let _nested = enter_pipeline_scope();
                assert_eq!(frame_count(), 3);
            }
            assert_eq!(frame_count(), 2);
        }
        assert_eq!(frame_count(), 1);
    }

    /// Regression test for the cross-pipeline contamination finding: two
    /// "pipelines" (simulated by two `PushOp`/`PopOp` pairs, each guarded by
    /// its own `enter_pipeline_scope`) used alternately on the same thread
    /// must never observe each other's pushed values, even when the first
    /// one aborts mid-pipeline (push with no matching pop, mirroring a step
    /// between `push` and `pop` returning an error).
    #[test]
    fn cross_pipeline_scopes_do_not_contaminate() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp { which: [true; 4] };
        let pop = PopOp { which: [true; 4] };

        // "Pipeline A" processes a point: push succeeds, then a later step
        // fails and the pipeline aborts before reaching `pop`. The scope
        // guard drops here (end of the `{ }` block) without a matching pop,
        // exactly as `Pipeline::forward_4d` returning `Err` mid-way would
        // leave the guard's block.
        {
            let _scope_a = enter_pipeline_scope();
            let point_a = Coord::new(111.0, 222.0, 333.0, 444.0);
            push.forward_4d(point_a)?;
            // (simulated failing step here; `pop` is never reached)
        }

        // "Pipeline B" processes a completely unrelated point on the same
        // thread. If the stacks were still a single shared thread-local
        // (the pre-fix behaviour), B's `pop` would silently receive A's
        // orphaned values instead of its own.
        let restored_b = {
            let _scope_b = enter_pipeline_scope();
            let point_b = Coord::new(1.0, 2.0, 3.0, 4.0);
            push.forward_4d(point_b)?;
            pop.forward_4d(Coord::new(9.0, 9.0, 9.0, 9.0))?
        };
        assert_eq!(
            restored_b.v(),
            [1.0, 2.0, 3.0, 4.0],
            "pipeline B must recover its own pushed point, not pipeline A's orphaned one"
        );

        // Back at the base (un-scoped) frame: pipeline A's orphaned push was
        // discarded when its scope dropped, and pipeline B's scope is closed
        // too, so a bare pop here (no scope open) must NOT see either of
        // their leaked values — it hits the empty base frame (underflow) and
        // leaves the component unchanged (PROJ silent pass-through).
        clear_stacks();
        let untouched = Coord::new(7.0, 8.0, 9.0, 10.0);
        let after_pop = pop.forward_4d(untouched)?;
        assert_eq!(after_pop.v(), untouched.v());
        Ok(())
    }

    /// Nested-pipeline regression test: an inner pipeline's `push`/`pop`
    /// (its own `enter_pipeline_scope`, opened while an outer scope is still
    /// active — as happens when a nested `+proj=pipeline` step's
    /// `forward_4d` runs inside an outer pipeline's step loop) must not
    /// disturb the outer pipeline's own stacked value, and the outer scope's
    /// value must still be there once the nested scope closes.
    #[test]
    fn nested_pipeline_scope_isolates_from_outer() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp { which: [true; 4] };
        let pop = PopOp { which: [true; 4] };

        let _outer = enter_pipeline_scope();
        let outer_point = Coord::new(1000.0, 2000.0, 3000.0, 4000.0);
        push.forward_4d(outer_point)?;

        // Nested pipeline: pushes and pops its own, different value, fully
        // within its own nested scope.
        {
            let _inner = enter_pipeline_scope();
            let inner_point = Coord::new(1.0, 1.0, 1.0, 1.0);
            push.forward_4d(inner_point)?;
            let inner_restored = pop.forward_4d(Coord::new(0.0, 0.0, 0.0, 0.0))?;
            assert_eq!(
                inner_restored.v(),
                [1.0, 1.0, 1.0, 1.0],
                "nested pipeline must recover its own value"
            );
        }

        // Back in the outer scope: its pushed value must be intact, unmixed
        // with anything the nested pipeline did.
        let outer_restored = pop.forward_4d(Coord::new(0.0, 0.0, 0.0, 0.0))?;
        assert_eq!(
            outer_restored.v(),
            [1000.0, 2000.0, 3000.0, 4000.0],
            "outer pipeline's value must survive a nested pipeline's own push/pop"
        );
        Ok(())
    }

    /// Error-path cleanup regression test: if a pipeline aborts after `push`
    /// but before its matching `pop` (simulated by dropping the scope guard
    /// without popping), the orphaned value must not resurface for a later,
    /// unrelated point processed in a fresh scope on the same thread.
    #[test]
    fn error_path_orphaned_push_is_discarded_on_scope_drop() -> ProjResult<()> {
        clear_stacks();
        let push = PushOp { which: [true; 4] };
        let pop = PopOp { which: [true; 4] };

        {
            let _aborted_scope = enter_pipeline_scope();
            push.forward_4d(Coord::new(42.0, 42.0, 42.0, 42.0))?;
            // Pipeline aborts: matching `pop` never runs, scope drops here.
        }

        // A fresh point, fresh scope: must not see the orphaned 42.0 values.
        let fresh_scope = enter_pipeline_scope();
        let fresh_point = Coord::new(5.0, 6.0, 7.0, 8.0);
        push.forward_4d(fresh_point)?;
        let restored = pop.forward_4d(Coord::new(0.0, 0.0, 0.0, 0.0))?;
        assert_eq!(restored.v(), [5.0, 6.0, 7.0, 8.0]);
        drop(fresh_scope);
        Ok(())
    }
}