#2237·iii

Trigger registry: teardown racing a re-home or an in-flight activation leaves bindings firing untracked or resurrects them

Author: sergiofilhowzCreated Sep 25, 2026Updated Sep 25, 2026
Labelsbugengine

Summary

Found while reviewing #2198 (the fix for #2178). There are four races in engine/src/trigger.rs. Each one ends with a binding that keeps firing when it shouldn't: either a provider keeps running it with no registry entry left to tear it down, or it gets published live after an explicit unregister or an owner disconnect.

All four reproduce on main (merge base 3ccf2251f) and on #2198 (2e872b7cd). They are pre-existing and not caused by #2198. That PR removes the accidental serialization the shard guards provided, which only made some interleavings less likely. Repro tests are at the bottom.

Cases

1. unregister_worker tears bindings down on a stale provider (one-line fix)

unregister_worker snapshots the worker's bindings. For each one it calls remove_if(worker_id matches), but then sends unregister_trigger to the provider from trigger.provider_key() of the snapshot, not of the entry actually removed (code). Suppose a home provider re-homes some of those bindings (default → shop) while the loop is awaiting a provider call. The loop then removes the re-homed entries from the registry but tells the fallback to let go. shop keeps running them, and nothing can unregister them anymore.

registry still tracks []; `shop` still runs N untracked bindings: [...]

N was 52, 31 and 4 in different runs; it depends on DashMap iteration order. The test only passes by chance, when the paused binding a happens to be visited last (about 1 in 65).

Fix (validated locally: the repro passes and the trigger:: suite stays green):

rust
let Some((_, trigger)) = self
    .triggers
    .remove_if(&trigger.id, |_, t| t.worker_id == Some(*worker_id))
else {
    // existing "already replaced" debug log
    continue;
};
// ...and tear down on `trigger.provider_key()` of the removed entry

2. unregister_trigger racing a re-home leaves the job on the new home provider

unregister_trigger snapshots t (provider default) and awaits the fallback's unregister. Meanwhile a shop provider re-homes t: the fallback gets -t, shop gets +t, and the entry is republished with provider_namespace = "shop". The unregister then removes the entry from the registry but never tells shop. The loop added in #2198 ("tell every generation observed") follows same-key replacements, not a route change.

registry live=None; `shop` runs t=true (untracked); shop events ["+t"]; fallback events ["+t", "-t", "-t"]

3. An unregister during a pending activation answers Ok(false), then the binding goes live

The pending drain in register_trigger_type claims an intent with pending_triggers.remove and replays it while the intent is in neither map. An explicit unregister_trigger in that window finds nothing and returns Ok(false). The drain then publishes the binding: the caller was told it doesn't exist, yet it fires. The same claim-outside-both-maps window exists in the park/recheck of register_trigger, in park_rejected_trigger and in the failover path of unregister_worker.

unregister answered removed=false, yet registry live=Some("default") and the provider runs t=true

4. An owner disconnecting during failover resurrects a dead worker's binding

The home provider leaves. unregister_worker takes its orphan t (owned by worker O) out of triggers and replays it to the fallback. While that replay is in flight, O disconnects, and O's cleanup finds t in neither map. The failover then publishes t live with a dead owner. The dead-owner sweep in router_msg (code) only cleans pending_triggers, never triggers, so the binding keeps firing against a function that no longer exists.

dead owner's binding live=Some("default") pending=false; fallback runs t=true

Root cause

In all four paths, the code awaits a provider call while working on a snapshot, or on a binding claimed out of both maps. When the call completes, the result is published (or torn down) without re-checking that the binding is still wanted and still where the snapshot said it was. Only the provider generation is re-checked. Cases 3 and 4 fall under the "cancellation of an in-flight registration" item that #2198 lists as out of scope (MOT-4866). Cases 1 and 2 are route-change (re-home) variants.

