How would you prevent a junior engineer doing this mistake? Presumably, you would setup a lint rule. Do the same for LLMs. Run the linter after each edit through a hook, give feedback to the LLM. Write your lint rules with clear explanations of why the behavior is a problem, and nudges to the good behavior.
You wouldn't prevent the junior from making this mistake.
You would correct them once or twice, and they won't make the mistake again.
It's something we can't do with LLM's currently, so we all just try(and fail) to predict any possible failure ever, and then somehow try to cram it into the limited context.
You would review their code, and give them the feedback. They would learn from that, and not make the mistake again (or not make it after receiving the same feedback again).