Fix datalog bugs

Catch-all PR for Datalog bugs.

1. Please add tests for any existing Datalog bugs here. I caught #107 and #177 so far. The expectation is that the tests should fail!

2. Please fix the bugs. Once we have a comprehensive test suite and all the bugs are fixed, we can be more confident in Datalog working.