General stochastic separation theorems with optimal bounds