Suggested direction

  • Case 1: use the value returned by remove_if (above).
  • Case 2: after the final remove in unregister_trigger, if the removed entry's provider_key() differs from the one already unregistered, unregister it there too. Symmetrically, rehome_fallback_bindings should publish only if the entry still exists (e.g. get_mut under park_transition), and otherwise undo the replay on the new provider.
  • Cases 3–4: keep in-flight claims visible, e.g. an in_flight set or a tombstone in pending_triggers guarded by park_transition. unregister_trigger and unregister_worker can then cancel them. The claimant checks the marker before publishing and sends unregister_trigger to the provider if the claim was cancelled.

Repro

Append the module below to engine/src/trigger.rs and run cargo test -p iii --lib teardown_race_repro. All four tests fail on main and on #2198. The settles helper keeps them from hanging on main, where a spawned task can block behind a shard guard held across the paused call.

Repro tests
rust
#[cfg(test)]
mod teardown_race_repro {
    use super::*;
    use crate::protocol::DEFAULT_NAMESPACE;
    use std::collections::HashSet;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
    use std::time::Duration;
    use tokio::sync::Notify;

    /// In-process provider whose next register / unregister can be paused
    /// once: the paused call signals `entered`, then waits for `resume`.
    #[derive(Default)]
    struct Gate {
        live: std::sync::Mutex<HashSet<String>>,
        events: std::sync::Mutex<Vec<String>>,
        pause_register: AtomicBool,
        pause_unregister: AtomicBool,
        entered: Notify,
        resume: Notify,
    }

    impl Gate {
        fn live(&self, id: &str) -> bool {
            self.live.lock().unwrap().contains(id)
        }
        fn live_ids(&self) -> Vec<String> {
            let mut ids: Vec<String> = self.live.lock().unwrap().iter().cloned().collect();
            ids.sort();
            ids
        }
        fn events(&self) -> Vec<String> {
            self.events.lock().unwrap().clone()
        }
    }

    impl TriggerRegistrator for Arc<Gate> {
        fn register_trigger(
            &self,
            trigger: Trigger,
        ) -> Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + Send + '_>> {
            Box::pin(async move {
                if self.pause_register.swap(false, SeqCst) {
                    self.entered.notify_one();
                    self.resume.notified().await;
                }
                self.live.lock().unwrap().insert(trigger.id.clone());
                self.events.lock().unwrap().push(format!("+{}", trigger.id));
                Ok(())
            })
        }

