The problem isn't with creating the category (which actually works), but rather with the moment the assignment takes place.
You are using the `publish_post` hook. When you save a post from the block editor (Gutenberg), the save process goes through the REST API, and the sequence is as follows...