xenith-sync 0.1.0

State sync engine for xenith — push, read, and resolve across chains
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use backon::{ExponentialBuilder, Retryable};
use bytes::Bytes;
use xenith_core::{
    wire, ChainId, ConflictResolver, KeyMetadata, MessageId, MessagingTransport, ReadStrategy,
    Result, SendOptions, StateKey, StateStore, StateValue, StateVersion, SyncStatus, SyncedState,
    XenithError,
};
use xenith_read::MultiChainReader;

use crate::subscription::SubscriptionHandle;

/// Configuration for a [`SyncEngine`] instance.
pub struct SyncConfig {
    /// Number of times to retry a failed transport send before giving up.
    pub retry_attempts: u32,
    /// Base delay in milliseconds between retry attempts.
    pub retry_delay_ms: u64,
    /// Strategy used when no explicit strategy is supplied to [`SyncEngine::read`].
    pub default_strategy: ReadStrategy,
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            retry_attempts: 3,
            retry_delay_ms: 500,
            default_strategy: ReadStrategy::Latest,
        }
    }
}

/// The result of a [`SyncEngine::push`] call.
///
/// `successes` carries one entry per chain that accepted the message.
/// `failures` captures per-chain errors so the caller can retry selectively.
/// A push that encounters errors on *some* chains never returns `Err` — it
/// returns `Ok` with a [`SyncStatus::PartialFailure`] status instead.
///
/// `store_written` is `true` only when the local store was actually updated.
/// If every send failed and `targets` was non-empty, the store is left
/// untouched and `store_written` is `false`.
#[derive(Clone, Debug)]
pub struct SyncReceipt {
    pub key: StateKey,
    /// Chains that accepted the message: `(destination, message_id)`.
    pub successes: Vec<(ChainId, MessageId)>,
    /// Chains whose send failed: `(destination, error)`.
    pub failures: Vec<(ChainId, XenithError)>,
    pub status: SyncStatus,
    /// `true` if the local [`xenith_core::StateStore`] was updated.
    pub store_written: bool,
}

/// Orchestrates cross-chain state propagation.
///
/// Composes a [`MessagingTransport`] for sending messages and a [`StateStore`]
/// for local persistence. All strategy decisions are left to the caller.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use xenith_core::{InMemoryStore, ReadStrategy};
/// use xenith_sync::{SyncEngine, SyncConfig};
///
/// # async fn example(transport: Arc<dyn xenith_core::MessagingTransport>) {
/// let engine = SyncEngine::new(
///     transport,
///     Arc::new(InMemoryStore::default()),
///     SyncConfig::default(),
/// );
/// # }
/// ```
pub struct SyncEngine {
    pub transport: Arc<dyn MessagingTransport>,
    pub store: Arc<dyn StateStore>,
    pub config: SyncConfig,
    reader: Option<Arc<MultiChainReader>>,
}

impl SyncEngine {
    pub fn new(
        transport: Arc<dyn MessagingTransport>,
        store: Arc<dyn StateStore>,
        config: SyncConfig,
    ) -> Self {
        Self {
            transport,
            store,
            config,
            reader: None,
        }
    }

    /// Create a [`SyncEngine`] that can execute [`ReadStrategy::Quorum`] reads.
    ///
    /// The `reader` is used to issue parallel storage reads across all chains
    /// registered in its provider map when verifying on-chain agreement.
    pub fn new_with_reader(
        transport: Arc<dyn MessagingTransport>,
        store: Arc<dyn StateStore>,
        config: SyncConfig,
        reader: MultiChainReader,
    ) -> Self {
        Self {
            transport,
            store,
            config,
            reader: Some(Arc::new(reader)),
        }
    }

