I don't have a completely definitive answer. However generally, fermentation produces lactic acid which inhibits the growth of harmful bacteria, which is why it is a successful food preservation method. The yeast and bacteria that are responsible for the fermentation are often naturally occurring on many raw foods. For example with lacto-fermented vegetables often all you have to do is submerge them in a salt solution and the naturally occurring yeast and beneficial bacteria will usually just do their thing and begin the fermentation process, which inhibits the growth of bacteria.
This is similar to how sourdough starter works, you simply add water to flour and the naturally occurring yeasts are activated. As the starter ferments, lactic acid is produced, which reduces the pH of the solution, which inhibits the growth of bacteria. This is why you end up with sourdough starter rather than something spoiled. This is also why fermented foods (pickles, sourdough bread, etc) are generally sour in flavor.
Incidentally this same thing is true of wine grapes, if you harvest ripe wine grapes and just leave them somewhere, fermentation will begin because of the naturally occurring yeasts on the fruit, which will eventually produce wine. These yeasts are variable and can be mixed with various bacteria and produce uneven results, so wine makers generally do not roll the dice and add their own preferred yeast instead. But I suspect that this is how wine was made for thousands of years before that technology was developed.
Back to dosa, the dosa batter is usually prepared by combining dal and rice and sometimes salt with water. The dal especially typically has a significant amount of lactic acid bacteria, and the salt, if used, inhibits the growth of harmful bacteria. Many recipes call for fenugreek seeds (not ground fenugreek), which usually contain naturally occurring yeast which helps kick off the fermentation. The rice is usually raw (soaked) before it is ground, and so has not had a chance to sit cooked at room temperature to develop harmful bacteria. The goal of the recipe is to ensure the beneficial fermentation happens instead of the growth of harmful bacteria. The recipe is pretty foolproof which is why dosa have become a dietary staple in such large parts of the world.