rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
//! Incremental config reconciliation (issue #316): stable stub identity, the order-aware
//! stub edit script, apply reports, and imposter change events.

use super::core::{LoadClock, StubState, first_divergence, restamp};
use super::types::{ImposterError, Stub};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tracing::error;

/// Whether an imposter is written through to the manager's datadir (issue #1122).
///
/// Persist-on-create exists so an imposter created through the admin API survives a restart
/// (issues #563/#575). An imposter loaded from `--configfile`/`--imposters` already has a store it
/// is re-read from; a datadir copy of it would be a second imposter with no rule to match it back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Persistence {
    /// Written to `{port}.json` on create and on every config change.
    Datadir,
    /// Never written to the datadir. An apply entry with this store also removes a runtime
    /// `{port}.json` left by the `Datadir` imposter it took over from (issue #1821).
    Ephemeral,
}

/// One entry of the desired set passed to
/// [`ImposterManager::apply_desired`](super::ImposterManager::apply_desired).
#[derive(Debug, Clone)]
pub struct DesiredImposter {
    pub config: super::types::ImposterConfig,
    pub persistence: Persistence,
    /// What this imposter's scripts may `require()`, as the door it came through decides (issue
    /// #1611): a local config file is trusted, a datadir file or a network source is confined.
    pub script_files: super::script_resolve::ScriptFileAccess,
}

/// Outcome of [`ImposterManager::apply_config`](super::ImposterManager::apply_config):
/// which ports were created, replaced wholesale, stub-patched in place, deleted, or
/// failed to apply. Untouched imposters appear in none of the lists. A port may appear
/// in more than one list when that is the truth — e.g. a wholesale replace whose recreate
/// fails after teardown lands in both `deleted` and `failed`, and a patched imposter whose
/// datadir write fails lands in both `stub_patched` and `failed`. Failures for configs
/// without an explicit port (auto-assign creates) are reported under port `0`. Explicit-port configs
/// are applied before auto-assigned ones (issue #1112), so `created` lists explicit ports first, in
/// input order, then auto-assigned ports.
#[derive(Debug, Default)]
pub struct ApplyReport {
    pub created: Vec<u16>,
    pub replaced: Vec<u16>,
    pub stub_patched: Vec<u16>,
    /// Ports whose only imposter-level change was the `enabled` flag, applied
    /// in place — runtime state intact (pausing an imposter must never reset
    /// its scenario state).
    pub toggled: Vec<u16>,
    pub deleted: Vec<u16>,
    pub failed: Vec<(u16, ImposterError)>,
}

impl ApplyReport {
    /// The per-port lists as the admin API and the C-ABI report them: `created`, `replaced`,
    /// `stubPatched`, `toggled`, `deleted` — always all five, empty when nothing happened.
    ///
    /// `failed` is not here: HTTP and the FFI render it differently (strings vs objects). This is
    /// the one place that knows the list of lists, so a new field cannot be missed by one surface.
    #[must_use]
    pub fn port_lists(&self) -> serde_json::Map<String, serde_json::Value> {
        let mut lists = serde_json::Map::new();
        for (key, ports) in [
            ("created", &self.created),
            ("replaced", &self.replaced),
            ("stubPatched", &self.stub_patched),
            ("toggled", &self.toggled),
            ("deleted", &self.deleted),
        ] {
            lists.insert(key.to_owned(), serde_json::json!(ports));
        }
        lists
    }
}

/// Outcome of [`ImposterManager::delete_all`](super::ImposterManager::delete_all) (issue #1124).
///
/// A port in `failed` was **not** deleted: it is still registered and serving, because its datadir
/// file could not be removed and deleting it anyway would bring it back on the next restart.
#[derive(Debug, Default)]
pub struct DeleteAllReport {
    pub deleted: Vec<super::types::ImposterConfig>,
    pub failed: Vec<(u16, ImposterError)>,
}

/// A config mutation observed on the manager (issue #316), for embedders that need to
/// react to config changes (audit logging, persistence hooks, webhooks).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImposterEvent {
    Created(u16),
    Replaced(u16),
    StubsChanged(u16),
    /// The serve/pause flag flipped (issue #817): config, not ephemera — the
    /// toggle persists and replicates like any other config change.
    EnabledChanged {
        port: u16,
        enabled: bool,
    },
    Deleted(u16),
    AllDeleted,
}

