Does sparing the innocent not directly contradict the biblical commandment - Deuteronomy 13:16 - that everyone in such a town should be killed?
Here is the passage:
הכה תכה את ישבי העיר ההוא לפי חרב: החרם אתה ואת כל אשר בה ואת בהמתה
לפי חרב
You shall surely strike the inhabitants of that city with the sword; destroying it utterly, and all that is therein and the
cattle thereof, by the sword.
I think that according to the plain reading, there are two clauses here. The first clause: "You shall strike the inhabitants of that city with the sword" does not state that ALL of the inhabitants should be killed. Thus our mesorah teaches the system by means of which we separate out the transgressors from the righteous and subject them to sentencing. The second clause: "destroying it utterly, and all that is therein and the cattle thereof, by the sword" refers to the city itself and its property. That is entirely eliminated, and not even the property of the sadiqim (righteous) escape this fate as you note.
To add to that, there is an explicit Tannaitic source for differentiating between the wicked and the righteous of the 'Ir ha-Nidahath. The 'Abhodath ha-Melekh (H. A.Z. 4:6) cites a Genizah fragment from the Mekhiltah:
נעשתה התועבה הזאת למה נאמר, לפי שנאמר הכה תכה שומע אני אחד צדיקים
ואחד רשעים ת"ל נעשתה התועבה הזאת בקרבך העובדין בלבד
"That did this abomination" (Deut. 17:4) why did the text include
this? Since it said "Shall surely strike" (Deut. 13:6) I would have
thought the righteous and the wicked alike, the Torah therefore comes
and teaches those "that did this abomination" who within your midst served
idolatry, they alone.