Repository: RasaHQ/rasa
Pull request: Fix tracker init copy method
**Proposed changes**:
- The `init_copy` function of `DialogStateTracker` now uses the `sender_id` of the tracker to be copied
- Fixes #7338 

**Status (please check what you already did)**:
- [x] added some tests for the functionality
- [ ] updated the documentation
- [x] updated the changelog (please check [changelog](https://github.com/RasaHQ/rasa/tree/master/changelog) for instructions)
- [x] reformat files using `black` (please check [Readme](https://github.com/RasaHQ/rasa#code-style) for instructions)


Problem statement:
tracker.sender_id always returns `default` in custom actions
**Rasa version**: 2.1.0

**Rasa SDK version**: 2.1.1

**Python version**: 3.7.9

**Operating system**: Ubuntu

**Issue**:
In all of my custom actions, `tracker.sender_id` now always returns `default` instead of the actual sender id. We are heavily using this sender id as user identifiers in our database which currently fails as a result. 

Note that I am using Facebook Messenger and in the Rasa core, the `sender_id` is correctly set.

**Error (including full traceback)**:
No error is thrown

**Command or request that led to error**:
```
rasa run actions --action actions --debug
```

Hints from issue discussion:
Thanks for raising this issue, @joejuzl will get back to you about it soon✨

###### Please also check out the [docs](https://rasa.com/docs/) and the [forum](https://forum.rasa.com/) in case your issue was raised there too 🤗
Hi @joejuzl ! I was wondering if you had a chance to look into that? Any help would be greatly appreciated!! :-)
Hi @nbeuchat thanks for creating this issue.

This does indeed seem to be a bug.
I think it originates in https://github.com/RasaHQ/rasa.
I believe it comes from where we create `temporary_tracker` in `MessageProcessor._run_action` 

Would you be up for contributing a fix?


Hi @joejuzl thanks for checking! I see where the issue lies now. Happy to provide a fix, looking into this now. 
@wochinge I am looking at the `_run_action` from the `MessageProcessor`. I see that you added the temporary tracker that copies from the original one. However, `tracker.copy()` does not copy the `sender_id` because of how `init_copy` initializes the sender id:

```
    def init_copy(self) -> "DialogueStateTracker":
        """Creates a new state tracker with the same initial values."""

        return DialogueStateTracker(
            DEFAULT_SENDER_ID,  # problematic line
           ...
```

In order to fix this, I see two options:

- Set the `sender_id` on the `temporary_tracker`
- Modify the behavior of `DialogueStateTracker.copy` or `DialogueStateTracker.init_copy` so that they also copy the sender id. However, I do not have enough overview on the whole Rasa ecosystem to understand how that would effect other parts of Rasa. 

What do you think would be the best approach? 

Thanks for your inputs! Happy to do a PR afterwards :-)
> Modify the behavior of DialogueStateTracker.copy or DialogueStateTracker.init_copy so that they also copy the sender id. However, I do not have enough overview on the whole Rasa ecosystem to understand how that would effect other parts of Rasa.

That sounds perfect! 👍 I checked the code base and it should actually fix a couple of other locations which use `init_copy` 🙈  Feel free to request review from me then 👍 
Perfect, will work on it today! 
Please target `2.1.x` for your PR. Then we can ship a patch release asap.

Commit message: add changelog for copying the sender id

Patch to review:
diff --git a/changelog/7338.bugfix.md b/changelog/7338.bugfix.md
new file mode 100644
index 000000000000..006f4e1b69b9
--- /dev/null
+++ b/changelog/7338.bugfix.md
@@ -0,0 +1 @@
+Sender id is correctly set when copying the tracker and sending it to the action server (instead of sending the `default` value)
diff --git a/rasa/shared/core/trackers.py b/rasa/shared/core/trackers.py
index ccfd51db3362..36d51122240f 100644
--- a/rasa/shared/core/trackers.py
+++ b/rasa/shared/core/trackers.py
@@ -387,7 +387,7 @@ def init_copy(self) -> "DialogueStateTracker":
         """Creates a new state tracker with the same initial values."""
 
         return DialogueStateTracker(
-            DEFAULT_SENDER_ID,
+            self.sender_id or DEFAULT_SENDER_ID,
             self.slots.values(),
             self._max_event_history,
             is_rule_tracker=self.is_rule_tracker,
diff --git a/tests/shared/core/test_trackers.py b/tests/shared/core/test_trackers.py
index f9aa1dd5b808..8f68c917c572 100644
--- a/tests/shared/core/test_trackers.py
+++ b/tests/shared/core/test_trackers.py
@@ -68,10 +68,7 @@
 from rasa.shared.core.training_data.story_writer.markdown_story_writer import (
     MarkdownStoryWriter,
 )
-from rasa.shared.nlu.constants import (
-    ACTION_NAME,
-    PREDICTED_CONFIDENCE_KEY,
-)
+from rasa.shared.nlu.constants import ACTION_NAME, PREDICTED_CONFIDENCE_KEY
 
 domain = Domain.load("examples/moodbot/domain.yml")
 
@@ -501,6 +498,13 @@ def test_traveling_back_in_time(default_domain: Domain):
     assert len(list(tracker.generate_all_prior_trackers())) == 2
 
 
+def test_tracker_init_copy(default_domain: Domain):
+    sender_id = "some-id"
+    tracker = DialogueStateTracker(sender_id, default_domain.slots)
+    tracker_copy = tracker.init_copy()
+    assert tracker.sender_id == tracker_copy.sender_id
+
+
 async def test_dump_and_restore_as_json(default_agent: Agent, tmp_path: Path):
     trackers = await default_agent.load_data(DEFAULT_STORIES_FILE)
 
@@ -612,7 +616,7 @@ def test_session_started_not_part_of_applied_events(default_agent: Agent):
     tracker_dump = "data/test_trackers/tracker_moodbot.json"
     tracker_json = json.loads(rasa.shared.utils.io.read_file(tracker_dump))
     tracker_json["events"].insert(
-        4, {"event": ActionExecuted.type_name, "name": ACTION_SESSION_START_NAME},
+        4, {"event": ActionExecuted.type_name, "name": ACTION_SESSION_START_NAME}
     )
     tracker_json["events"].insert(5, {"event": SessionStarted.type_name})
 
@@ -1153,8 +1157,8 @@ def test_reading_of_trackers_with_legacy_form_validation_events():
     tracker = DialogueStateTracker.from_dict(
         "sender",
         events_as_dict=[
-            {"event": LegacyFormValidation.type_name, "name": None, "validate": True,},
-            {"event": LegacyFormValidation.type_name, "name": None, "validate": False,},
+            {"event": LegacyFormValidation.type_name, "name": None, "validate": True},
+            {"event": LegacyFormValidation.type_name, "name": None, "validate": False},
         ],
     )
 


Code review comments:
diff_hunk: @@ -0,0 +1 @@
+Sender id is correctly set when copying the tracker and sending it to the action server (instead of sending the `default` value)
path: changelog/7338.bugfix.md
text: @user1:
what do you think?
```suggestion
Sender ID is correctly set when copying the tracker and sending it to the action server (instead of sending the `default` value). This fixes a problem where the action server would only retrieve trackers with a `sender_id` `default`.
```