/// Who caused a change event (issue #855).
///
/// Attribution rides here, on the listener signature, rather than on [`ImposterEvent`]: the enum
/// is not `#[non_exhaustive]`, so adding a field to every variant would break every downstream
/// `match` — the wrong trade for a seam whose premise is that installing nothing changes nothing.
/// `#[non_exhaustive]` for the same reason attribution is not on [`ImposterEvent`]: the next
/// attribution field (scope, request id, remote addr) must not be a second breaking change to the
/// same seam. Embedders read this type; to build one in a test, start from
/// [`Default`] and assign — a struct literal, including `..Default::default()`, is not available
/// outside this crate.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct EventContext {
    /// The principal an [`AdminAuthorizer`](crate::extensions::authz::AdminAuthorizer) attributed
    /// the causing request to, via `AuthzDecision::Allow { principal }`.
    ///
    /// `None` whenever there is nobody to name — no authorizer installed, an authorizer that
    /// allowed without identifying anyone, or a mutation with no request behind it at all (a
    /// config-file load, or an embedder driving [`ImposterManager`](super::ImposterManager)
    /// directly). Absent attribution is reported as absent; it is never guessed.
    pub principal: Option<String>,
}

/// Observer for [`ImposterEvent`]s; register via
/// [`ImposterManager::with_event_listener`](super::ImposterManager::with_event_listener).
/// Called synchronously on the mutating path — keep implementations fast and non-blocking.
///
/// `ctx` carries attribution (issue #855). A listener that only cares *what* changed ignores it.
pub trait ImposterEventListener: Send + Sync {
    fn on_event(&self, event: &ImposterEvent, ctx: &EventContext);
}

/// Stable stub identity: the explicit `id` (issue #202) if set, else
/// `"~" + <16-hex content hash> + "#" + <occurrence among content-identical siblings>`.
/// The `~` prefix keeps generated keys disjoint from user-supplied ids.
pub fn stub_key(stub: &Stub, occurrence: usize) -> String {
    match &stub.id {
        Some(id) => id.clone(),
        None => key_for(None, content_hash(stub), occurrence),
    }
}

/// [`stub_key`] from a stub's id and an already-computed [`content_hash`].
pub(crate) fn key_for(id: Option<&str>, hash: u64, occurrence: usize) -> String {
    match id {
        Some(id) => id.to_string(),
        None => format!("~{hash:016x}#{occurrence}"),
    }
}

/// FNV-1a 64 over the stub's canonical JSON. `Stub` holds `std::collections::HashMap`s
/// (predicate operations, response headers) that serialize in per-instance iteration order, so the
/// stub is first converted to a `serde_json::Value`, whose objects are sorted maps (`preserve_order`
/// is off workspace-wide), and that is what gets hashed (issue #1256). Struct fields are sorted
/// too, so this form differs from serializing the stub directly: every id-less key moved once.
///
/// `recordedAt` (issue #1759) is left out: it says when a proxy recorded the stub, not what the stub
/// does, so a recording keeps the key it would have had without it, on every release (a rift-cluster
/// rolling upgrade hashes the same bytes on old and new nodes alike).
pub(crate) fn content_hash(stub: &Stub) -> u64 {
    if stub.recorded_at.is_some() {
        let mut keyed = stub.clone();
        keyed.recorded_at = None;
        return content_hash(&keyed);
    }
    let mut hasher = Fnv1a::default();
    let hashed = serde_json::to_value(stub)
        .and_then(|canonical| serde_json::to_writer(&mut hasher, &canonical));
    if let Err(e) = hashed {
        // Debug output is content-distinguishing but not canonical across processes —
        // keys built from it may churn between reloads, so make the degradation visible.
        error!("stub serialization failed while keying; falling back to Debug format: {e}");
        hasher = Fnv1a::default();
        hasher.update(format!("{stub:?}").as_bytes());
    }
    hasher.0
}

/// Streaming FNV-1a 64, so the canonical JSON is hashed without materializing a `String`. Also the
/// `_rift.conditional` ETag (issue #1280), which must be the same on every process and node.
pub(crate) struct Fnv1a(u64);

impl Default for Fnv1a {
    fn default() -> Self {
        Self(0xcbf2_9ce4_8422_2325)
    }
}

impl Fnv1a {
    pub(crate) fn finish(&self) -> u64 {
        self.0
    }

