My original incorrect claims were too strong, but the argument does give the following, which is perhaps of some interest also:
Suppose that $B$ is closed, and write the complement as a disjoint union of open intervals $B^c=\bigcup I_n$. If $\sum |I_n|\log |I_n|<\infty$$\sum |I_n|\log |I_n|^{-1}<\infty$, then $\sum a_n(B)<\infty$.
This also says something about arbitrary Borel sets $B$ by using inner regularity.
To prove this, suppose we had an $N$ for which $\sum_{n\le N} a_n$ is very large, and in particular much larger than $\sum |I|\log |I|$$\sum |I|\log |I|^{-1}$. Let $I$ be one of these intervals.
I now want to take a look at what happens to $\sum a_n$ if I add $I$ to $B$. Clearly, your quadratic function of the density is only affected for those dyadic intervals that have a part in $I$ as well as a part in $I^c$. At each level $n$, there are at most two such intervals. If $|I|\ll 2^{-n}$, then the density of a dyadic interval at level $n$ changes by not more than $2^n|I|$. So the change of $a_n$ will be $\lesssim |I|$. There are $\lesssim \log |I|$$\lesssim -\log |I|$ such levels $n$. At the others levels $n$, with $|I|\gtrsim 2^{-n}$, it's clear that $a_n$ changes by $\lesssim 2^{-n}$.
We obtain a total change $\lesssim |I|\log |I|$$\lesssim -|I|\log |I|$ to $\sum a_n$ when $I$ is included in $B$. By successively adding intervals, we can pass to a new set $C\supseteq B$, of almost full measure, and $$ \sum_{n\le N} a_n(B) \lesssim \sum_{n\le N} a_n(C) + \sum |I|\log |I| . $$$$ \sum_{n\le N} a_n(B) \lesssim \sum_{n\le N} a_n(C) + \sum |I|\log |I|^{-1} . $$ However, $\sum_{n\le N} a_n(C)$ is clearly not very large, so it follows that $\sum_{n\le N} a_n(B)$ can actually not be made arbitrarily large.