greentic-runner-host 1.2.2

Host runtime shim for Greentic runner: config, pack loading, activity handling
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
use std::str::FromStr;
use std::sync::Arc;

use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
use greentic_state::inmemory::InMemoryStateStore;
use greentic_state::{StateKey as StoreStateKey, StateStore};
use greentic_types::{EnvId, TenantCtx, TenantId};
use serde_json::Value;

use crate::engine::error::{GResult, RunnerError};
use crate::engine::host::{SessionKey, StateHost};
use crate::fault::wrap_state_store;
use crate::storage::config::StateBackend;
use crate::storage::offload::{Offloaded, StoreKind};

pub type DynStateStore = Arc<dyn StateStore>;

pub(crate) const STATE_PREFIX: &str = "runner";

/// Adapter that backs the runner state host with a greentic-state store.
///
/// The store is held behind [`Offloaded`], so every call reaches it through
/// `spawn_blocking`. `StateStore` is a synchronous trait, and its Redis
/// implementation is a blocking `redis::Connection` behind a mutex — calling it
/// straight from these `async fn`s would park a tokio worker on a socket AND
/// serialise every state access in the process behind one connection.
pub struct StateStoreHost {
    store: Offloaded<dyn StateStore>,
    /// Expiry applied to every `set_json`. `None` keeps entries until deleted.
    ttl_secs: Option<u32>,
}

/// Env var bounding the lifetime of flow state (seconds). Unset or `0` keeps
/// the historical "never expires" behaviour, which on Redis means abandoned
/// conversations leave permanent keys.
pub const STATE_TTL_ENV: &str = "GREENTIC_FLOW_STATE_TTL_SECS";

impl StateStoreHost {
    pub fn new(store: DynStateStore) -> Self {
        Self {
            store: Offloaded::new(store, StoreKind::State),
            ttl_secs: None,
        }
    }

    /// Expire every state entry written through this host after `ttl_secs`.
    #[must_use]
    pub fn with_ttl_secs(mut self, ttl_secs: Option<u32>) -> Self {
        self.ttl_secs = ttl_secs.filter(|secs| *secs > 0);
        self
    }
}

fn ttl_from_env() -> Option<u32> {
    parse_ttl(std::env::var(STATE_TTL_ENV).ok().as_deref())
}

/// Parse the TTL setting. `0`/unset means "never expire"; a value above
/// `u32::MAX` is clamped (and warned about) rather than silently disabling the
/// TTL; an unparsable value is warned about and ignored.
fn parse_ttl(raw: Option<&str>) -> Option<u32> {
    let raw = raw?.trim();
    match raw.parse::<u64>() {
        Ok(0) => None,
        Ok(secs) => match u32::try_from(secs) {
            Ok(secs) => Some(secs),
            Err(_) => {
                tracing::warn!(
                    value = secs,
                    max = u32::MAX,
                    "{STATE_TTL_ENV} exceeds the maximum; clamping"
                );
                Some(u32::MAX)
            }
        },
        Err(_) => {
            tracing::warn!(
                value = raw,
                "{STATE_TTL_ENV} is not a valid number of seconds; flow state will not expire"
            );
            None
        }
    }
}

pub fn new_state_store() -> DynStateStore {
    let store: DynStateStore = Arc::new(InMemoryStateStore::new());
    wrap_state_store(store)
}

/// Build the flow-state store named by `backend`.
///
/// Unlike the session store this needs no namespace: `greentic_state::key::fqn`
/// already scopes every key by environment and tenant. See
/// [`crate::storage::config`] for the evidence.
pub fn store_from_config(backend: &StateBackend) -> Result<DynStateStore> {
    match backend {
        StateBackend::InMemory => Ok(new_state_store()),
        StateBackend::Redis { url } => {
            let store = greentic_state::redis_store::RedisStateStore::from_url(url)
                .map_err(|err| anyhow!("{err}"))
                .context("failed to open the Redis flow-state store")?;
            let store: DynStateStore = Arc::new(store);
            probe(&store)?;
            Ok(wrap_state_store(store))
        }
    }
}

