One of the fun parts of working with an optimizer is that rules combine in ways ...
Oliver Kennedy @okennedy@discuss.systems
One of the fun parts of working with an optimizer is that rules combine in ways that you don't expect (and sometimes those ways are good). #Draupnir just had such an event.
I've been slowly extending it to support #SouffleLang so that we can run DDisasm, and noticed that the recursive parts of our small running slice of DDisasm was far smaller than I expected --- for a plan of about two dozen joins, only two of them were part of a recursive stratum.
What turned out to be happening was a bunch of rules of the form:
```
Q :- R, ..., Q
Q :- S, ..., Q
...
```
A naive execution strategy would compute
```
Q := (R ⋈ ... ⋈ Q) ∪ (S ⋈ ... ⋈ Q) ∪ ...
```
But Draupnir was instead computing
```
Q := ((R ⋈ ...) ∪ (S ⋈ ...) ∪ ... ) ⋈ Q
```
This allowed it to pre-compute an index over `((R ⋈ ...) ∪ (S ⋈ ...) ∪ ... )` once, and then re-use this index as the build-side relation of a join for all recursive iterations of computing Q.
In and of itself, this is a fairly obvious optimization, and I'd be surprised if it wasn't happening in e.g., Souffle (iirc, recent versions of DuckDB also do this). What is surprising is the fact that this is a natural consequence of this new Flow-based architecture that we came up with for Draupnir. Since the dataflow graph just represents unions as coterminous edges, the shared structure just falls out of the standard operator deduplication checks.
Draupnir just does the right thing™. It's neat :D