    /// Broadcast `value` to each chain in `targets`, then persist it locally.
    ///
    /// Pass `metadata` if you intend to use [`ReadStrategy::Quorum`] for this key.
    /// Metadata must include the EVM contract address and storage slot that
    /// corresponds to the value being synced. Without it, Quorum reads will fail.
    ///
    /// The store is written **only** when at least one send succeeded, or when
    /// `targets` is empty (local-only push). If every send fails the store is
    /// left untouched and [`SyncReceipt::store_written`] is `false`.
    ///
    /// Per-chain send errors are collected into [`SyncReceipt::failures`] rather
    /// than aborting early, so the caller can inspect and retry individual chains.
    pub async fn push(
        &self,
        key: StateKey,
        value: Bytes,
        targets: Vec<ChainId>,
        source: ChainId,
        metadata: Option<KeyMetadata>,
    ) -> Result<SyncReceipt> {
        let ts_ms = unix_now_ms()?;

        let state_value = StateValue {
            data: value.clone(),
            version: StateVersion {
                timestamp_ms: ts_ms,
                sequence: 0,
                source_chain: source.0,
            },
            updated_at: ts_ms / 1_000,
            source_chain: source,
        };

        let payload = wire::encode(&key, &state_value, metadata.as_ref());

        let mut successes: Vec<(ChainId, MessageId)> = Vec::with_capacity(targets.len());
        let mut failures: Vec<(ChainId, XenithError)> = Vec::new();

        for chain in &targets {
            match send_with_retry(
                Arc::clone(&self.transport),
                *chain,
                payload.clone(),
                SendOptions::default(),
                self.config.retry_attempts,
                self.config.retry_delay_ms,
            )
            .await
            {
                Ok(id) => successes.push((*chain, id)),
                Err(e) => failures.push((*chain, e)),
            }
        }

        // Only persist locally if at least one send succeeded, or if there were no
        // targets (local-only push). Skipping the write when all sends fail prevents
        // the store from holding state that was never propagated to any chain.
        // TODO v0.2: replace this conditional with a WAL (write-ahead log) so that
        // partially-propagated state survives crashes and can be retried on restart.
        let store_written = targets.is_empty() || !successes.is_empty();
        if store_written {
            self.store.set(&key, state_value.clone()).await?;
            if let Some(ref m) = metadata {
                self.store.set_metadata(&key, m.clone()).await?;
            }
        }

        let status = if failures.is_empty() {
            successes
                .first()
                .map(|&(_, id)| SyncStatus::Pending { message_id: id })
                .unwrap_or(SyncStatus::Synced)
        } else {
            SyncStatus::PartialFailure {
                succeeded: successes.iter().map(|&(c, _)| c).collect(),
                failed: failures.iter().map(|&(c, _)| c).collect(),
            }
        };

        Ok(SyncReceipt {
            key,
            successes,
            failures,
            status,
            store_written,
        })
    }

    /// Retrieve state for `key` and apply `strategy` to determine its sync status.
    pub async fn read(&self, key: StateKey, strategy: ReadStrategy) -> Result<SyncedState> {
        let value = self
            .store
            .get(&key)
            .await?
            .ok_or_else(|| XenithError::StoreError("key not found".into()))?;

        let chains = vec![value.source_chain];

        match strategy {
            ReadStrategy::SourceOfTruth(chain) => {
                let status = if value.source_chain == chain {
                    SyncStatus::Synced
                } else {
                    SyncStatus::Diverged {
                        chains: vec![(value.source_chain, value.clone())],
                    }
                };
                Ok(SyncedState {
                    key,
                    value,
                    chains,
                    status,
                })
            }

            ReadStrategy::Latest => Ok(SyncedState {
                key,
                value,
                chains,
                status: SyncStatus::Synced,
            }),

            ReadStrategy::Quorum(n) => {
                let reader = self.reader.as_ref().ok_or_else(|| {
                    XenithError::StoreError(
                        "Quorum strategy requires a MultiChainReader — \
                         use SyncEngine::new_with_reader"
                            .into(),
                    )
                })?;

                let meta = self.store.get_metadata(&key).await?.ok_or_else(|| {
                    XenithError::StoreError(
                        "Quorum read requires KeyMetadata (address + slot) — \
                             call store.set_metadata before pushing"
                            .into(),
                    )
                })?;

                let address = meta
                    .address
                    .ok_or_else(|| XenithError::StoreError("KeyMetadata.address is None".into()))?;
                let slot = meta
                    .slot
                    .ok_or_else(|| XenithError::StoreError("KeyMetadata.slot is None".into()))?;

                let target_chains: Vec<ChainId> = reader.providers.keys().copied().collect();
                let all_chains = target_chains.clone();
                let readings = reader.read_parallel(target_chains, address, slot).await?;

                // Count how many chains agree on each distinct raw slot value.
                let mut counts: HashMap<[u8; 32], usize> = HashMap::new();
                for (_, raw) in &readings {
                    *counts.entry(*raw).or_insert(0) += 1;
                }

                let max_count = counts.values().copied().max().unwrap_or(0);
                let status = if max_count >= n {
                    SyncStatus::Synced
                } else {
                    // Build per-chain StateValues from raw slot readings for the caller.
                    let diverged: Vec<(ChainId, StateValue)> = readings
                        .iter()
                        .map(|(chain, raw)| {
                            (
                                *chain,
                                StateValue {
                                    data: Bytes::copy_from_slice(raw.as_ref()),
                                    version: value.version,
                                    updated_at: value.updated_at,
                                    source_chain: *chain,
                                },
                            )
                        })
                        .collect();
                    SyncStatus::Diverged { chains: diverged }
                };

                Ok(SyncedState {
                    key,
                    value,
                    chains: all_chains,
                    status,
                })
            }

            ReadStrategy::Custom(f) => {
                let resolved = f(vec![(value.source_chain, value)]);
                let resolved_chain = resolved.source_chain;
                Ok(SyncedState {
                    key,
                    chains: vec![resolved_chain],
                    value: resolved,
                    status: SyncStatus::Synced,
                })
            }
        }
    }

