mako-engine 0.5.0

Event-sourced process engine for German energy market communication (MaKo)
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
//! Process routing registry.
//!
//! Maps string routing keys to [`ProcessIdentity`] values so inbound
//! EDIFACT messages can be dispatched to the correct running process without
//! the caller managing a bespoke routing table.
//!
//! # Routing key conventions
//!
//! Any stable string that uniquely identifies a process for a given message
//! type works as a routing key. Common patterns:
//!
//! | Message type | Recommended key |
//! |---|---|
//! | UTILMD waiting for APERAK | `RegistryKey::from_conversation_and_sender(conversation_id, sender_gln)` |
//! | Route follow-up by correlation | `RegistryKey::from_correlation(correlation_id)` |
//! | Direct lookup by process | `RegistryKey::from_process(process_id)` |
//!
//! One process may be registered under multiple keys when it handles several
//! different message types simultaneously.
//!
//! # Tenant scoping
//!
//! All registry operations are scoped to a `TenantId`. This prevents routing
//! keys from leaking across tenant boundaries when the engine handles multiple
//! market participants in a single deployment.
//!
//! # Usage
//!
//! ```rust,ignore
//! // After spawning a process, register it under the UTILMD conversation ID + sender GLN:
//! ctx.registry
//!     .register(tenant_id, &RegistryKey::from_conversation_and_sender(utilmd_conv_id, sender_gln), process.identity())
//!     .await?;
//!
//! // When the APERAK arrives, look up by conversation ID + APERAK sender GLN:
//! let identity = ctx.registry
//!     .lookup(tenant_id, &RegistryKey::from_conversation_and_sender(aperak_conv_id, aperak_sender_gln))
//!     .await?
//!     .ok_or(EngineError::registry("unknown conversation"))?;
//!
//! let process = ctx.resume::<SupplierChangeWorkflow>(identity);
//! process.execute(HandleAperak { .. }).await?;
//!
//! // Clean up after process completion:
//! ctx.registry.remove(tenant_id, &RegistryKey::from_conversation_and_sender(utilmd_conv_id, sender_gln)).await?;
//! ```

use std::{fmt, sync::Arc};

#[cfg(any(test, feature = "testing"))]
use std::collections::HashMap;
#[cfg(any(test, feature = "testing"))]
use tokio::sync::RwLock;

use crate::{
    error::EngineError,
    ids::{ConversationId, CorrelationId, ProcessId, ProcessIdentity, TenantId},
};

/// Maximum byte length for a [`RegistryKey`] routing key.
///
/// Keys beyond this limit are rejected by [`RegistryKey::parse`] to
/// prevent oversized LSM keys from bloating the `pr/` key namespace in
/// SlateDB. AS4 `MessageId` values and EDIFACT correlation identifiers are
/// typically ≤ 36 bytes (UUID); 256 bytes provides ample headroom.
pub const MAX_REGISTRY_KEY_LEN: usize = 256;

// ── RegistryKey ───────────────────────────────────────────────────────────────

/// A typed routing key for the [`ProcessRegistry`].
///
/// Using a newtype instead of a bare `&str` prevents accidental key-format
/// mismatches (e.g. mixing `conversation_id` and `correlation_id` keys at
/// different call sites) and makes the key derivation convention explicit at
/// the type level.
///
/// # Named constructors
///
/// | Constructor | Use case |
/// |---|---|
/// | Constructor | Use case |
/// |---|---|
/// | [`from_conversation_and_sender`] | Route inbound APERAK by UTILMD conversation ID + sender GLN |
/// | [`from_correlation`] | Route follow-up messages by root correlation |
/// | [`from_process`] | Direct lookup by process instance |
/// | [`parse`] | Primary validated constructor for runtime-derived keys |
/// | [`from_static`] | Infallible constructor for compile-time-known string literals |
///
/// [`from_conversation_and_sender`]: RegistryKey::from_conversation_and_sender
/// [`from_correlation`]: RegistryKey::from_correlation
/// [`from_process`]: RegistryKey::from_process
/// [`parse`]: RegistryKey::parse
/// [`from_static`]: RegistryKey::from_static
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct RegistryKey(Box<str>);

