Safari password autofill sometimes sets the wrong password

I found a case where Safari, the macOS web browser, will sometime append a username to a password field. It's very odd. 

This is with Apple Password, on an old-ish web site using two step login: fill in the username, press next, fill in the password. Using autofill, the site would respond with "incorrect password", but if you paste in the password from Apple Password, that worked.

I checked what was going on by auto-filling the password, and before hitting “submit” I dropped to the browser console and ran:
document.getElementById("password").value
With a username “root”, I'd see output like: "trustno1root" (I can trust you not to share my login details, of course).

Turns out the username was propagated using a hidden field called "username" at the end of the form. Moving the hidden field to be before the password field solved the problem.

I suppose Safari uses a bunch of heuristics for form filling, and I stumbled into an edge case. Like I said: it's very odd.