    /// Resolve any divergence for `key` using the supplied resolver, persist the
    /// winner, and return it.
    pub async fn resolve(
        &self,
        key: StateKey,
        resolver: &dyn ConflictResolver,
    ) -> Result<StateValue> {
        let value = self
            .store
            .get(&key)
            .await?
            .ok_or_else(|| XenithError::StoreError("key not found".into()))?;

        let candidates = vec![(value.source_chain, value)];
        let resolved = resolver.resolve(&key, candidates).await?;
        self.store.set(&key, resolved.clone()).await?;
        Ok(resolved)
    }

    /// Subscribe to state updates for a key from a source chain.
    ///
    /// Fires `handler` whenever a new `StateValue` with a higher `StateVersion`
    /// is observed — either via incoming transport messages or via direct writes
    /// to the local store.
    ///
    /// # Poll interval guidance
    ///
    /// `poll_interval_ms` controls how frequently the transport is polled for
    /// incoming messages and the local store is checked for updates.
    ///
    /// Recommended values:
    /// - Testing / local development: 50–100ms
    /// - Production liquidation bots: 500–1000ms (1 RPC call per tick)
    /// - Production arbitrage bots: 200–500ms (latency-sensitive)
    ///
    /// Each tick issues one [`MessagingTransport::poll_incoming`] call to the
    /// transport, which typically maps to one `eth_getLogs` RPC call. Set the
    /// interval according to your RPC rate limits and latency requirements.
    ///
    /// # Cancellation
    ///
    /// Returns a [`SubscriptionHandle`]. Call `handle.cancel()` or pass it to
    /// [`SyncEngine::unsubscribe`] to stop the polling loop.
    pub async fn subscribe<F, Fut>(
        &self,
        key: StateKey,
        source: ChainId,
        poll_interval_ms: u64,
        handler: F,
    ) -> Result<SubscriptionHandle>
    where
        F: Fn(StateValue) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send,
    {
        let store = Arc::clone(&self.store);
        let transport = Arc::clone(&self.transport);
        let key_clone = key.clone();
        let interval = tokio::time::Duration::from_millis(poll_interval_ms);

        let join_handle = tokio::spawn(async move {
            let mut last_seen: Option<StateVersion> = None;
            loop {
                // Path 1: poll transport for incoming messages.
                if let Ok(messages) = transport.poll_incoming().await {
                    for (incoming_key, incoming_value, incoming_metadata) in messages {
                        if incoming_key == key_clone && incoming_value.source_chain == source {
                            let _ = store.set(&key_clone, incoming_value.clone()).await;
                            if let Some(ref m) = incoming_metadata {
                                let _ = store.set_metadata(&key_clone, m.clone()).await;
                            }
                            last_seen = Some(incoming_value.version);
                            handler(incoming_value).await;
                        }
                    }
                }

                // Path 2: check local store as fallback for values written directly.
                if let Ok(Some(value)) = store.get(&key_clone).await {
                    let is_newer = last_seen.map(|seen| value.version > seen).unwrap_or(true);
                    if is_newer {
                        last_seen = Some(value.version);
                        handler(value).await;
                    }
                }

                tokio::time::sleep(interval).await;
            }
        });

        Ok(SubscriptionHandle::new(
            key,
            source,
            join_handle.abort_handle(),
        ))
    }