impl RegistryKey {
    /// Key derived from a conversation ID **and sender GLN**.
    ///
    /// This is the correct constructor for UTILMD ↔ APERAK routing in
    /// multi-market-participant deployments.
    ///
    /// # Why sender is required
    ///
    /// EDIFACT conversation IDs are assigned by the sender within their own
    /// numbering space.  Two senders may independently assign the same
    /// conversation-ID string, which would collide if keyed on conversation
    /// alone.  Including the sender GLN as a discriminator makes the key
    /// globally unique within the tenant's namespace.
    ///
    /// # Key format
    ///
    /// `"{sender_gln}:{conversation_id}"` — stable, URL-safe, human-readable.
    #[must_use]
    pub fn from_conversation_and_sender(id: ConversationId, sender_gln: &str) -> Self {
        let key = format!("{sender_gln}:{id}");
        Self(key.into_boxed_str())
    }

    /// Key derived from a correlation ID (route all messages in the same root trace).
    #[must_use]
    pub fn from_correlation(id: CorrelationId) -> Self {
        Self(id.to_string().into_boxed_str())
    }

    /// Key derived from a process ID (direct process lookup).
    #[must_use]
    pub fn from_process(id: ProcessId) -> Self {
        Self(id.to_string().into_boxed_str())
    }

    /// Primary validated constructor for runtime-derived keys.
    ///
    /// Returns [`EngineError::Registry`] when `s` contains a NUL byte or
    /// exceeds [`MAX_REGISTRY_KEY_LEN`] bytes. Use this for all keys derived
    /// from untrusted input (e.g. EDIFACT `MessageId`, AS4 `conversation_id`,
    /// or user-supplied strings).
    ///
    /// # Errors
    ///
    /// - [`EngineError::Registry`] when `s` contains `\0`.
    /// - [`EngineError::Registry`] when `s.len() > MAX_REGISTRY_KEY_LEN`.
    pub fn parse(s: &str) -> Result<Self, EngineError> {
        if s.contains('\0') {
            return Err(EngineError::registry(
                "registry key must not contain NUL bytes",
            ));
        }
        if s.len() > MAX_REGISTRY_KEY_LEN {
            return Err(EngineError::registry(format!(
                "registry key is {} bytes, exceeds maximum of {MAX_REGISTRY_KEY_LEN}",
                s.len()
            )));
        }
        Ok(Self(s.into()))
    }

    /// Infallible constructor for **compile-time-known** string literals.
    ///
    /// Panics at runtime if `s` contains a NUL byte or exceeds
    /// [`MAX_REGISTRY_KEY_LEN`] — but since this is only correct to call with
    /// string literals, any violation would be caught immediately in tests.
    ///
    /// # Panics
    ///
    /// Panics when `s` contains a NUL byte or exceeds [`MAX_REGISTRY_KEY_LEN`]
    /// bytes. **Only use this with string literals.** Use [`parse`] for any
    /// value that may be runtime-derived.
    ///
    /// [`parse`]: RegistryKey::parse
    #[must_use]
    pub fn from_static(s: &'static str) -> Self {
        assert!(
            !s.contains('\0'),
            "RegistryKey::from_static: key must not contain NUL bytes"
        );
        assert!(
            s.len() <= MAX_REGISTRY_KEY_LEN,
            "RegistryKey::from_static: key exceeds MAX_REGISTRY_KEY_LEN ({MAX_REGISTRY_KEY_LEN} bytes)"
        );
        Self(s.into())
    }

    /// The raw key string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for RegistryKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::str::FromStr for RegistryKey {
    type Err = EngineError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        RegistryKey::parse(s)
    }
}

// ── ProcessRegistry ───────────────────────────────────────────────────────────