/// Force a connection so an unreachable backend fails at construction rather
/// than mid-turn. `RedisStateStore::from_url` only parses the URL.
fn probe(store: &DynStateStore) -> Result<()> {
    let ctx = TenantCtx::new(
        EnvId::from_str("local").map_err(|err| anyhow!("{err}"))?,
        TenantId::from_str("greenticprobe").map_err(|err| anyhow!("{err}"))?,
    );
    store
        .get_json(
            &ctx,
            STATE_PREFIX,
            &StoreStateKey::from("startup-probe"),
            None,
        )
        .map(|_| ())
        .map_err(|err| anyhow!("{err}"))
        .context("the configured Redis flow-state store is unreachable")
}

pub fn state_host_from(store: DynStateStore) -> Arc<dyn StateHost> {
    Arc::new(StateStoreHost::new(store).with_ttl_secs(ttl_from_env()))
}

#[async_trait]
impl StateHost for StateStoreHost {
    async fn get_json(&self, key: &SessionKey) -> GResult<Option<Value>> {
        let tenant = tenant_ctx_from_key(key)?;
        let state_key = derive_state_key(key);
        let legacy_key = legacy_state_key(key);
        let ttl_secs = self.ttl_secs;
        self.store
            .call(move |store| {
                if let Some(value) = store.get_json(&tenant, STATE_PREFIX, &state_key, None)? {
                    return Ok(Some(value));
                }
                // Ids containing `%` or `/` were stored under an unescaped key
                // before escaping was introduced: migrate on read.
                let Some(legacy_key) = legacy_key else {
                    return Ok(None);
                };
                let Some(value) = store.get_json(&tenant, STATE_PREFIX, &legacy_key, None)? else {
                    return Ok(None);
                };
                // Write-if-absent: a `set_json` that landed on the current key
                // between the read above and this write is NEWER than the legacy
                // value, and a plain `set_json` here would overwrite it with the
                // stale one. A backend without the primitive (its default is an
                // error) keeps the old unconditional write.
                let value = match store.set_json_if_absent(
                    &tenant,
                    STATE_PREFIX,
                    &state_key,
                    &value,
                    ttl_secs,
                ) {
                    Ok(true) => value,
                    Ok(false) => store
                        .get_json(&tenant, STATE_PREFIX, &state_key, None)?
                        .unwrap_or(value),
                    Err(_) => {
                        store.set_json(
                            &tenant,
                            STATE_PREFIX,
                            &state_key,
                            None,
                            &value,
                            ttl_secs,
                        )?;
                        value
                    }
                };
                store.del(&tenant, STATE_PREFIX, &legacy_key)?;
                Ok(Some(value))
            })
            .await
            .map_err(map_state_error)
    }

    async fn set_json(&self, key: &SessionKey, value: Value) -> GResult<()> {
        let tenant = tenant_ctx_from_key(key)?;
        let state_key = derive_state_key(key);
        let ttl_secs = self.ttl_secs;
        self.store
            .call(move |store| {
                store.set_json(&tenant, STATE_PREFIX, &state_key, None, &value, ttl_secs)
            })
            .await
            .map_err(map_state_error)
    }

    async fn del(&self, key: &SessionKey) -> GResult<()> {
        let tenant = tenant_ctx_from_key(key)?;
        let state_key = derive_state_key(key);
        let legacy_key = legacy_state_key(key);
        self.store
            .call(move |store| {
                if let Some(legacy_key) = &legacy_key {
                    store.del(&tenant, STATE_PREFIX, legacy_key)?;
                }
                store.del(&tenant, STATE_PREFIX, &state_key)
            })
            .await
            .map_err(map_state_error)?;
        Ok(())
    }

    async fn del_prefix(&self, _key_prefix: &str) -> GResult<()> {
        // Deliberately NOT forwarded: `RedisStateStore::del_prefix` runs an
        // unbounded `SCAN MATCH` across the whole keyspace, which on a shared
        // Redis is a cost paid by every other tenant on the box. It used to
        // return `Ok(())`, which told the caller the keys were deleted when
        // they were not; it now reports the operation as unsupported so the
        // caller finds out. Pinned by `del_prefix_is_unsupported_and_never_reaches_the_backing_store`.
        Err(RunnerError::State {
            reason: "del_prefix is not supported by the durable state store".to_string(),
        })
    }
}

