Does the bolt lock back properly when you hand cycle it? If so, it's not the buffer tube,spring, or any of that stuff in the rear.
There may be a burr on the bolt latch lever or plunger or the slot may just be tight. The bolt latch is engaged by the mag follower against the pressure of the spring. If any of the connected parts is hanging up, the follower will not raise the bolt latch sufficiently to securely lock the bolt back.
If the bolt is not traveling far enough to the rear, the bolt latch may catch the bottom of the bolt carrier rather than the front of the bolt which will allow the bolt to slip off and fly forward if jiggled or bumped. In that case, you have a problem related to weak ammo, a plugged gas tube, or any of the problems related to the buffer assembly.