/// Routes inbound messages to their target processes by string key.
///
/// A `ProcessRegistry` decouples message routing from process creation.
/// Register a [`ProcessIdentity`] under a stable key at process creation
/// time, then look it up by that key when routing subsequent inbound messages.
///
/// All operations are scoped to a [`TenantId`] so routing entries from
/// different market participants cannot collide.
///
/// ## Correlated-process lookup (1:many)
///
/// The standard `register`/`lookup` API maps a key 1:1 to a single process.
/// For cases where multiple processes share a common business identifier —
/// for example, all MSCONS measurement-data processes for a single MaLo ID
/// in MABIS billing aggregation — use the correlated index:
///
/// - [`register_correlated`]: associate a `(tenant, tag, process_id)` triple.
/// - [`lookup_correlated`]: retrieve **all** `ProcessIdentity` values for a tag.
/// - [`remove_correlated`]: remove a single process from the tag's fan-out set.
///
/// The tag is an arbitrary opaque string (e.g. a MaLo ID such as
/// `"DE0001234567890"`). Key validation rules match [`RegistryKey`].
///
/// ```rust,ignore
/// // Register all MSCONS processes for a Bilanzkreis MaLo:
/// for process in &mscons_processes {
///     ctx.registry
///         .register_correlated(tenant_id, malo_id, process.process_id(), process.identity())
///         .await?;
/// }
///
/// // Retrieve all processes for billing aggregation:
/// let identities = ctx.registry
///     .lookup_correlated(tenant_id, malo_id)
///     .await?;
/// ```
///
/// ## Blanket `Arc` implementation
///
/// `Arc<S>` implements `ProcessRegistry` whenever `S: ProcessRegistry`,
/// enabling shared access from multiple concurrent message handlers.
///
/// [`register_correlated`]: ProcessRegistry::register_correlated
/// [`lookup_correlated`]:   ProcessRegistry::lookup_correlated
/// [`remove_correlated`]:   ProcessRegistry::remove_correlated
#[allow(async_fn_in_trait)]
pub trait ProcessRegistry: Send + Sync {
    /// Associate `key` with `identity` for the given `tenant_id`.
    ///
    /// Overwrites any existing mapping for the `(tenant_id, key)` pair
    /// (upsert semantics).
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn register(
        &self,
        tenant_id: TenantId,
        key: &RegistryKey,
        identity: ProcessIdentity,
    ) -> Result<(), EngineError>;

    /// Return the identity associated with `(tenant_id, key)`, or `None`
    /// if not registered.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn lookup(
        &self,
        tenant_id: TenantId,
        key: &RegistryKey,
    ) -> Result<Option<ProcessIdentity>, EngineError>;

    /// Remove the mapping for `(tenant_id, key)`. No-op if not found.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn remove(&self, tenant_id: TenantId, key: &RegistryKey) -> Result<(), EngineError>;

    /// Return `true` when `(tenant_id, key)` has a registered mapping.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn contains(&self, tenant_id: TenantId, key: &RegistryKey) -> Result<bool, EngineError> {
        Ok(self.lookup(tenant_id, key).await?.is_some())
    }

    /// Total number of registered routing keys across all tenants.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn len(&self) -> Result<usize, EngineError>;

    /// Return `true` when no routing keys are registered.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn is_empty(&self) -> Result<bool, EngineError> {
        Ok(self.len().await? == 0)
    }

    // ── Correlated (1:many) index ────────────────────────────────────────────

    /// Associate `process_id`/`identity` with the correlation `tag` for the
    /// given `tenant_id`.
    ///
    /// Multiple processes can be registered under the same `(tenant_id, tag)`,
    /// making `lookup_correlated` return all of them. This is the fan-out
    /// counterpart to the 1:1 `register`/`lookup` API.
    ///
    /// # Tag constraints
    ///
    /// Same validation as [`RegistryKey`]: must not contain `\0`, must be
    /// ≤ [`MAX_REGISTRY_KEY_LEN`] bytes.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure or invalid tag.
    async fn register_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
        process_id: crate::ids::ProcessId,
        identity: ProcessIdentity,
    ) -> Result<(), EngineError>;

    /// Return all `ProcessIdentity` values registered under `(tenant_id, tag)`.
    ///
    /// Returns an empty `Vec` when no entries exist for the tag.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn lookup_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
    ) -> Result<Vec<ProcessIdentity>, EngineError>;

    /// Remove the `process_id` entry from the `(tenant_id, tag)` fan-out set.
    ///
    /// No-op when the entry does not exist.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Registry`] on storage failure.
    async fn remove_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
        process_id: crate::ids::ProcessId,
    ) -> Result<(), EngineError>;
}