    pub(crate) fn update(&mut self, bytes: &[u8]) {
        const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
        self.0 = bytes.iter().fold(self.0, |hash, byte| {
            (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
        });
    }
}

impl std::io::Write for Fnv1a {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.update(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// Keys for a stub sequence; occurrence is counted per content hash so content-identical
/// id-less siblings get distinct keys and stay individually addressable in the diff.
#[cfg(test)]
pub(crate) fn stub_keys(stubs: &[Stub]) -> Vec<String> {
    keys_from(
        stubs
            .iter()
            .map(|stub| (stub.id.as_deref(), content_hash(stub))),
    )
}

/// Keys from each stub's `(id, content hash)`, so a caller holding cached hashes (live
/// [`StubState`]s) never re-serializes a stub.
pub(crate) fn keys_from<'a>(stubs: impl Iterator<Item = (Option<&'a str>, u64)>) -> Vec<String> {
    let mut seen: HashMap<u64, usize> = HashMap::new();
    stubs
        .map(|(id, hash)| match id {
            Some(id) => id.to_string(),
            None => {
                let occurrence = seen.entry(hash).or_insert(0);
                let key = key_for(None, hash, *occurrence);
                *occurrence += 1;
                key
            }
        })
        .collect()
}

/// Outcome of a stub-level reconcile.
#[derive(Debug)]
pub(crate) enum StubReconcile {
    /// Same stubs, same order — nothing touched.
    Unchanged,
    /// Edited in place; untouched slots kept their cycling state.
    Patched {
        /// Sequencer keys (`stub_key(stub, 0)`) of stubs the patch removed, so the
        /// manager can fire the per-stub `reset_scope` GC hook (issue #313).
        removed_keys: Vec<String>,
    },
    /// More than half the stubs would change — the caller should replace the imposter
    /// wholesale instead of thrashing the stub set in place.
    Degenerate,
    /// The writing door's script access allows more than the imposter's (issue #1645), so it can
    /// only take effect on an imposter whose every stub is new: the caller replaces the imposter.
    /// Nothing was touched.
    Widens,
}

/// What reconciling a live stub vector toward a desired one would do, computed without touching
/// the live vector, so an `Unchanged` or `Degenerate` outcome stores nothing (issue #1254).
pub(crate) enum StubPlan {
    Unchanged,
    Degenerate,
    Patched {
        /// The new stub vector, in desired order, reusing every surviving `Arc<StubState>`.
        next: Vec<Arc<StubState>>,
        /// Sequencer keys (occurrence 0) of the stubs the patch removes.
        removed_keys: Vec<String>,
    },
}

/// Plan the reconcile of `states` toward `desired`, preserving per-slot cycling state for every
/// stub whose key survives. Pure moves (reorder) preserve everything; a same-key content change
/// (explicit id) swaps the stub in place like `replace_stub_by_id`. `Degenerate` when the changed
/// fraction exceeds 1/2 (pure moves cost nothing in that metric).
///
/// Content is compared by [`content_hash`]: cached on each live state, computed once per desired
/// stub (issue #1254). A content key already embeds the hash, so for id-less stubs a matching key
/// is a matching content; for an explicit id the hashes are compared. Equal `(id, hash)` sequences
/// are `Unchanged`, which is the common case of re-applying an unchanged set and costs one
/// serialization per desired stub and nothing per live one.
pub(crate) fn plan_stub_reconcile(
    states: &[Arc<StubState>],
    desired: &[Stub],
    clock: &LoadClock,
) -> StubPlan {
    let desired_hashes: Vec<u64> = desired.iter().map(content_hash).collect();
    let unchanged = states.len() == desired.len()
        && states
            .iter()
            .zip(desired.iter().zip(&desired_hashes))
            .all(|(state, (stub, hash))| state.stub.id == stub.id && state.content_hash() == *hash);
    if unchanged {
        return StubPlan::Unchanged;
    }

    let old_keys = keys_from(
        states
            .iter()
            .map(|state| (state.stub.id.as_deref(), state.content_hash())),
    );
    let new_keys = keys_from(
        desired
            .iter()
            .zip(&desired_hashes)
            .map(|(stub, hash)| (stub.id.as_deref(), *hash)),
    );

    let old_index: HashMap<&String, usize> =
        old_keys.iter().enumerate().map(|(i, k)| (k, i)).collect();
    let new_set: HashSet<&String> = new_keys.iter().collect();

    let deletes = old_keys.iter().filter(|k| !new_set.contains(*k)).count();
    let mut inserts = 0usize;
    let mut content_replaced = 0usize;
    for (i, key) in new_keys.iter().enumerate() {
        match old_index.get(key) {
            None => inserts += 1,
            // Same explicit id, different content.
            Some(&j) if states[j].content_hash() != desired_hashes[i] => {
                content_replaced += 1;
            }
            Some(_) => {}
        }
    }

    // Changed fraction over both sides: a content replace touches one slot on each side.
    let changed_slots = deletes + inserts + 2 * content_replaced;
    if changed_slots * 2 > states.len() + desired.len() {
        return StubPlan::Degenerate;
    }

    let mut by_key: HashMap<String, Arc<StubState>> =
        old_keys.into_iter().zip(states.iter().cloned()).collect();
    // Only an inserted or changed stub is cloned out of `desired`; a surviving one reuses its Arc.
    // New content shares one stamp from `clock`, taken only if there is any (issue #1301).
    let mut fresh: Option<chrono::DateTime<chrono::Utc>> = None;
    let mut stamp = || *fresh.get_or_insert_with(|| clock.next());
    let next = new_keys
        .into_iter()
        .zip(desired.iter().zip(desired_hashes))
        .map(|(key, (stub, hash))| match by_key.remove(&key) {
            // Same key: keep the slot's cycler + slot token; only rebuild the Arc when the
            // stub content actually changed (issue #287).
            Some(state) if state.content_hash() == hash => state,
            Some(state) => Arc::new(
                state
                    .with_stub_hashed(stub.clone(), hash)
                    .with_loaded_at(stamp()),
            ),
            None => Arc::new(StubState::with_hash(stub.clone(), hash).with_loaded_at(stamp())),
        })
        .collect::<Vec<_>>();
    // Stamps are positional (issue #1303): what a request gets depends on which stub sits where,
    // and a surviving state reused by key may have moved. From the first position where the old
    // and new stubs stop matching alike, every stub takes the patch's stamp; before it, a position
    // keeps the stamp it had only when it holds the same content it held.
    let mut next = next;
    let k = first_divergence(states.iter().map(|s| &s.stub), desired.iter());
    for p in 0..next.len() {
        let at = match states.get(p) {
            Some(prev) if p < k && prev.content_hash() == next[p].content_hash() => {
                prev.loaded_at()
            }
            _ => stamp(),
        };
        if next[p].loaded_at() != at {
            restamp(&mut next, p..=p, at);
        }
    }
    let removed_keys = by_key
        .into_values()
        .map(|state| state.sequence_key())
        .collect();
    StubPlan::Patched { next, removed_keys }
}

/// Apply [`plan_stub_reconcile`] to an owned vector, which is left untouched unless the plan
/// patches it.
#[cfg(test)]
pub(crate) fn reconcile_stub_states(
    states: &mut Vec<Arc<StubState>>,
    desired: Vec<Stub>,
) -> StubReconcile {
    match plan_stub_reconcile(states, &desired, &LoadClock::new()) {
        StubPlan::Unchanged => StubReconcile::Unchanged,
        StubPlan::Degenerate => StubReconcile::Degenerate,
        StubPlan::Patched { next, removed_keys } => {
            *states = next;
            StubReconcile::Patched { removed_keys }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::imposter::core::StubState;

    #[test]
    fn port_lists_has_every_list_even_when_empty() {
        let lists = ApplyReport::default().port_lists();
        let mut keys: Vec<&str> = lists.keys().map(String::as_str).collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            ["created", "deleted", "replaced", "stubPatched", "toggled"]
        );
        assert!(lists.values().all(|v| v == &json!([])));

        let report = ApplyReport {
            toggled: vec![7],
            stub_patched: vec![8],
            ..ApplyReport::default()
        };
        let lists = report.port_lists();
        assert_eq!(lists["toggled"], json!([7]));
        assert_eq!(lists["stubPatched"], json!([8]));
    }
    use crate::imposter::types::Stub;
    use serde_json::json;

    fn stub(v: serde_json::Value) -> Stub {
        serde_json::from_value(v).expect("test stub json")
    }

    fn one_resp(body: &str) -> Stub {
        stub(json!({
            "predicates": [{"equals": {"path": format!("/{body}")}}],
            "responses": [{"is": {"statusCode": 200, "body": body}}]
        }))
    }

    fn two_resp(first: &str, second: &str) -> Stub {
        stub(json!({
            "predicates": [{"equals": {"path": "/cycled"}}],
            "responses": [
                {"is": {"statusCode": 200, "body": first}},
                {"is": {"statusCode": 200, "body": second}}
            ]
        }))
    }

    /// Build a live stub state (states are stored behind `Arc` since #287).
    fn st(stub: Stub) -> Arc<StubState> {
        Arc::new(StubState::new(stub))
    }

    /// Serve the state's next response and return its body (advances the cycler).
    fn next_body(state: &StubState) -> String {
        let resp = state.get_next_response().expect("stub has responses");
        serde_json::to_value(resp).expect("serialize response")["is"]["body"]
            .as_str()
            .expect("string body")
            .to_string()
    }

    /// A stub whose predicate and response headers are multi-key `HashMap`s — the shape whose
    /// serialization order varied per parse before issue #1256.
    const MULTI_KEY_STUB: &str = r#"{
        "predicates": [
            {"equals": {"method": "GET", "path": "/a", "query": {"q": "1", "r": "2"}, "body": "x"}},
            {"or": [{"contains": {"path": "/a", "body": "y", "method": "G"}}, {"not": {"startsWith": {"path": "/b", "body": "z"}}}]}
        ],
        "responses": [{"is": {"statusCode": 200, "headers": {"Content-Type": "application/json", "X-A": "1", "X-B": "2", "X-C": "3", "X-D": "4"}, "body": "b"}}]
    }"#;

    fn parse_multi() -> Stub {
        serde_json::from_str(MULTI_KEY_STUB).expect("multi-key stub json")
    }

    // Issue #1256: identical content must key identically however its maps were built.
    #[test]
    fn stub_key_is_stable_across_fresh_parses() {
        let first = stub_key(&parse_multi(), 0);
        for _ in 0..20 {
            assert_eq!(stub_key(&parse_multi(), 0), first);
        }
    }

    #[test]
    fn identical_multi_key_stubs_are_unchanged() {
        let mut live = vec![st(parse_multi()), st(one_resp("a"))];
        let before: Vec<_> = live.iter().map(Arc::clone).collect();
        let outcome = reconcile_stub_states(&mut live, vec![parse_multi(), one_resp("a")]);
        assert!(
            matches!(outcome, StubReconcile::Unchanged),
            "a re-parsed identical set must be Unchanged, got {outcome:?}"
        );
        assert!(live.iter().zip(&before).all(|(a, b)| Arc::ptr_eq(a, b)));
    }

    #[test]
    fn identical_multi_key_siblings_get_distinct_occurrences() {
        let keys = stub_keys(&[parse_multi(), parse_multi()]);
        assert!(keys[0].ends_with("#0"), "{keys:?}");
        assert!(keys[1].ends_with("#1"), "{keys:?}");
        assert_eq!(
            keys[0].trim_end_matches("#0"),
            keys[1].trim_end_matches("#1")
        );
    }

    // The key is process-independent (rift-cluster shares response cursors across nodes by it), so
    // its exact value is pinned: any change to the hashed form moves every id-less stub's key.
    // Issue #1369: the hashed form now omits a `statusCode`/`headers` the author did not write
    // (it used to print `"200"` and `{}`), because a stub that omits them behaves differently from
    // one that writes them once an imposter has a `defaultResponse`. `one_resp` omits `headers`, so
    // its key moved from `~d760f3e4c82afe1f#0`; a stub that writes both prints as before.
    // Issues #1361/#1362 move it again, in the same release as #1369, as one deliberate move:
    // `is.statusCode` prints as a number (`one_resp` writes `200`) and empty/default fields are no
    // longer printed, so the key moved from `~f57bb8b520808243#0`.
    #[test]
    fn stub_key_value_is_pinned() {
        assert_eq!(stub_key(&one_resp("a"), 0), "~e2d14a5a1776f053#0");
    }

    /// Issue #1558 widened `statusCode` to any string, but a numeric string still decodes to the
    /// number it spells and prints as it did, so a stub admitted before keys as before.
    #[test]
    fn a_numeric_string_status_keys_as_before() {
        let parse = |status: serde_json::Value| -> Stub {
            serde_json::from_value(serde_json::json!({
                "responses": [{"is": {"statusCode": status, "body": "a"}}]
            }))
            .expect("stub")
        };
        let key = stub_key(&parse(serde_json::json!("404")), 0);
        assert_eq!(key, stub_key(&parse(serde_json::json!(404)), 0));
        assert_eq!(key, "~03fc7688c0fb7a8d#0");
    }

    /// Issue #1362: a stub's `name` is kept and hashed like any other field. An unnamed stub's key
    /// does not move; naming a stub is a content edit, so its key does.
    #[test]
    fn stub_key_ignores_absent_name() {
        let unnamed = one_resp("a");
        assert_eq!(stub_key(&unnamed, 0), "~e2d14a5a1776f053#0");

        let mut named = serde_json::to_value(&unnamed).expect("print");
        named["name"] = json!("s1");
        let named = stub(named);
        assert_ne!(stub_key(&named, 0), stub_key(&unnamed, 0));
    }

    /// Issue #1361: the printed form omits empty and default fields. Re-loading what was printed
    /// must give stubs with the same key, so the omission loses nothing on decode.
    #[test]
    fn corpus_stubs_keep_their_key_through_a_print_round_trip() {
        use crate::imposter::types::ImposterConfig;
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../sdk-conformance/corpus/imposters");
        let mut seen = 0;
        for entry in std::fs::read_dir(&dir).expect("read the corpus") {
            let path = entry.expect("corpus entry").path();
            if path.extension().is_none_or(|e| e != "json") {
                continue;
            }
            let text = std::fs::read_to_string(&path).expect("read corpus file");
            let loaded: ImposterConfig = serde_json::from_str(&text)
                .unwrap_or_else(|e| panic!("{}: decode: {e}", path.display()));
            let printed = serde_json::to_value(&loaded).expect("print");
            let reloaded: ImposterConfig = serde_json::from_value(printed)
                .unwrap_or_else(|e| panic!("{}: re-load: {e}", path.display()));
            assert_eq!(
                stub_keys(&loaded.stubs),
                stub_keys(&reloaded.stubs),
                "{}",
                path.display()
            );
            seen += 1;
        }
        assert!(seen > 0, "no corpus fixtures under {}", dir.display());
    }

    #[test]
    fn stub_key_ignores_json_key_order() {
        let a = stub(json!({
            "predicates": [{"equals": {"method": "GET", "path": "/p"}}],
            "responses": [{"is": {"headers": {"A": "1", "B": "2"}, "statusCode": 200}}]
        }));
        let b = stub(json!({
            "responses": [{"is": {"statusCode": 200, "headers": {"B": "2", "A": "1"}}}],
            "predicates": [{"equals": {"path": "/p", "method": "GET"}}]
        }));
        assert_eq!(stub_key(&a, 0), stub_key(&b, 0));
    }

    // AC3: determinism, occurrence suffixes, "~" disjointness from user ids.

    #[test]
    fn recorded_at_is_not_part_of_the_key() {
        // Issue #1759: when a proxy recorded a stub says nothing about what it does, and a node
        // that predates the field must key the same bytes the same way.
        let plain = one_resp("a");
        let mut recorded = one_resp("a");
        recorded.recorded_at = Some(1_700_000_000);
        assert_eq!(stub_key(&plain, 0), stub_key(&recorded, 0));
    }

    #[test]
    fn stub_key_is_deterministic_and_prefixed() {
        let a = one_resp("a");
        let b = one_resp("a");
        let key = stub_key(&a, 0);
        assert_eq!(
            key,
            stub_key(&b, 0),
            "same content must hash to the same key"
        );
        assert!(key.starts_with('~'), "generated keys carry the ~ prefix");
        assert!(key.ends_with("#0"));
        assert_eq!(
            key.len(),
            "~".len() + 16 + "#0".len(),
            "16-hex content hash"
        );
    }

    #[test]
    fn stub_key_uses_explicit_id_verbatim() {
        let mut s = one_resp("a");
        s.id = Some("checkout-flow".into());
        assert_eq!(stub_key(&s, 0), "checkout-flow");
        assert_eq!(
            stub_key(&s, 3),
            "checkout-flow",
            "occurrence is irrelevant for explicit ids"
        );
    }

    #[test]
    fn stub_key_occurrence_suffix_disambiguates_identical_siblings() {
        let s = one_resp("dup");
        let keys = stub_keys(&[s.clone(), s.clone(), one_resp("other")]);
        assert_eq!(keys.len(), 3);
        assert_ne!(
            keys[0], keys[1],
            "byte-identical siblings get distinct keys"
        );
        assert!(keys[0].ends_with("#0"));
        assert!(keys[1].ends_with("#1"));
        assert!(keys[2].ends_with("#0"));
        assert_ne!(keys[0], keys[2]);
    }

    #[test]
    fn stub_key_content_change_changes_key() {
        assert_ne!(stub_key(&one_resp("a"), 0), stub_key(&one_resp("b"), 0));
    }

    // AC2a: a stub-level patch preserves untouched stubs' cursors.

    #[test]
    fn patch_preserves_untouched_stub_cursors() {
        let mut states = vec![
            st(two_resp("a1", "a2")),
            st(one_resp("b")),
            st(one_resp("c")),
        ];
        assert_eq!(next_body(&states[0]), "a1");

        let desired = vec![two_resp("a1", "a2"), one_resp("b"), one_resp("c2")];
        let outcome = reconcile_stub_states(&mut states, desired);
        assert!(matches!(outcome, StubReconcile::Patched { .. }));
        assert_eq!(states.len(), 3);
        assert_eq!(
            next_body(&states[0]),
            "a2",
            "untouched stub keeps its cursor"
        );
        assert_eq!(next_body(&states[2]), "c2", "changed stub swapped in");
    }

    // AC2b: a pure reorder converges without resetting any cursor.

    #[test]
    fn pure_reorder_preserves_all_cursors() {
        let mut states = vec![st(two_resp("a1", "a2")), st(two_resp("b1", "b2"))];
        assert_eq!(next_body(&states[0]), "a1");
        assert_eq!(next_body(&states[1]), "b1");

        let desired = vec![two_resp("b1", "b2"), two_resp("a1", "a2")];
        let outcome = reconcile_stub_states(&mut states, desired);
        assert!(matches!(outcome, StubReconcile::Patched { .. }));
        assert_eq!(next_body(&states[0]), "b2", "moved stub keeps its cursor");
        assert_eq!(next_body(&states[1]), "a2", "moved stub keeps its cursor");
    }

    // AC2c: > 50 % of stubs changing is degenerate — no in-place mutation.

    #[test]
    fn degenerate_ratio_falls_back_without_mutating() {
        let mut states = vec![st(one_resp("a")), st(one_resp("b"))];
        let outcome = reconcile_stub_states(&mut states, vec![one_resp("x"), one_resp("y")]);
        assert!(matches!(outcome, StubReconcile::Degenerate));
        assert_eq!(
            next_body(&states[0]),
            "a",
            "a degenerate outcome must not mutate the live stubs"
        );
        assert_eq!(next_body(&states[1]), "b");
    }

    #[test]
    fn identical_stubs_are_unchanged() {
        let mut states = vec![st(one_resp("a")), st(one_resp("b"))];
        let outcome = reconcile_stub_states(&mut states, vec![one_resp("a"), one_resp("b")]);
        assert!(matches!(outcome, StubReconcile::Unchanged));
    }

    #[test]
    fn same_id_content_change_patches_in_place_keeping_cursor() {
        let mut with_id = two_resp("v1a", "v1b");
        with_id.id = Some("s1".into());
        let mut states = vec![st(with_id), st(one_resp("b")), st(one_resp("c"))];
        assert_eq!(next_body(&states[0]), "v1a");

        let mut updated = two_resp("v2a", "v2b");
        updated.id = Some("s1".into());
        let outcome =
            reconcile_stub_states(&mut states, vec![updated, one_resp("b"), one_resp("c")]);
        assert!(matches!(outcome, StubReconcile::Patched { .. }));
        assert_eq!(
            next_body(&states[0]),
            "v2b",
            "in-place id replace keeps the slot's cursor"
        );
    }

    #[test]
    fn insertion_below_threshold_patches() {
        let mut states = vec![
            st(two_resp("a1", "a2")),
            st(one_resp("b")),
            st(one_resp("c")),
        ];
        assert_eq!(next_body(&states[0]), "a1");

        let desired = vec![
            two_resp("a1", "a2"),
            one_resp("new"),
            one_resp("b"),
            one_resp("c"),
        ];
        let outcome = reconcile_stub_states(&mut states, desired);
        assert!(matches!(outcome, StubReconcile::Patched { .. }));
        assert_eq!(states.len(), 4);
        assert_eq!(next_body(&states[0]), "a2");
        assert_eq!(next_body(&states[1]), "new");
    }
}