How Saving a Single Byte Cost Me Over a Day (and Was Solved With a Single Byte)
An example of a simple error, a simple solution, and a single byte.
Join the DZone community and get the full member experience.Join For Free
i’m currently doing something that i would rather not do. i’m doing significant refactoring to the lowest level of ravendb, preparing some functionality that i need to develop some visible features. but in the meantime, i’m mucking about in the storage layer, dealing with how voron actually persists and manages the information we have. and i’m making drastic changes. that means that stuff breaks, but we have got the tests to cover for us, so we are good in that regard - yeah!
the case for this post is that i decided to break apart a class that had too many responsibilities. the class in question was:
as you can see, there are multiple concerns here. there are actually several types of page in the system, but changing this would have been a major change so i just tucked more responsibility into this poor class at the time.
when i finally got around to actually handling this it was part of a much larger body of work, but i felt really great that i was able to do that.
that was until i ran the tests, and a few of them broke. in particular, only the tests that deal with large amounts of information (over four million entries) broke. and they broke in a really annoying way - it looked like utter memory corruption was happening. it was scary, and it took me a long while to figure out what was going on.
here is the fix:
this error happens when adding a new entry to a tree. in particular, this piece of code will only run when we have a page split on a branch page (that is, we need to move from two levels in the tree to three levels).
the issue turned out to be because when we split the fixed size tree from the variable size tree, i was able to save a single byte in the header of the fixed size tree page. the previous header was 17 bytes in size, and the new header was 16 bytes in size.
the size of branchentrysize is 16 bytes… and i think you get the error now, right?
before, with page size of 4k, we had a pagemaxsize of 4079 bytes. so on the 255 entry, we would be over the limit, and split the page. by reducing a single byte from the header, the pagemaxsize was 4080. because we only checked from greater than, we thought that we could write to that page; but we ended up writing to the next page, corrupting it.
the fix, ironically enough, was to add another byte, to check for greater than or equal.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.