this bit looks like it is the most tricksy in here.  Have you checked that this does the right thing for large enough responses?  They're not really feasible to test in the context of the travis build, as you would need to create a large tree or a tree with a lot of creation/deletion events to get a query result large enough to require encoding with larger ints