Muscle cramps during marathons

Recently I completed my 2nd marathon.
As in the previous marathon, and unlike most of the training sessions (longest being 38km), I encountered muscle cramps from approximately the halfway mark (i.e. 21km). In the previous week I did my best to consume sufficient amounts of magnesium and potassium, and throughout the race I consumed salt capsules. I completed the race although it was quite a struggle.

I am soliciting inputs on why these cramps occur and why so soon (again, in training over 4 months I barely encountered such cramps.

I am speculating that I had low levels of blood sugar early on which triggered the events (I did eat/drink sufficient amounts during the race to overcome that).

Any comments/thoughts are much appreciated.

I have had this occur in 10k races a couple of time but not in the two marathons I've run. Reason for them, I believe, was the opposite of your idea. I think my blood sugar got way too high from the nerves and food eaten prior to the race. Just another idea.

I’ve had this happen a bunch. It’s really difficult. Doctors haven’t helped. I’ve had some good runs but many of the longer ones, 15+ miles, have been crampy and difficult.

there's some research out there showing that the real reason for the cramps is muscle fatigue and has very little to do with dehydration, electrolyte imbalance, etc. if you were running the marathon on race day at a pace that was faster than your long training runs (even if it is not a huge difference in pace)can really add up as you mow through the miles. the good news is it might be something that you can fix by making some training corrections.
i also had the cramping issue for my first 5 or 6 marathons but once i increased my training miles along with my pace and included some exercises to work on my leg strength, i really haven't had any issues with cramping anymore.
i'm not sure if anyone else has had similar experiences but for me it has made a world of difference. it's nice to feel confident all the way through 22 or 23 miles and really only feeling like i'm working hard in the last 3 or 4 miles.