fn tenant_ctx_from_key(key: &SessionKey) -> GResult<TenantCtx> {
    let (env, tenant) = key
        .tenant_key
        .split_once("::")
        .ok_or_else(|| RunnerError::State {
            reason: format!("invalid tenant descriptor '{}'", key.tenant_key),
        })?;
    let env_id = EnvId::from_str(env).map_err(|err| RunnerError::State {
        reason: format!("invalid env id {env}: {err}"),
    })?;
    let tenant_id = TenantId::from_str(tenant).map_err(|err| RunnerError::State {
        reason: format!("invalid tenant id {tenant}: {err}"),
    })?;
    Ok(TenantCtx::new(env_id, tenant_id))
}

/// Escape `%` and `/` so a segment can never contain the key separator.
fn escape_segment(segment: &str) -> String {
    let mut out = String::with_capacity(segment.len());
    for ch in segment.chars() {
        match ch {
            '%' => out.push_str("%25"),
            '/' => out.push_str("%2F"),
            other => out.push(other),
        }
    }
    out
}

/// Injective key for one session's state.
///
/// Segments are escaped (`%` and `/`), so `pack/a/flow/b/session/x` cannot be
/// produced by a different `(pack, flow, hint)` triple. `-` is the marker for
/// "no hint"; a literal `-` hint is escaped to `%2D` so the two cannot alias.
/// Keys without `%`, `/` or a bare `-` hint are identical to the historical
/// format, so existing state stays addressable; for ids that DO contain `%` or
/// `/` the historical (unescaped) key is [`legacy_state_key`], which
/// `get_json` falls back to and migrates from.
fn derive_state_key(key: &SessionKey) -> StoreStateKey {
    let hint = match key.session_hint.as_deref() {
        None => "-".to_string(),
        Some("-") => "%2D".to_string(),
        Some(hint) => escape_segment(hint),
    };
    StoreStateKey::from(format!(
        "pack/{}/flow/{}/session/{hint}",
        escape_segment(&key.pack_id),
        escape_segment(&key.flow_id),
    ))
}

/// The pre-escaping key for `key`, when it differs from [`derive_state_key`].
///
/// `None` for a literal `-` hint: its historical key is the "no hint" key, so
/// reading it back would hand one session another's state.
fn legacy_state_key(key: &SessionKey) -> Option<StoreStateKey> {
    if key.session_hint.as_deref() == Some("-") {
        return None;
    }
    // Only a raw `/` makes the legacy key distinguishable: it then has more
    // than five slashes, so it can never equal any escaped (current) key. A
    // `%`-only id's legacy key can equal ANOTHER session's current key
    // (`a/b` escapes to `a%2Fb`, which is the raw hint `a%2Fb`'s legacy key),
    // so falling back to it would read, migrate and delete that session's state.
    let has_slash = key.pack_id.contains('/')
        || key.flow_id.contains('/')
        || key.session_hint.as_deref().is_some_and(|h| h.contains('/'));
    if !has_slash {
        return None;
    }
    let hint = key.session_hint.as_deref().unwrap_or("-");
    let legacy = StoreStateKey::from(format!(
        "pack/{}/flow/{}/session/{hint}",
        key.pack_id, key.flow_id
    ));
    (legacy != derive_state_key(key)).then_some(legacy)
}