// ── Arc<S> blanket impl ───────────────────────────────────────────────────────

impl<S: ProcessRegistry> ProcessRegistry for Arc<S> {
    async fn register(
        &self,
        tenant_id: TenantId,
        key: &RegistryKey,
        identity: ProcessIdentity,
    ) -> Result<(), EngineError> {
        self.as_ref().register(tenant_id, key, identity).await
    }

    async fn lookup(
        &self,
        tenant_id: TenantId,
        key: &RegistryKey,
    ) -> Result<Option<ProcessIdentity>, EngineError> {
        self.as_ref().lookup(tenant_id, key).await
    }

    async fn remove(&self, tenant_id: TenantId, key: &RegistryKey) -> Result<(), EngineError> {
        self.as_ref().remove(tenant_id, key).await
    }

    async fn len(&self) -> Result<usize, EngineError> {
        self.as_ref().len().await
    }

    async fn register_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
        process_id: crate::ids::ProcessId,
        identity: ProcessIdentity,
    ) -> Result<(), EngineError> {
        self.as_ref()
            .register_correlated(tenant_id, tag, process_id, identity)
            .await
    }

    async fn lookup_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
    ) -> Result<Vec<ProcessIdentity>, EngineError> {
        self.as_ref().lookup_correlated(tenant_id, tag).await
    }

    async fn remove_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
        process_id: crate::ids::ProcessId,
    ) -> Result<(), EngineError> {
        self.as_ref()
            .remove_correlated(tenant_id, tag, process_id)
            .await
    }
}

// ── NoopProcessRegistry ───────────────────────────────────────────────────────

/// A [`ProcessRegistry`] that never stores any mappings.
///
/// Every `lookup` returns `None`. Use this as the default when routing is
/// managed externally or not required.
///
/// # ⚠️ Routing loss warning
///
/// `NoopProcessRegistry` **discards every routing registration silently**.
/// All `lookup` calls return `None`. Inbound messages for existing processes
/// will not be routed. Do not use in production when message routing is needed.
///
/// This type is available in all build configurations so it can serve as a
/// default type parameter in [`EngineBuilder`]. However, [`EngineBuilder::new`]
/// (which wires this as the default) is only available with the `testing`
/// feature or in `cfg(test)`. Production binaries must call
/// [`EngineBuilder::with_stores`] instead.
///
/// [`EngineBuilder`]: crate::builder::EngineBuilder
/// [`EngineBuilder::new`]: crate::builder::EngineBuilder::new
/// [`EngineBuilder::with_stores`]: crate::builder::EngineBuilder::with_stores
#[derive(Debug, Clone, Copy, Default)]
#[must_use = "NoopProcessRegistry discards all routing registrations silently — use a persistent ProcessRegistry in production"]
pub struct NoopProcessRegistry;

#[cfg(any(test, feature = "testing"))]
impl ProcessRegistry for NoopProcessRegistry {
    async fn register(
        &self,
        _tenant_id: TenantId,
        _key: &RegistryKey,
        _identity: ProcessIdentity,
    ) -> Result<(), EngineError> {
        Ok(())
    }

    async fn lookup(
        &self,
        _tenant_id: TenantId,
        _key: &RegistryKey,
    ) -> Result<Option<ProcessIdentity>, EngineError> {
        Ok(None)
    }

