I haven’t looked at this very closely, but it looks like your profile is slightly skewed relative to the rail. I guess this is probably causing some strange things to happen at the mitred edges.
I’m going to check to see if that might be the issue but the rectangle you see in the image is not the rail to sweep the section on. It is actually irrelevant to the script. I forgot to take it out when attaching it to the forum haha my bad.
The image shows the profile and the rail together (the geometry you have connected to the sweep), zoomed in at the bottom right hand corner (top view). If I rotate the profile to align with the rail and then sweep, the brep is valid.