    /// Cancel a subscription returned by [`subscribe`][SyncEngine::subscribe].
    pub async fn unsubscribe(&self, handle: SubscriptionHandle) {
        handle.cancel();
    }
}

/// Sends `payload` to `chain` via `transport`, retrying up to `attempts` times
/// with exponential backoff starting at `delay_ms`. Only `XenithError::Transport`
/// is considered transient; other errors are returned immediately without retrying.
async fn send_with_retry(
    transport: Arc<dyn MessagingTransport>,
    chain: ChainId,
    payload: Bytes,
    options: SendOptions,
    attempts: u32,
    delay_ms: u64,
) -> Result<MessageId> {
    let backoff = ExponentialBuilder::default()
        .with_max_times(attempts as usize)
        .with_min_delay(Duration::from_millis(delay_ms));

    (|| {
        let t = Arc::clone(&transport);
        let p = payload.clone();
        let o = options.clone();
        async move { t.send_message(chain, p, o).await }
    })
    .retry(&backoff)
    .when(|e| matches!(e, XenithError::Transport { .. }))
    .notify(|e, dur| {
        eprintln!(
            "xenith: transient error on chain {}: {e}; retrying in {dur:?}",
            chain.0
        );
    })
    .await
}

fn unix_now_ms() -> Result<u64> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .map_err(|_| XenithError::StoreError("system clock is before the Unix epoch".into()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use xenith_core::{InMemoryStore, LatestVersionResolver, ReadStrategy};
    use xenith_layerzero::LayerZeroTransport;

    fn make_engine(chains: &[(u64, u32)]) -> SyncEngine {
        let transport = Arc::new(LayerZeroTransport::new(
            [0u8; 20],
            chains
                .iter()
                .map(|&(c, eid)| (ChainId::from(c), eid))
                .collect(),
        ));
        let store = Arc::new(InMemoryStore::default());
        SyncEngine::new(transport, store, SyncConfig::default())
    }

    #[tokio::test]
    async fn push_then_read_source_of_truth() {
        // Ethereum mainnet is the source; target is Arbitrum.
        let engine = make_engine(&[(42161, 30110)]);
        let key = StateKey::new("uniswap", "pool", "0xabc");

        let receipt = engine
            .push(
                key.clone(),
                Bytes::from_static(b"price=100"),
                vec![ChainId(42161)],
                ChainId(1),
                None,
            )
            .await
            .unwrap();

        assert_eq!(receipt.successes.len(), 1);
        assert!(receipt.failures.is_empty());
        assert!(matches!(receipt.status, SyncStatus::Pending { .. }));

        // Reading from the declared source chain should yield Synced.
        let state = engine
            .read(key, ReadStrategy::SourceOfTruth(ChainId(1)))
            .await
            .unwrap();
        assert!(matches!(state.status, SyncStatus::Synced));
        assert_eq!(state.value.data, Bytes::from_static(b"price=100"));
        assert_eq!(state.value.source_chain, ChainId(1));
    }

    #[tokio::test]
    async fn push_then_read_wrong_source_of_truth_is_diverged() {
        let engine = make_engine(&[(42161, 30110)]);
        let key = StateKey::new("uniswap", "pool", "0xdef");

        engine
            .push(
                key.clone(),
                Bytes::from_static(b"v"),
                vec![ChainId(42161)],
                ChainId(1),
                None,
            )
            .await
            .unwrap();

        // Asking for chain 42161 as truth, but data originated on chain 1.
        let state = engine
            .read(key, ReadStrategy::SourceOfTruth(ChainId(42161)))
            .await
            .unwrap();
        assert!(matches!(state.status, SyncStatus::Diverged { .. }));
    }

    #[tokio::test]
    async fn push_then_resolve_latest_version() {
        let engine = make_engine(&[(42161, 30110)]);
        let key = StateKey::new("aave", "reserve", "0x1");

        engine
            .push(
                key.clone(),
                Bytes::from_static(b"ltv=0.8"),
                vec![ChainId(42161)],
                ChainId(1),
                None,
            )
            .await
            .unwrap();

        let resolved = engine
            .resolve(key.clone(), &LatestVersionResolver)
            .await
            .unwrap();
        assert_eq!(resolved.data, Bytes::from_static(b"ltv=0.8"));

        // Resolved value must be persisted — a subsequent read should see it.
        let state = engine.read(key, ReadStrategy::Latest).await.unwrap();
        assert_eq!(state.value.data, Bytes::from_static(b"ltv=0.8"));
    }

    #[tokio::test]
    async fn push_no_targets_yields_synced_receipt() {
        let engine = make_engine(&[]);
        let key = StateKey::new("proto", "x", "1");
        let receipt = engine
            .push(key, Bytes::from_static(b"d"), vec![], ChainId(1), None)
            .await
            .unwrap();
        assert!(receipt.successes.is_empty());
        assert!(receipt.failures.is_empty());
        assert!(matches!(receipt.status, SyncStatus::Synced));
    }

    #[tokio::test]
    async fn read_missing_key_returns_error() {
        let engine = make_engine(&[]);
        let err = engine
            .read(StateKey::new("x", "y", "z"), ReadStrategy::Latest)
            .await
            .unwrap_err();
        assert!(matches!(err, XenithError::StoreError(_)));
    }

    #[tokio::test]
    async fn push_to_unsupported_chain_is_partial_failure() {
        let engine = make_engine(&[]); // no chains registered
        let receipt = engine
            .push(
                StateKey::new("p", "q", "r"),
                Bytes::from_static(b"x"),
                vec![ChainId(42161)],
                ChainId(1),
                None,
            )
            .await
            .unwrap();
        assert_eq!(receipt.failures.len(), 1);
        assert!(matches!(
            receipt.failures[0].1,
            XenithError::UnsupportedChain(_)
        ));
        assert!(matches!(receipt.status, SyncStatus::PartialFailure { .. }));
    }

    #[tokio::test]
    async fn test_subscribe_fires_on_new_value() {
        use tokio::sync::mpsc;

        let store = Arc::new(InMemoryStore::default());
        let transport = Arc::new(LayerZeroTransport::new([0u8; 20], vec![]));
        let engine = SyncEngine::new(
            transport,
            Arc::clone(&store) as Arc<dyn StateStore>,
            SyncConfig::default(),
        );

        let key = StateKey::new("test", "pos", "u1");
        let (tx, mut rx) = mpsc::channel::<StateValue>(1);

        let handle = engine
            .subscribe(key.clone(), ChainId(1), 10, move |value| {
                let tx = tx.clone();
                async move {
                    let _ = tx.send(value).await;
                }
            })
            .await
            .unwrap();

        let new_value = StateValue {
            data: Bytes::from_static(b"new_data"),
            version: StateVersion {
                timestamp_ms: 1_000_000,
                sequence: 0,
                source_chain: 1,
            },
            updated_at: 1000,
            source_chain: ChainId(1),
        };
        store.set(&key, new_value.clone()).await.unwrap();

        let received = tokio::time::timeout(tokio::time::Duration::from_millis(200), rx.recv())
            .await
            .expect("timed out waiting for subscription event")
            .expect("channel closed");

        assert_eq!(received, new_value);
        handle.cancel();
    }

    #[tokio::test]
    async fn test_subscribe_fires_on_incoming_message() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use tokio::sync::mpsc;

        let key = StateKey::new("proto", "entity", "id1");
        let incoming_value = StateValue {
            data: Bytes::from_static(b"incoming_data"),
            version: StateVersion {
                timestamp_ms: 9_000_000,
                sequence: 0,
                source_chain: 1,
            },
            updated_at: 9000,
            source_chain: ChainId(1),
        };

        struct MockTransport {
            returned: AtomicBool,
            message: (StateKey, StateValue, Option<xenith_core::KeyMetadata>),
        }

        #[async_trait::async_trait]
        impl xenith_core::MessagingTransport for MockTransport {
            async fn send_message(
                &self,
                destination: ChainId,
                _: Bytes,
                _: SendOptions,
            ) -> xenith_core::Result<MessageId> {
                Err(XenithError::UnsupportedChain(destination))
            }
            async fn estimate_fee(&self, _: ChainId, _: Bytes) -> xenith_core::Result<u128> {
                Ok(0)
            }
            async fn message_status(
                &self,
                _: MessageId,
            ) -> xenith_core::Result<xenith_core::MessageStatus> {
                Ok(xenith_core::MessageStatus::Delivered)
            }
            fn sender_address(&self) -> Option<[u8; 20]> {
                None
            }
            async fn poll_incoming(
                &self,
            ) -> xenith_core::Result<
                Vec<(
                    xenith_core::StateKey,
                    xenith_core::StateValue,
                    Option<xenith_core::KeyMetadata>,
                )>,
            > {
                if self.returned.swap(true, Ordering::SeqCst) {
                    Ok(vec![])
                } else {
                    Ok(vec![self.message.clone()])
                }
            }
        }

        let (tx, mut rx) = mpsc::channel::<StateValue>(1);
        let store = Arc::new(InMemoryStore::default());

        let mock_transport = Arc::new(MockTransport {
            returned: AtomicBool::new(false),
            message: (key.clone(), incoming_value.clone(), None),
        });

        let engine = SyncEngine::new(
            mock_transport as Arc<dyn xenith_core::MessagingTransport>,
            Arc::clone(&store) as Arc<dyn StateStore>,
            SyncConfig::default(),
        );

        let handle = engine
            .subscribe(key.clone(), ChainId(1), 10, move |value| {
                let tx = tx.clone();
                async move {
                    let _ = tx.send(value).await;
                }
            })
            .await
            .unwrap();

        let received = tokio::time::timeout(tokio::time::Duration::from_millis(200), rx.recv())
            .await
            .expect("timed out waiting for subscription event from transport")
            .expect("channel closed");

        assert_eq!(received.data, Bytes::from_static(b"incoming_data"));
        assert_eq!(received.source_chain, ChainId(1));
        handle.cancel();
    }

    /// A transport that returns `XenithError::Transport` for the first `n` calls,
    /// then succeeds. Used to verify retry logic without hitting a real network.
    struct FailNTimesTransport {
        fail_count: Arc<std::sync::atomic::AtomicU32>,
        fail_times: u32,
    }

    impl FailNTimesTransport {
        fn new(fail_times: u32) -> (Arc<std::sync::atomic::AtomicU32>, Arc<Self>) {
            let counter = Arc::new(std::sync::atomic::AtomicU32::new(0));
            let t = Arc::new(Self {
                fail_count: Arc::clone(&counter),
                fail_times,
            });
            (counter, t)
        }
    }

    #[async_trait::async_trait]
    impl xenith_core::MessagingTransport for FailNTimesTransport {
        async fn send_message(
            &self,
            _destination: ChainId,
            _payload: Bytes,
            _options: SendOptions,
        ) -> xenith_core::Result<MessageId> {
            let prev = self
                .fail_count
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if prev < self.fail_times {
                Err(XenithError::Transport {
                    chain: ChainId(1),
                    message: "transient".into(),
                })
            } else {
                Ok(MessageId(prev as u64 + 1))
            }
        }

        async fn estimate_fee(
            &self,
            _destination: ChainId,
            _payload: Bytes,
        ) -> xenith_core::Result<u128> {
            Ok(0)
        }

        async fn message_status(
            &self,
            _message_id: MessageId,
        ) -> xenith_core::Result<xenith_core::MessageStatus> {
            Ok(xenith_core::MessageStatus::Delivered)
        }

        fn sender_address(&self) -> Option<[u8; 20]> {
            None
        }

        async fn poll_incoming(
            &self,
        ) -> xenith_core::Result<
            Vec<(
                xenith_core::StateKey,
                xenith_core::StateValue,
                Option<xenith_core::KeyMetadata>,
            )>,
        > {
            Ok(vec![])
        }
    }

    #[tokio::test]
    async fn push_retries_on_transport_error() {
        let (call_count, transport) = FailNTimesTransport::new(2);
        let engine = SyncEngine::new(
            transport as Arc<dyn xenith_core::MessagingTransport>,
            Arc::new(InMemoryStore::default()),
            SyncConfig {
                retry_attempts: 3,
                retry_delay_ms: 1, // fast for tests
                ..SyncConfig::default()
            },
        );

        let receipt = engine
            .push(
                StateKey::new("test", "retry", "1"),
                Bytes::from_static(b"v"),
                vec![ChainId(1)],
                ChainId(1),
                None,
            )
            .await
            .unwrap();

        // Two failures then one success = 3 total calls.
        assert_eq!(
            call_count.load(std::sync::atomic::Ordering::SeqCst),
            3,
            "expected 3 calls (2 failures + 1 success)"
        );
        assert_eq!(receipt.successes.len(), 1);
        assert!(receipt.failures.is_empty());
    }

    #[tokio::test]
    async fn push_does_not_retry_unsupported_chain() {
        // UnsupportedChain is permanent — should not be retried.
        let (call_count, transport) = FailNTimesTransport::new(u32::MAX);
        let _engine = SyncEngine::new(
            transport as Arc<dyn xenith_core::MessagingTransport>,
            Arc::new(InMemoryStore::default()),
            SyncConfig {
                retry_attempts: 3,
                retry_delay_ms: 1,
                ..SyncConfig::default()
            },
        );

        // FailNTimesTransport always returns Transport errors, but let's use a mock
        // that sends UnsupportedChain directly. We test the when() predicate instead:
        // the call_count should be exactly 1 because the error variant is not Transport.
        // (FailNTimesTransport emits Transport errors, so this test verifies the
        // opposite: that a non-Transport error stops immediately without retry.)
        // We use a dedicated impl for this case.
        struct UnsupportedTransport;
        #[async_trait::async_trait]
        impl xenith_core::MessagingTransport for UnsupportedTransport {
            async fn send_message(
                &self,
                destination: ChainId,
                _payload: Bytes,
                _options: SendOptions,
            ) -> xenith_core::Result<MessageId> {
                Err(XenithError::UnsupportedChain(destination))
            }
            async fn estimate_fee(
                &self,
                _dst: ChainId,
                _payload: Bytes,
            ) -> xenith_core::Result<u128> {
                Ok(0)
            }
            async fn message_status(
                &self,
                _id: MessageId,
            ) -> xenith_core::Result<xenith_core::MessageStatus> {
                Ok(xenith_core::MessageStatus::Delivered)
            }

            fn sender_address(&self) -> Option<[u8; 20]> {
                None
            }

            async fn poll_incoming(
                &self,
            ) -> xenith_core::Result<
                Vec<(
                    xenith_core::StateKey,
                    xenith_core::StateValue,
                    Option<xenith_core::KeyMetadata>,
                )>,
            > {
                Ok(vec![])
            }
        }

        let engine2 = SyncEngine::new(
            Arc::new(UnsupportedTransport) as Arc<dyn xenith_core::MessagingTransport>,
            Arc::new(InMemoryStore::default()),
            SyncConfig {
                retry_attempts: 3,
                retry_delay_ms: 1,
                ..SyncConfig::default()
            },
        );

        let receipt = engine2
            .push(
                StateKey::new("test", "no-retry", "1"),
                Bytes::from_static(b"v"),
                vec![ChainId(99)],
                ChainId(1),
                None,
            )
            .await
            .unwrap();

        // Must fail with exactly one attempt (no retries for UnsupportedChain).
        assert_eq!(receipt.failures.len(), 1);
        assert!(matches!(
            receipt.failures[0].1,
            XenithError::UnsupportedChain(_)
        ));
        let _ = call_count; // suppress unused warning
    }
}