    async fn remove(&self, _tenant_id: TenantId, _key: &RegistryKey) -> Result<(), EngineError> {
        Ok(())
    }

    async fn len(&self) -> Result<usize, EngineError> {
        Ok(0)
    }

    async fn register_correlated(
        &self,
        _tenant_id: TenantId,
        _tag: &str,
        _process_id: crate::ids::ProcessId,
        _identity: ProcessIdentity,
    ) -> Result<(), EngineError> {
        Ok(())
    }

    async fn lookup_correlated(
        &self,
        _tenant_id: TenantId,
        _tag: &str,
    ) -> Result<Vec<ProcessIdentity>, EngineError> {
        Ok(vec![])
    }

    async fn remove_correlated(
        &self,
        _tenant_id: TenantId,
        _tag: &str,
        _process_id: crate::ids::ProcessId,
    ) -> Result<(), EngineError> {
        Ok(())
    }
}

// ── InMemoryProcessRegistry ───────────────────────────────────────────────────

/// An in-memory [`ProcessRegistry`] for tests and development.
///
/// Backed by a `HashMap<(TenantId, String), ProcessIdentity>` protected by a
/// `RwLock`. Cloning shares the underlying data via `Arc` — all clones see the
/// same mappings.
///
/// Use this with [`EngineContext`] to verify message routing without
/// depending on an external registry service.
///
/// Only available in `#[cfg(test)]` or with the `testing` feature enabled.
///
/// [`EngineContext`]: crate::builder::EngineContext
#[cfg(any(test, feature = "testing"))]
#[derive(Debug, Default, Clone)]
pub struct InMemoryProcessRegistry {
    #[allow(clippy::type_complexity)]
    inner: Arc<RwLock<HashMap<(TenantId, Box<str>), ProcessIdentity>>>,
    /// Correlated 1:many index: `(tenant_id, tag, process_id)` → `ProcessIdentity`.
    #[allow(clippy::type_complexity)]
    correlated: Arc<RwLock<HashMap<(TenantId, Box<str>, crate::ids::ProcessId), ProcessIdentity>>>,
}

#[cfg(any(test, feature = "testing"))]
impl InMemoryProcessRegistry {
    /// Create an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Return `true` when no routing keys are registered.
    pub async fn is_empty_async(&self) -> bool {
        self.inner.read().await.is_empty()
    }
}

#[cfg(any(test, feature = "testing"))]
impl ProcessRegistry for InMemoryProcessRegistry {
    async fn register(
        &self,
        tenant_id: TenantId,
        key: &RegistryKey,
        identity: ProcessIdentity,
    ) -> Result<(), EngineError> {
        self.inner
            .write()
            .await
            .insert((tenant_id, key.0.clone()), identity);
        Ok(())
    }

    async fn lookup(
        &self,
        tenant_id: TenantId,
        key: &RegistryKey,
    ) -> Result<Option<ProcessIdentity>, EngineError> {
        Ok(self
            .inner
            .read()
            .await
            .get(&(tenant_id, key.0.clone()))
            .cloned())
    }

    async fn remove(&self, tenant_id: TenantId, key: &RegistryKey) -> Result<(), EngineError> {
        self.inner.write().await.remove(&(tenant_id, key.0.clone()));
        Ok(())
    }

    async fn len(&self) -> Result<usize, EngineError> {
        Ok(self.inner.read().await.len())
    }