        fn unregister_trigger(
            &self,
            trigger: Trigger,
        ) -> Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + Send + '_>> {
            Box::pin(async move {
                if self.pause_unregister.swap(false, SeqCst) {
                    self.entered.notify_one();
                    self.resume.notified().await;
                }
                self.live.lock().unwrap().remove(&trigger.id);
                self.events.lock().unwrap().push(format!("-{}", trigger.id));
                Ok(())
            })
        }
    }

    /// A fresh Box (fresh registrator identity) per announce, like router_msg.
    fn gate_type(ns: &str, type_id: &str, gate: &Arc<Gate>, owner: Option<Uuid>) -> TriggerType {
        TriggerType::new_ns(ns, type_id, "gate", Box::new(Arc::clone(gate)), owner)
    }

    /// A resolvable binding (no explicit provider namespace) at `home`.
    fn bind(id: &str, type_id: &str, home: &str, owner: Option<Uuid>) -> Trigger {
        Trigger {
            id: id.to_string(),
            trigger_type: type_id.to_string(),
            function_id: format!("fn_{id}"),
            config: serde_json::json!({}),
            worker_id: owner,
            metadata: None,
            namespace: DEFAULT_NAMESPACE.to_string(),
            trigger_namespace: None,
            home_namespace: home.to_string(),
            provider_namespace: DEFAULT_NAMESPACE.to_string(),
        }
    }

    fn live_on(registry: &TriggerRegistry, id: &str) -> Option<String> {
        registry
            .triggers
            .get(id)
            .map(|t| t.provider_namespace.clone())
    }

    fn spawn_type(
        registry: &Arc<TriggerRegistry>,
        ns: &'static str,
        gate: &Arc<Gate>,
        owner: Uuid,
    ) -> tokio::task::JoinHandle<()> {
        let r = Arc::clone(registry);
        let g = Arc::clone(gate);
        tokio::spawn(async move {
            r.register_trigger_type(gate_type(ns, "evt", &g, Some(owner)))
                .await
                .unwrap()
        })
    }

    fn spawn_cleanup(registry: &Arc<TriggerRegistry>, worker: Uuid) -> tokio::task::JoinHandle<()> {
        let r = Arc::clone(registry);
        tokio::spawn(async move { r.unregister_worker(&worker).await })
    }

    /// Waits up to 3 s for a spawned task. When a shard guard is held across
    /// the paused call (current main), the task may block until the caller
    /// resumes that call. Do NOT await the handle again when this returns true.
    async fn settles(handle: &mut tokio::task::JoinHandle<()>) -> bool {
        match tokio::time::timeout(Duration::from_secs(3), handle).await {
            Ok(joined) => {
                joined.unwrap();
                true
            }
            Err(_) => false,
        }
    }

    /// 1 — `unregister_worker` removes each of the worker's bindings with
    /// `remove_if`, but tears it down on the provider of the SNAPSHOT taken
    /// before the loop. While the loop awaits a provider call, a home provider
    /// re-homes the rest of the worker's bindings off the fallback. The loop
    /// then removes the re-homed entries from the registry but tells the
    /// (stale) fallback to let go: `shop` keeps running them, untracked.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn owner_cleanup_tears_down_on_the_provider_it_removed_from() {
        let registry = Arc::new(TriggerRegistry::new());
        let fallback = Arc::new(Gate::default());
        let other = Arc::new(Gate::default());
        registry
            .register_trigger_type(gate_type(DEFAULT_NAMESPACE, "evt", &fallback, None))
            .await
            .unwrap();
        registry
            .register_trigger_type(gate_type(DEFAULT_NAMESPACE, "other", &other, None))
            .await
            .unwrap();

        let owner = Uuid::new_v4();
        registry
            .register_trigger(bind("a", "other", DEFAULT_NAMESPACE, Some(owner)))
            .await
            .unwrap();
        let ids: Vec<String> = (0..64).map(|i| format!("t{i}")).collect();
        for id in &ids {
            registry
                .register_trigger(bind(id, "evt", "shop", Some(owner)))
                .await
                .unwrap();
        }

        // The owner's cleanup is awaiting `-a` somewhere in its loop.
        other.pause_unregister.store(true, SeqCst);
        let cleanup = spawn_cleanup(&registry, owner);
        other.entered.notified().await;

        // The project's own provider shows up meanwhile and re-homes.
        let home = Arc::new(Gate::default());
        let mut reg = spawn_type(&registry, "shop", &home, Uuid::new_v4());
        let reg_settled = settles(&mut reg).await;
        other.resume.notify_one();
        if !reg_settled {
            reg.await.unwrap();
        }
        cleanup.await.unwrap();

        let tracked: Vec<&String> = ids
            .iter()
            .filter(|id| {
                registry.triggers.contains_key(*id) || registry.pending_triggers.contains_key(*id)
            })
            .collect();
        let ghosts = home.live_ids();
        assert!(
            tracked.is_empty() && ghosts.is_empty(),
            "registry still tracks {tracked:?}; `shop` still runs {} untracked bindings: {ghosts:?}",
            ghosts.len()
        );
    }

    /// 2 — An explicit unregister is awaiting the fallback's `-t` when a home
    /// provider re-homes `t` onto `shop`. The unregister then removes the
    /// re-homed entry from the registry without ever telling `shop` to let go.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn unregister_racing_rehome_does_not_leave_job_on_new_home() {
        let registry = Arc::new(TriggerRegistry::new());
        let fallback = Arc::new(Gate::default());
        registry
            .register_trigger_type(gate_type(DEFAULT_NAMESPACE, "evt", &fallback, None))
            .await
            .unwrap();
        registry
            .register_trigger(bind("t", "evt", "shop", None))
            .await
            .unwrap();

        fallback.pause_unregister.store(true, SeqCst);
        let unreg = {
            let r = Arc::clone(&registry);
            tokio::spawn(async move { r.unregister_trigger("t".to_string(), None).await.unwrap() })
        };
        fallback.entered.notified().await;

        let home = Arc::new(Gate::default());
        let mut reg = spawn_type(&registry, "shop", &home, Uuid::new_v4());
        let reg_settled = settles(&mut reg).await;
        fallback.resume.notify_one();
        if !reg_settled {
            reg.await.unwrap();
        }
        let removed = unreg.await.unwrap();

        assert!(removed);
        let live = live_on(&registry, "t");
        assert!(
            live.is_none() && !registry.pending_triggers.contains_key("t") && !home.live("t"),
            "registry live={live:?}; `shop` runs t={} (untracked); shop events {:?}; \
             fallback events {:?}",
            home.live("t"),
            home.events(),
            fallback.events()
        );
    }

    /// 3 — A parked intent is claimed by the drain (taken out of both maps)
    /// while the provider replay is in flight. An explicit unregister in that
    /// window finds nothing and answers Ok(false); the drain then publishes the
    /// binding: the caller was told it does not exist, yet it fires.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn unregister_during_pending_activation_is_not_lost() {
        let registry = Arc::new(TriggerRegistry::new());
        let outcome = registry
            .register_trigger(bind("t", "evt", DEFAULT_NAMESPACE, None))
            .await
            .unwrap();
        assert!(matches!(outcome, RegisterTriggerOutcome::Deferred));

        let provider = Arc::new(Gate::default());
        provider.pause_register.store(true, SeqCst);
        let reg = spawn_type(&registry, DEFAULT_NAMESPACE, &provider, Uuid::new_v4());
        provider.entered.notified().await;

        let removed = registry
            .unregister_trigger("t".to_string(), None)
            .await
            .unwrap();
        provider.resume.notify_one();
        reg.await.unwrap();

        let live = live_on(&registry, "t");
        assert!(
            live.is_none() && !provider.live("t"),
            "unregister answered removed={removed}, yet registry live={live:?} and the \
             provider runs t={}",
            provider.live("t")
        );
    }

    /// 4 — The home provider leaves; its orphan `t` (owned by worker O) is
    /// taken out of `triggers` and replayed to the fallback. While that replay
    /// is in flight, O disconnects: its cleanup finds `t` in neither map. The
    /// failover then publishes `t` live with a dead owner, and nothing reaps it
    /// later (router_msg only sweeps dead owners out of `pending_triggers`).
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn owner_disconnect_during_failover_does_not_resurrect_binding() {
        let registry = Arc::new(TriggerRegistry::new());
        let fallback = Arc::new(Gate::default());
        let home = Arc::new(Gate::default());
        let home_worker = Uuid::new_v4();
        let owner = Uuid::new_v4();
        registry
            .register_trigger_type(gate_type(DEFAULT_NAMESPACE, "evt", &fallback, None))
            .await
            .unwrap();
        registry
            .register_trigger_type(gate_type("shop", "evt", &home, Some(home_worker)))
            .await
            .unwrap();
        registry
            .register_trigger(bind("t", "evt", "shop", Some(owner)))
            .await
            .unwrap();
        assert_eq!(live_on(&registry, "t").as_deref(), Some("shop"));

        fallback.pause_register.store(true, SeqCst);
        let provider_cleanup = spawn_cleanup(&registry, home_worker);
        fallback.entered.notified().await;

        let mut owner_cleanup = spawn_cleanup(&registry, owner);
        let settled = settles(&mut owner_cleanup).await;
        fallback.resume.notify_one();
        if !settled {
            owner_cleanup.await.unwrap();
        }
        provider_cleanup.await.unwrap();

        let live = live_on(&registry, "t");
        let pending = registry.pending_triggers.contains_key("t");
        assert!(
            live.is_none() && !pending && !fallback.live("t"),
            "dead owner's binding live={live:?} pending={pending}; fallback runs t={}",
            fallback.live("t")
        );
    }
}

Related: #2178, #2198