fn map_state_error(err: greentic_types::GreenticError) -> RunnerError {
    RunnerError::State {
        reason: err.to_string(),
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn ttl_parsing_clamps_instead_of_disabling() {
        use super::parse_ttl;
        assert_eq!(parse_ttl(None), None);
        assert_eq!(parse_ttl(Some("0")), None);
        assert_eq!(parse_ttl(Some(" 3600 ")), Some(3600));
        assert_eq!(parse_ttl(Some("4294967295")), Some(u32::MAX));
        assert_eq!(parse_ttl(Some("4294967296")), Some(u32::MAX));
        assert_eq!(parse_ttl(Some("99999999999999")), Some(u32::MAX));
        assert_eq!(parse_ttl(Some("abc")), None);
        assert_eq!(parse_ttl(Some("-5")), None);
    }

    use super::*;
    use greentic_state::StatePath;
    use greentic_types::GResult as TypesResult;
    use std::sync::Mutex;

    /// Records every call that reaches the backing store.
    #[derive(Default)]
    struct RecordingStore {
        calls: Mutex<Vec<String>>,
    }

    impl RecordingStore {
        fn calls(&self) -> Vec<String> {
            self.calls.lock().map(|c| c.clone()).unwrap_or_default()
        }

        fn record(&self, call: &str) {
            if let Ok(mut calls) = self.calls.lock() {
                calls.push(call.to_string());
            }
        }
    }

    impl StateStore for RecordingStore {
        fn get_json(
            &self,
            _tenant: &TenantCtx,
            _prefix: &str,
            _key: &StoreStateKey,
            _path: Option<&StatePath>,
        ) -> TypesResult<Option<Value>> {
            self.record("get_json");
            Ok(None)
        }

        fn set_json(
            &self,
            _tenant: &TenantCtx,
            _prefix: &str,
            _key: &StoreStateKey,
            _path: Option<&StatePath>,
            _value: &Value,
            _ttl_secs: Option<u32>,
        ) -> TypesResult<()> {
            self.record("set_json");
            Ok(())
        }

        fn set_json_if_absent(
            &self,
            _tenant: &TenantCtx,
            _prefix: &str,
            _key: &StoreStateKey,
            _value: &Value,
            _ttl_secs: Option<u32>,
        ) -> TypesResult<bool> {
            self.record("set_json_if_absent");
            Ok(true)
        }

        fn del(
            &self,
            _tenant: &TenantCtx,
            _prefix: &str,
            _key: &StoreStateKey,
        ) -> TypesResult<bool> {
            self.record("del");
            Ok(true)
        }

        fn del_prefix(&self, _tenant: &TenantCtx, _prefix: &str) -> TypesResult<u64> {
            self.record("del_prefix");
            Ok(0)
        }
    }

    fn sample_key() -> SessionKey {
        SessionKey {
            tenant_key: "local::demo".into(),
            pack_id: "pack.demo".into(),
            flow_id: "flow.main".into(),
            session_hint: Some("hint".into()),
        }
    }

    /// `RedisStateStore::del_prefix` walks the WHOLE keyspace with an unbounded
    /// `SCAN MATCH`, a cost every other tenant on a shared Redis pays. Nothing
    /// in this crate needs prefix deletion, so the adapter refuses it (rather
    /// than pretending to succeed) without touching the store. If that ever
    /// changes it must be a decision, and this test is what forces it to be one.
    #[tokio::test]
    async fn del_prefix_is_unsupported_and_never_reaches_the_backing_store() {
        let store = Arc::new(RecordingStore::default());
        let host = StateStoreHost::new(store.clone());

        assert!(host.del_prefix("runner/pack").await.is_err());

        assert!(
            store.calls().is_empty(),
            "del_prefix forwarded to the backing store: {:?}",
            store.calls()
        );
    }

    /// The other three DO reach it — so the test above is about `del_prefix`
    /// and not about a host that forwards nothing.
    #[tokio::test]
    async fn the_other_operations_do_reach_the_backing_store() {
        let store = Arc::new(RecordingStore::default());
        let host = StateStoreHost::new(store.clone());
        let key = sample_key();

        host.set_json(&key, Value::Null).await.expect("set");
        host.get_json(&key).await.expect("get");
        host.del(&key).await.expect("del");

        assert_eq!(store.calls(), vec!["set_json", "get_json", "del"]);
    }

    #[test]
    fn state_keys_do_not_alias() {
        let mut a = sample_key();
        a.pack_id = "p/flow/f".into();
        a.flow_id = "x".into();
        let mut b = sample_key();
        b.pack_id = "p".into();
        b.flow_id = "f/session/h".into();
        b.session_hint = None;
        assert_ne!(derive_state_key(&a), derive_state_key(&b));

        let mut none = sample_key();
        none.session_hint = None;
        let mut dash = sample_key();
        dash.session_hint = Some("-".into());
        assert_ne!(derive_state_key(&none), derive_state_key(&dash));

        // Plain keys keep the historical shape.
        assert_eq!(
            derive_state_key(&sample_key()),
            StoreStateKey::from("pack/pack.demo/flow/flow.main/session/hint")
        );
    }

    #[derive(Default)]
    struct TtlRecorder(Mutex<Vec<Option<u32>>>);

    impl StateStore for TtlRecorder {
        fn get_json(
            &self,
            _t: &TenantCtx,
            _p: &str,
            _k: &StoreStateKey,
            _path: Option<&StatePath>,
        ) -> TypesResult<Option<Value>> {
            Ok(None)
        }
        fn set_json(
            &self,
            _t: &TenantCtx,
            _p: &str,
            _k: &StoreStateKey,
            _path: Option<&StatePath>,
            _v: &Value,
            ttl_secs: Option<u32>,
        ) -> TypesResult<()> {
            if let Ok(mut seen) = self.0.lock() {
                seen.push(ttl_secs);
            }
            Ok(())
        }
        fn set_json_if_absent(
            &self,
            _t: &TenantCtx,
            _p: &str,
            _k: &StoreStateKey,
            _v: &Value,
            _ttl: Option<u32>,
        ) -> TypesResult<bool> {
            Ok(true)
        }
        fn del(&self, _t: &TenantCtx, _p: &str, _k: &StoreStateKey) -> TypesResult<bool> {
            Ok(true)
        }
        fn del_prefix(&self, _t: &TenantCtx, _p: &str) -> TypesResult<u64> {
            Ok(0)
        }
    }

    #[tokio::test]
    async fn configured_ttl_reaches_set_json() {
        let store = Arc::new(TtlRecorder::default());
        let host = StateStoreHost::new(store.clone()).with_ttl_secs(Some(90));
        host.set_json(&sample_key(), Value::Null)
            .await
            .expect("set");
        let plain = StateStoreHost::new(store.clone());
        plain
            .set_json(&sample_key(), Value::Null)
            .await
            .expect("set");
        let zero = StateStoreHost::new(store.clone()).with_ttl_secs(Some(0));
        zero.set_json(&sample_key(), Value::Null)
            .await
            .expect("set");
        let seen = store.0.lock().map(|v| v.clone()).unwrap_or_default();
        assert_eq!(seen, vec![Some(90), None, None]);
    }

    #[tokio::test]
    async fn state_under_a_pre_escaping_key_is_found_and_migrated() {
        let store = Arc::new(InMemoryStateStore::new());
        let host = StateStoreHost::new(store.clone());
        let mut key = sample_key();
        key.flow_id = "flow/main%x".into();
        let tenant = tenant_ctx_from_key(&key).expect("tenant");
        let legacy = legacy_state_key(&key).expect("differs from current key");
        assert_ne!(legacy, derive_state_key(&key));
        let value = serde_json::json!({"n": 1});
        store
            .set_json(&tenant, STATE_PREFIX, &legacy, None, &value, None)
            .expect("seed");

        assert_eq!(host.get_json(&key).await.expect("get"), Some(value.clone()));
        // Migrated: legacy key gone, current key populated.
        assert!(
            store
                .get_json(&tenant, STATE_PREFIX, &legacy, None)
                .expect("legacy")
                .is_none()
        );
        assert_eq!(
            store
                .get_json(&tenant, STATE_PREFIX, &derive_state_key(&key), None)
                .expect("current"),
            Some(value)
        );
    }

    /// An in-memory store that, right after the LEGACY key is read, lets a
    /// concurrent `set_json` land on the current key (the migrate-on-read race).
    struct RacingStore {
        inner: InMemoryStateStore,
        legacy: StoreStateKey,
        current: StoreStateKey,
        newer: Value,
        supports_if_absent: bool,
    }

    impl StateStore for RacingStore {
        fn get_json(
            &self,
            tenant: &TenantCtx,
            prefix: &str,
            key: &StoreStateKey,
            path: Option<&greentic_state::StatePath>,
        ) -> greentic_types::GResult<Option<Value>> {
            let found = self.inner.get_json(tenant, prefix, key, path)?;
            if *key == self.legacy && found.is_some() {
                self.inner
                    .set_json(tenant, prefix, &self.current, None, &self.newer, None)?;
            }
            Ok(found)
        }

        fn set_json(
            &self,
            tenant: &TenantCtx,
            prefix: &str,
            key: &StoreStateKey,
            path: Option<&greentic_state::StatePath>,
            value: &Value,
            ttl_secs: Option<u32>,
        ) -> greentic_types::GResult<()> {
            self.inner
                .set_json(tenant, prefix, key, path, value, ttl_secs)
        }

        fn del(
            &self,
            tenant: &TenantCtx,
            prefix: &str,
            key: &StoreStateKey,
        ) -> greentic_types::GResult<bool> {
            self.inner.del(tenant, prefix, key)
        }

        fn del_prefix(&self, tenant: &TenantCtx, prefix: &str) -> greentic_types::GResult<u64> {
            self.inner.del_prefix(tenant, prefix)
        }

        fn set_json_if_absent(
            &self,
            tenant: &TenantCtx,
            prefix: &str,
            key: &StoreStateKey,
            value: &Value,
            ttl_secs: Option<u32>,
        ) -> greentic_types::GResult<bool> {
            if self.supports_if_absent {
                self.inner
                    .set_json_if_absent(tenant, prefix, key, value, ttl_secs)
            } else {
                Err(greentic_types::GreenticError::new(
                    greentic_types::ErrorCode::InvalidInput,
                    "unsupported",
                ))
            }
        }
    }

    #[tokio::test]
    async fn migration_does_not_overwrite_a_write_that_raced_it() {
        let mut key = sample_key();
        key.flow_id = "flow/main%x".into();
        let tenant = tenant_ctx_from_key(&key).expect("tenant");
        let legacy = legacy_state_key(&key).expect("differs from current key");
        let current = derive_state_key(&key);
        let stale = serde_json::json!({"n": "stale"});
        let newer = serde_json::json!({"n": "newer"});
        let store = Arc::new(RacingStore {
            inner: InMemoryStateStore::new(),
            legacy: legacy.clone(),
            current: current.clone(),
            newer: newer.clone(),
            supports_if_absent: true,
        });
        store
            .inner
            .set_json(&tenant, STATE_PREFIX, &legacy, None, &stale, None)
            .expect("seed");
        let host = StateStoreHost::new(store.clone());

        // The racing write wins: the caller sees it, and so does the store.
        assert_eq!(host.get_json(&key).await.expect("get"), Some(newer.clone()));
        assert_eq!(
            store
                .inner
                .get_json(&tenant, STATE_PREFIX, &current, None)
                .expect("current"),
            Some(newer)
        );
        assert!(
            store
                .inner
                .get_json(&tenant, STATE_PREFIX, &legacy, None)
                .expect("legacy")
                .is_none(),
            "the legacy key is still removed"
        );
    }

    #[tokio::test]
    async fn migration_falls_back_to_a_plain_write_without_if_absent_support() {
        let mut key = sample_key();
        key.flow_id = "flow/main%x".into();
        let tenant = tenant_ctx_from_key(&key).expect("tenant");
        let legacy = legacy_state_key(&key).expect("differs from current key");
        let current = derive_state_key(&key);
        let value = serde_json::json!({"n": 2});
        let store = Arc::new(RacingStore {
            inner: InMemoryStateStore::new(),
            legacy: legacy.clone(),
            current: current.clone(),
            newer: value.clone(),
            supports_if_absent: false,
        });
        // No racing write here: seed only the legacy key, with the race value
        // equal to it, so the fallback path is what is observed.
        store
            .inner
            .set_json(&tenant, STATE_PREFIX, &legacy, None, &value, None)
            .expect("seed");
        let host = StateStoreHost::new(store.clone());
        assert_eq!(host.get_json(&key).await.expect("get"), Some(value.clone()));
        assert_eq!(
            store
                .inner
                .get_json(&tenant, STATE_PREFIX, &current, None)
                .expect("current"),
            Some(value)
        );
    }

    #[tokio::test]
    async fn percent_only_ids_never_touch_another_sessions_current_key() {
        let store = Arc::new(InMemoryStateStore::new());
        let host = StateStoreHost::new(store.clone());
        let mut a = sample_key();
        a.session_hint = Some("a/b".into());
        let mut b = sample_key();
        b.session_hint = Some("a%2Fb".into());
        assert!(legacy_state_key(&b).is_none());
        let value = serde_json::json!({"owner": "a"});
        host.set_json(&a, value.clone()).await.expect("set a");

        assert_eq!(host.get_json(&b).await.expect("get b"), None);
        host.del(&b).await.expect("del b");
        assert_eq!(host.get_json(&a).await.expect("get a"), Some(value));
    }

    #[test]
    fn plain_ids_and_a_dash_hint_have_no_legacy_key() {
        let mut key = sample_key();
        assert!(legacy_state_key(&key).is_none());
        key.session_hint = Some("-".into());
        assert!(legacy_state_key(&key).is_none());
    }

    /// The in-memory default must still be reachable with no configuration.
    #[test]
    fn the_default_backend_is_in_memory() {
        assert!(store_from_config(&StateBackend::InMemory).is_ok());
        assert!(!StateBackend::InMemory.is_durable());
    }
}