    async fn register_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
        process_id: crate::ids::ProcessId,
        identity: ProcessIdentity,
    ) -> Result<(), EngineError> {
        self.correlated
            .write()
            .await
            .insert((tenant_id, tag.into(), process_id), identity);
        Ok(())
    }

    async fn lookup_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
    ) -> Result<Vec<ProcessIdentity>, EngineError> {
        let guard = self.correlated.read().await;
        let result = guard
            .iter()
            .filter(|((tid, t, _), _)| *tid == tenant_id && t.as_ref() == tag)
            .map(|(_, identity)| identity.clone())
            .collect();
        Ok(result)
    }

    async fn remove_correlated(
        &self,
        tenant_id: TenantId,
        tag: &str,
        process_id: crate::ids::ProcessId,
    ) -> Result<(), EngineError> {
        self.correlated
            .write()
            .await
            .remove(&(tenant_id, tag.into(), process_id));
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        ids::{ProcessId, TenantId},
        version::WorkflowId,
    };

    fn make_identity() -> ProcessIdentity {
        let pid = ProcessId::new();
        ProcessIdentity::new(
            pid,
            TenantId::new(),
            WorkflowId::new("test", "FV2024-10-01"),
        )
    }

    fn tid() -> TenantId {
        TenantId::new()
    }

    fn key(s: &str) -> RegistryKey {
        RegistryKey::parse(s).expect("valid test key")
    }

    #[tokio::test]
    async fn register_and_lookup() {
        let reg = InMemoryProcessRegistry::new();
        let tenant = tid();
        let id = make_identity();
        reg.register(tenant, &key("conv:abc"), id.clone())
            .await
            .unwrap();
        let found = reg
            .lookup(tenant, &key("conv:abc"))
            .await
            .unwrap()
            .expect("must be found");
        assert_eq!(found.process_id, id.process_id);
    }

    #[tokio::test]
    async fn lookup_returns_none_for_unknown_key() {
        let reg = InMemoryProcessRegistry::new();
        assert!(reg.lookup(tid(), &key("unknown")).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn remove_clears_mapping() {
        let reg = InMemoryProcessRegistry::new();
        let tenant = tid();
        let id = make_identity();
        reg.register(tenant, &key("k1"), id).await.unwrap();
        reg.remove(tenant, &key("k1")).await.unwrap();
        assert!(reg.lookup(tenant, &key("k1")).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn upsert_overwrites_existing() {
        let reg = InMemoryProcessRegistry::new();
        let tenant = tid();
        let id1 = make_identity();
        let id2 = make_identity();
        reg.register(tenant, &key("k1"), id1).await.unwrap();
        reg.register(tenant, &key("k1"), id2.clone()).await.unwrap();
        let found = reg.lookup(tenant, &key("k1")).await.unwrap().unwrap();
        assert_eq!(found.process_id, id2.process_id);
        assert_eq!(
            reg.len().await.unwrap(),
            1,
            "upsert must not duplicate the key"
        );
    }

    #[tokio::test]
    async fn contains_matches_register() {
        let reg = InMemoryProcessRegistry::new();
        let tenant = tid();
        assert!(!reg.contains(tenant, &key("k1")).await.unwrap());
        reg.register(tenant, &key("k1"), make_identity())
            .await
            .unwrap();
        assert!(reg.contains(tenant, &key("k1")).await.unwrap());
    }

    #[tokio::test]
    async fn clone_shares_state() {
        let reg1 = InMemoryProcessRegistry::new();
        let reg2 = reg1.clone();
        let tenant = tid();
        reg1.register(tenant, &key("k1"), make_identity())
            .await
            .unwrap();
        assert!(reg2.contains(tenant, &key("k1")).await.unwrap());
    }

    /// `from_conversation_and_sender` key contains sender prefix.
    #[test]
    fn from_conversation_and_sender_key_contains_sender() {
        use crate::ids::ConversationId;
        let conv = ConversationId::new();
        let k = RegistryKey::from_conversation_and_sender(conv, "4012345000023");
        assert!(k.as_str().starts_with("4012345000023:"));
        assert!(k.as_str().ends_with(&conv.to_string()));
    }

    #[tokio::test]
    async fn tenant_keys_are_isolated() {
        let reg = InMemoryProcessRegistry::new();
        let t1 = tid();
        let t2 = tid();
        reg.register(t1, &key("k1"), make_identity()).await.unwrap();
        assert!(
            reg.contains(t1, &key("k1")).await.unwrap(),
            "tenant1 must see key"
        );
        assert!(
            !reg.contains(t2, &key("k1")).await.unwrap(),
            "tenant2 must not see key"
        );
    }
}