Comprehensive Guide to Bottom-kk Sketches

Unweighted, Weighted, Proofs & Implementations; and VarOpt Sketches of a Recurrence on the Bitcoin Chain

1. Introduction to Bottom-kk Sketches

A bottom-kk sketch (also known as a K-Minimum Values (KMV) sketch or a single-hash MinHash sketch)Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133; Ziv Bar-Yossef, T. S. Jayram, Ravi Kumar, D. Sivakumar, and Luca Trevisan. Counting Distinct Elements in a Data Stream. In José D. P. Rolim and Salil Vadhan, editors, Randomization and Approximation Techniques in Computer Science: 6th International Workshop, RANDOM 2002, volume 2483 of Lecture Notes in Computer Science, pages 1–10. Springer, 2002. doi: 10.1007/3-540-45726-7_1. URL https://doi.org/10.1007/3-540-45726-7_1; and Andrei Z. Broder. On the resemblance and containment of documents. In Proceedings. Compression and Complexity of SEQUENCES 1997, pages 21–29. IEEE Computer Society, 1997. doi: 10.1109/SEQUEN.1997.666900. URL https://doi.org/10.1109/SEQUEN.1997.666900 is a probabilistic data structure used to summarize massive datasets using fixed, tiny memory footprints. Instead of storing every unique item in a stream, it hashes each item onto the interval [0,1][0, 1] and retains only the kk smallest unique hash values.

From those kk values alone, one can estimate:

  • The total number of distinct elements (cardinality),
  • The similarity between two sets (Jaccard similarity), and
  • Set operations (unions and intersections) without re-scanning raw data.

1.1 Overview & Construction

Suppose you have a stream of elements and a uniform random hash function h(x)→[0,1]h(x) \to [0, 1].

  1. Initialize an empty max-heap of capacity kk alongside a lookup structure to ignore duplicates.
  2. Hash each item xx to get a value v=h(x)∈[0,1]v = h(x) \in [0, 1].
  3. Update the sketch:
    • If vv is already in the sketch, ignore it.
    • If the sketch has fewer than kk items, insert vv.
    • If the sketch has kk items and v<v(k)v < v_{(k)} (the current maximum in the heap), evict v(k)v_{(k)} and insert vv.

Because updates only require computing a hash and comparing against v(k)v_{(k)}, processing each item takes O(1)O(1) expected time or O(log⁡k)O(\log k) worst-case time.

1.2 Primary Applications

1.2.1 Cardinality Estimation (Count-Distinct)

If NN distinct items are hashed uniformly into [0,1][0, 1], they divide the interval into N+1N + 1 sub-intervals of expected length 1N+1\frac{1}{N + 1}. The kk-th smallest hash value v(k)v_{(k)} has expected value:

𝔼[v(k)]=kN+1\mathbb{E}[v_{(k)}] = \frac{k}{N + 1}

Inverting this suggests N≈k/v(k)−1N \approx k/v_{(k)} - 1; the estimator that is exactly unbiased, for N≥k≥2N \ge k \ge 2 (with fewer than kk items the sketch holds them all and counts them exactly), is:

N^=k−1v(k)\hat{N} = \frac{k - 1}{v_{(k)}}

The relative standard error of this estimate is approximately 1k−2\frac{1}{\sqrt{k - 2}}.The variance is exactly N(N−k+1)/(k−2)N(N - k + 1)/(k - 2) for k≥3k \ge 3; at k=2k = 2 it is infinite. Inverting 𝔼[v(k)]\mathbb{E}[v_{(k)}] is only the heuristic: by Jensen’s inequality the plain k/v(k)k/v_{(k)} overestimates, and what makes (k−1)/v(k)(k - 1)/v_{(k)} exactly unbiased is 𝔼[1/v(k)]=N/(k−1)\mathbb{E}[1/v_{(k)}] = N/(k - 1). Keeping the kk smallest hash values goes back to Bar-Yossef et al.; the unbiased estimator, its variance and the name KMV are from Beyer et al.Ziv Bar-Yossef, T. S. Jayram, Ravi Kumar, D. Sivakumar, and Luca Trevisan. Counting Distinct Elements in a Data Stream. In José D. P. Rolim and Salil Vadhan, editors, Randomization and Approximation Techniques in Computer Science: 6th International Workshop, RANDOM 2002, volume 2483 of Lecture Notes in Computer Science, pages 1–10. Springer, 2002. doi: 10.1007/3-540-45726-7_1. URL https://doi.org/10.1007/3-540-45726-7_1; and Kevin Beyer, Peter J. Haas, Berthold Reinwald, Yannis Sismanis, and Rainer Gemulla. On synopses for distinct-value estimation under multiset operations. In Proceedings of the 2007 ACM SIGMOD International Conference on Management of Data, SIGMOD '07, pages 199–210. Association for Computing Machinery, 2007. doi: 10.1145/1247480.1247504. URL https://doi.org/10.1145/1247480.1247504 Storing k=1024k = 1024 hashes yields an estimate with ≈3.1%\approx 3.1\% error regardless of whether N=104N = 10^4 or N=1010N = 10^{10}.

The same estimator is exactly unbiased in a finite model as well. If the hash is a uniformly random permutation of a universe of MM items, with ranks 0,…,M−10, \dots, M - 1, and RR is the kk-th smallest rank of the NN items as an integer (0-based, so the number of universe items ranked strictly below it), then N^=(k−1)M/R\hat N = (k - 1)M / R has 𝔼[N^]=N\mathbb{E}[\hat N] = N, and its variance is slightly below N(N−k+1)/(k−2)⋅(M−N)/(M−1)N(N - k + 1)/(k - 2) \cdot (M - N)/(M - 1), within 1% for k≥256k \ge 256: the finite-population factor (M−N)/(M−1)(M - N)/(M - 1) is a free gain when the set fills a good part of its universe. Section 10.4 proves the unbiasedness and computes the variance exactly over the law of RR, writing nn for the set size and NN for the universe, and uses it with a smaller universe chosen for each record.

1.2.2 Set Merging (Unions)

Given sketch S(A)S(A) and sketch S(B)S(B) built with the same hash function hh, the exact bottom-kk sketch of A∪BA \cup B is:This is why KMV sketches merge exactly, in any order and over any partition of the data: each of the kk smallest hashes of a union is among the kk smallest of the part that contains it, so the union’s bottom-kk lies inside the union of the parts’ sketches.

S(A∪B)=bottom-k(S(A)∪S(B))S(A \cup B) = \text{bottom-}k\big(S(A) \cup S(B)\big)

1.2.3 Jaccard Similarity & Intersections

The Jaccard similarity J(A,B)=∣A∩B∣∣A∪B∣J(A, B) = \frac{|A \cap B|}{|A \cup B|} is estimated from the bottom-kk sketch of the union, S(A∪B)=bottom-k(S(A)∪S(B))S(A \cup B) = \text{bottom-}k\big(S(A) \cup S(B)\big), by the fraction of its elements present in both S(A)S(A) and S(B)S(B):

J^(A,B)=∣S(A∪B)∩S(A)∩S(B)∣∣S(A∪B)∣,∣S(A∪B)∣=min⁡(k,∣A∪B∣).\hat{J}(A, B) = \frac{|S(A \cup B) \cap S(A) \cap S(B)|}{|S(A \cup B)|}, \qquad |S(A \cup B)| = \min(k, |A \cup B|).

Membership is read off exactly: an element of S(A∪B)S(A \cup B) that belongs to AA has fewer than kk elements of AA hashed below it, so it is in S(A)S(A). When ∣A∪B∣>k|A \cup B| > k, S(A∪B)S(A \cup B) is a uniformly random kk-subset of A∪BA \cup B, the count in the numerator is hypergeometric, and J^\hat J is exactly unbiased, with variance

Var⁡(J^)=J(1−J)k⋅∣A∪B∣−k∣A∪B∣−1≤14k. \operatorname{Var}(\hat J) = \frac{J(1 - J)}{k} \cdot \frac{|A \cup B| - k}{|A \cup B| - 1} \le \frac{1}{4k}.

When both sketches hold their whole sets (each set has at most kk items), compute JJ exactly from them: the formula above is then still an estimate whenever the union exceeds kk (§10.5).

The intersection size is then estimated as

∣A∩B∣≈J^(A,B)⋅N^A∪B, |A \cap B| \approx \hat{J}(A, B) \cdot \hat{N}_{A \cup B},

consistently but not unbiasedly, and the containment ∣A∩B∣/∣A∣|A \cap B| / |A| by the elements of S(A)S(A) that hash at or below the kk-th hash of S(B)S(B) (all of S(A)S(A) when S(B)S(B) holds the whole of BB): the fraction of them found in S(B)S(B). That kk-th element belongs to BB, so when it is also in AA it is a sure hit, which biases the fraction up by up to about c(1−c)/kc(1 - c)/k for a containment cc (the full amount when AA is smaller than BB, none when it is much larger; at most 0.00025 at k=1024k = 1024). The fraction is undefined when no element of S(A)S(A) is that small, which is common when AA is much smaller than BB.These estimates ask little of the hash function. Thorup shows that with a merely 2-independent hh the expected relative error of estimating a fraction ff (here JJ) from a bottom-kk sample is O(1/fk)O(1/\sqrt{fk}), within a constant factor of truly random hashing when fk=Ω(1)fk = \Omega(1). Bottom-kk estimators of Jaccard and containment from two sketches are treated by Cohen and Kaplan.Mikkel Thorup. Bottom-k and priority sampling, set similarity and subset sums with minimal independence. In Proceedings of the Forty-Fifth Annual ACM Symposium on Theory of Computing, STOC '13, pages 371–380. Association for Computing Machinery, 2013. doi: 10.1145/2488608.2488655. URL https://doi.org/10.1145/2488608.2488655; and Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133

1.3 Comparison: Bottom-kk vs. MinHash vs. HyperLogLog

The two usual alternatives are kk-hash MinHashAndrei Z. Broder. On the resemblance and containment of documents. In Proceedings. Compression and Complexity of SEQUENCES 1997, pages 21–29. IEEE Computer Society, 1997. doi: 10.1109/SEQUEN.1997.666900. URL https://doi.org/10.1109/SEQUEN.1997.666900 and HyperLogLog:Philippe Flajolet, Éric Fusy, Olivier Gandouet, and Frédéric Meunier. HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm. In 2007 Conference on Analysis of Algorithms (AofA 07), volume AH of DMTCS Proceedings, pages 137–156, 2007. doi: 10.46298/dmtcs.3545. URL https://doi.org/10.46298/dmtcs.3545

FeatureBottom-kk Sketch (KMV)kk-Hash MinHashHyperLogLog (HLL)
Hash Functions per Item11kk11
Update Time ComplexityO(1)O(1) expected, O(log⁡k)O(\log k) worstO(k)O(k)O(1)O(1)
Memory FootprintO(klog⁡M)O(k \log M) bitsO(klog⁡M)O(k \log M) bitsO(mlog⁡log⁡M)O(m \log \log M) bits (~5–6 bits/register)
Best Use CaseFast updates + set intersections, Jaccard, & subset sumsLocality-Sensitive Hashing (LSH)Pure COUNT(DISTINCT) at minimal memory

Here MM is the size of the hashed universe, as in §1.2.1, so a hash value takes log⁡M\log M bits, and mm is the number of HLL registers (standard error about 1.04/m1.04/\sqrt{m}, §15).

2. Weighted Extension: Priority Sampling & Exponential Scaling

A weighted bottom-kk sketch generalizes count-distinct sketching to items with positive weights wi>0w_i > 0 (e.g., revenue, byte volume, or duration). It samples heavy items with higher probability and yields unbiased Horvitz-ThompsonD. G. Horvitz and D. J. Thompson. A Generalization of Sampling Without Replacement from a Finite Universe. Journal of the American Statistical Association, 47(260):663–685, 1952. doi: 10.1080/01621459.1952.10483446. URL https://doi.org/10.1080/01621459.1952.10483446 estimates for total stream weight and arbitrary subset sums.

2.1 Core Intuition: Virtual Replication

If an item xix_i has integer weight wi=100w_i = 100, an unweighted sketch could conceptually split xix_i into 100 sub-items (xi,1),…,(xi,100)(x_i, 1), \dots, (x_i, 100), hashing each to [0,1][0, 1] and taking the minimum:

ri=min⁡1≤j≤wih(xi,j)r_i = \min_{1 \le j \le w_i} h(x_i, j)

Computing wiw_i hashes directly requires O(wi)O(w_i) work and fails for continuous non-integer weights. Exponential scaling (§2.2.1) reproduces this minimum exactly in O(1)O(1) time, up to an increasing transformation: −ln⁡(1−min⁡jh(xi,j))∼Exp(wi)-\ln(1 - \min_j h(x_i, j)) \sim \text{Exp}(w_i), which is also the law of −ln⁡(ui)/wi-\ln(u_i)/w_i, and it extends to any real wi>0w_i > 0. Priority scaling ui/wiu_i/w_i (§2.2.2) matches it only for small ranks, since Pr⁡(ui/wi<t)=wit≈1−(1−t)wi\Pr(u_i/w_i < t) = w_i t \approx 1 - (1 - t)^{w_i}; under priority scaling the probability of holding the minimum is therefore not wi/∑j∈Swjw_i/\sum_{j \in S} w_j. This does not affect §3, whose unbiasedness proof uses only each rank’s CDF FiF_i.

2.2 Mathematical Formulations

Given uniform random hashes ui=h(i)∈(0,1)u_i = h(i) \in (0, 1) and weights wi>0w_i > 0:

2.2.1 Method A: Exponential Scaling (PPSWOR)

Transform ui∼Uniform(0,1)u_i \sim \text{Uniform}(0, 1) into an exponential variable ri∼Exp(wi)r_i \sim \text{Exp}(w_i)Edith Cohen and Haim Kaplan. Tighter estimation using bottom k sketches. Proceedings of the VLDB Endowment, 1(1):213–224, 2008. doi: 10.14778/1453856.1453884. URL https://doi.org/10.14778/1453856.1453884; and Bengt Rosén. Asymptotic theory for order sampling. Journal of Statistical Planning and Inference, 62(2):135–158, 1997. doi: 10.1016/S0378-3758(96)00185-1. URL https://doi.org/10.1016/S0378-3758(96)00185-1:

ri=−ln⁡(ui)wir_i = \frac{-\ln(u_i)}{w_i}

The probability that item ii achieves the minimum rank among set SS is strictly proportional to its weight:

Pr⁡(ri=min⁡j∈Srj)=wi∑j∈Swj\Pr\left(r_i = \min_{j \in S} r_j\right) = \frac{w_i}{\sum_{j \in S} w_j}

2.2.2 Method B: Priority Sampling (Uniform Scaling)

Scale the uniform float directlyPriority sampling is due to Duffield, Lund and Thorup. The same ranks ui/wiu_i / w_i, keeping the nn smallest, define Ohlsson’s sequential Poisson sampling, used for the Swedish Consumer Price Index since 1989, whose estimator Ohlsson showed to be asymptotically unbiased; the threshold estimator of §2.3 is exactly unbiased (§3).Nick Duffield, Carsten Lund, and Mikkel Thorup. Priority sampling for estimation of arbitrary subset sums. Journal of the ACM, 54(6), December 2007. doi: 10.1145/1314690.1314696. URL https://doi.org/10.1145/1314690.1314696. Article 32; and Esbjörn Ohlsson. Sequential Poisson Sampling. Journal of Official Statistics, 14(2):149–162, 1998. URL https://www.scb.se/contentassets/ca21efb41fee47d293bbee5bf7be7fb3/sequential-poisson-sampling.pdf:

ri=uiwir_i = \frac{u_i}{w_i}

This avoids logarithmic evaluations while maintaining optimal variance bounds.Optimal in a precise sense: Duffield, Lund and Thorup conjectured, and Szegedy proved, that no unbiased scheme sampling kk items has a smaller total variance than priority sampling with k+1k + 1 items.Mario Szegedy. The DLT priority sampling is essentially optimal. In Proceedings of the Thirty-Eighth Annual ACM Symposium on Theory of Computing, STOC '06, pages 150–158. Association for Computing Machinery, 2006. doi: 10.1145/1132516.1132539. URL https://doi.org/10.1145/1132516.1132539

2.3 Horvitz-Thompson Estimator

Assume N≥k≥2N \ge k \ge 2 (otherwise every item is kept, with w^i=wi\hat{w}_i = w_i). Let τ=r(k)\tau = r_{(k)} be the kk-th smallest rank in the sketch. The first k−1k - 1 items (r(1),…,r(k−1)r_{(1)}, \dots, r_{(k-1)}) are retained as active samples, while the kk-th item sets the threshold τ\tau.

  1. Under Exponential Scaling (ri=−ln⁡(ui)/wir_i = -\ln(u_i) / w_i): Inclusion probability: pi(τ)=1−e−wiτp_i(\tau) = 1 - e^{-w_i \tau} Adjusted weight:

    w^i=wi1−e−wiτ\hat{w}_i = \frac{w_i}{1 - e^{-w_i \tau}}
  2. Under Priority Sampling (ri=ui/wir_i = u_i / w_i): Inclusion probability: pi(τ)=min⁡(1,wiτ)p_i(\tau) = \min(1, w_i \tau) Adjusted weight:

    w^i=max⁡(wi,1τ)\hat{w}_i = \max\left(w_i, \frac{1}{\tau}\right)

In both schemes, the threshold-setting item r(k)r_{(k)} receives an adjusted weight w^(k)=0\hat{w}_{(k)} = 0.

2.4 Subset Sum Queries

Let Sk−1S_{k-1} denote the active sample set of size k−1k - 1. For any predicate QQ (e.g., region == 'EU'):

W^Q=∑i∈Sk−1∩Qw^iwhere 𝔼[W^Q]=∑i∈Qwi\hat{W}_Q = \sum_{i \in S_{k-1} \cap Q} \hat{w}_i \quad \text{where } \mathbb{E}[\hat{W}_Q] = \sum_{i \in Q} w_i

2.5 Worked Numerical Example (k=3k = 3)

Consider N=4N = 4 items evaluated with Priority Sampling (ri=ui/wir_i = u_i / w_i):

ItemWeight (wiw_i)Hash (uiu_i)Rank (rir_i)Status (k=3k = 3)Adjusted Weight w^i=max⁡(wi,1/τ)\hat{w}_i = \max(w_i, 1/\tau)
A1001000.500.500.00500.00501st (r(1)r_{(1)})max⁡(100,50)=𝟏𝟎𝟎\max(100, 50) = \mathbf{100}
B10100.200.200.02000.02003rd (r(3)=τr_{(3)} = \tau)00 (Threshold setter: τ=0.02  ⟹  1/τ=50\tau = 0.02 \implies 1/\tau = 50)
C20200.100.100.00500.00502nd (r(2)r_{(2)})max⁡(20,50)=𝟓𝟎\max(20, 50) = \mathbf{50}
D550.400.400.08000.0800Evicted (rD>τr_D > \tau)00
  • True Total Weight: W=100+10+20+5=𝟏𝟑𝟓W = 100 + 10 + 20 + 5 = \mathbf{135}
  • Estimated Total Weight: W^=w^A+w^C=100+50=𝟏𝟓𝟎\hat{W} = \hat{w}_A + \hat{w}_C = 100 + 50 = \mathbf{150}A note added on 2026-11-13: in this table A and C tie at rank 0.0050.005 (0.50/100=0.10/200.50/100 = 0.10/20), so “1st” and “2nd” are a convention, not an order. Nothing else changes: both are among the k−1=2k - 1 = 2 samples, τ=0.02\tau = 0.02 and the estimates stand. With hashes drawn from a continuous distribution a tie has probability zero.

Heavy item A (wA>1/τw_A > 1/\tau) retains its exact weight (100100), whereas light item C (wC<1/τw_C < 1/\tau) is scaled up to 1/τ=501/\tau = 50 to represent both itself and unsampled light items.

3. Mathematical Proof of Unbiasedness

3.1 The Leave-One-Out Threshold τ−i\tau_{-i}

Let r1,…,rNr_1, \dots, r_N be independent continuous random variables with CDFs Fi(t)=Pr⁡(ri<t)F_i(t) = \Pr(r_i < t), and N≥k≥2N \ge k \ge 2 (with fewer items every one is kept, with w^i=wi\hat{w}_i = w_i). Let r(1)<⋯<r(k)r_{(1)} < \dots < r_{(k)} be the sorted ranks, and set global threshold τ=r(k)\tau = r_{(k)}.

For any item ii, define the leave-one-out threshold τ−i\tau_{-i} as the (k−1)(k-1)-th smallest rank among all items excluding ii:

τ−i=r(k−1)(−i)\tau_{-i} = r_{(k-1)}^{(-i)}

Because ranks are mutually independent, τ−i\tau_{-i} is independent of rir_i.Conditioning on the ranks of the other items is Cohen and Kaplan’s rank conditioning, which generalises the derivation Duffield, Lund and Thorup gave for priority sampling to any family of rank distributions.Edith Cohen and Haim Kaplan. Tighter estimation using bottom k sketches. Proceedings of the VLDB Endowment, 1(1):213–224, 2008. doi: 10.14778/1453856.1453884. URL https://doi.org/10.14778/1453856.1453884

3.1.1 Fundamental Equivalence

  1. Item ii is inside the top k−1k-1 overall ranks if and only if ri<τ−ir_i < \tau_{-i}: ri<τ  ⟺  ri<τ−ir_i < \tau \iff r_i < \tau_{-i}
  2. Whenever ri<τ−ir_i < \tau_{-i} holds, inserting rir_i shifts the kk-th overall threshold to match τ−i\tau_{-i}: ri<τ−i  ⟹  τ=τ−ir_i < \tau_{-i} \implies \tau = \tau_{-i}

3.2 General Unbiasedness Proof

Define the indicator 𝕀(ri<τ)\mathbb{I}(r_i < \tau) and the adjusted weight estimator:

w^i=wiFi(τ)⋅𝕀(ri<τ)\hat{w}_i = \frac{w_i}{F_i(\tau)} \cdot \mathbb{I}(r_i < \tau)

Using the equivalences from Section 3.1:

w^i=wiFi(τ−i)⋅𝕀(ri<τ−i)\hat{w}_i = \frac{w_i}{F_i(\tau_{-i})} \cdot \mathbb{I}(r_i < \tau_{-i})

Applying the Law of Total Expectation by conditioning on τ−i\tau_{-i}:

𝔼[w^i]=𝔼τ−i[𝔼ri[w^i  ∣  τ−i]]\mathbb{E}[\hat{w}_i] = \mathbb{E}_{\tau_{-i}}\Big[ \mathbb{E}_{r_i}\big[\hat{w}_i \;\big|\; \tau_{-i}\big] \Big]

Evaluating the inner expectation with τ−i\tau_{-i} held fixed:

𝔼ri[w^i  ∣  τ−i]=wiFi(τ−i)⋅𝔼ri[𝕀(ri<τ−i)  ∣  τ−i]=wiFi(τ−i)⋅Pr⁡(ri<τ−i∣τ−i)\begin{aligned} \mathbb{E}_{r_i}\big[\hat{w}_i \;\big|\; \tau_{-i}\big] &= \frac{w_i}{F_i(\tau_{-i})} \cdot \mathbb{E}_{r_i}\big[\mathbb{I}(r_i < \tau_{-i}) \;\big|\; \tau_{-i}\big] \\ &= \frac{w_i}{F_i(\tau_{-i})} \cdot \Pr(r_i < \tau_{-i} \mid \tau_{-i}) \end{aligned}

Since rir_i is independent of τ−i\tau_{-i}, Pr⁡(ri<τ−i∣τ−i)=Fi(τ−i)\Pr(r_i < \tau_{-i} \mid \tau_{-i}) = F_i(\tau_{-i}). Thus:

𝔼ri[w^i  ∣  τ−i]=wiFi(τ−i)⋅Fi(τ−i)=wi\mathbb{E}_{r_i}\big[\hat{w}_i \;\big|\; \tau_{-i}\big] = \frac{w_i}{F_i(\tau_{-i})} \cdot F_i(\tau_{-i}) = w_i

Taking the outer expectation:

𝔼[w^i]=𝔼τ−i[wi]=wi\mathbb{E}[\hat{w}_i] = \mathbb{E}_{\tau_{-i}}[w_i] = w_i

By linearity of expectation, for any subset Q⊆{1,…,N}Q \subseteq \{1, \dots, N\}:

𝔼[W^Q]=∑i∈Q𝔼[w^i]=∑i∈Qwi=WQ■\mathbb{E}[\hat{W}_Q] = \sum_{i \in Q} \mathbb{E}[\hat{w}_i] = \sum_{i \in Q} w_i = W_Q \quad \blacksquare

3.3 Instantiating Distributions

Evaluating Fi(t)=Pr⁡(ri<t)F_i(t) = \Pr(r_i < t) for specific rank transformations:

  • Priority Sampling (ri=ui/wir_i = u_i / w_i):

    Fi(t)=Pr⁡(ui<wit)=min⁡(1,wit)  ⟹  w^i=wimin⁡(1,wiτ)=max⁡(wi,1τ)F_i(t) = \Pr(u_i < w_i t) = \min(1, w_i t) \implies \hat{w}_i = \frac{w_i}{\min(1, w_i \tau)} = \max\left(w_i, \frac{1}{\tau}\right)
  • Exponential Scaling (ri=−ln⁡(ui)/wir_i = -\ln(u_i) / w_i):

    Fi(t)=Pr⁡(ui>e−wit)=1−e−wit  ⟹  w^i=wi1−e−wiτF_i(t) = \Pr(u_i > e^{-w_i t}) = 1 - e^{-w_i t} \implies \hat{w}_i = \frac{w_i}{1 - e^{-w_i \tau}}

3.4 Why the kk-th Item acts as a Threshold Setter

Let ii be the item at position kk, so ri=r(k)=τr_i = r_{(k)} = \tau. Then 𝕀(ri<τ)=0\mathbb{I}(r_i < \tau) = 0, and the estimator of §3.2 gives w^(k)=0\hat{w}_{(k)} = 0 by itself: its leave-one-out threshold τ−i=r(k−1)(−i)=r(k−1)\tau_{-i} = r_{(k-1)}^{(-i)} = r_{(k-1)} lies below rir_i. Counting the kk-th item as a sample would mean a sample of size kk, whose leave-one-out threshold would be the kk-th smallest of the other ranks, r(k)(−i)=r(k+1)r_{(k)}^{(-i)} = r_{(k+1)}, which a sketch of capacity kk discards (this is the shifted convention of §6.5). So the kk-th item serves only as the threshold τ\tau.

3.5 Pairwise Zero Covariance Property

For Priority Sampling, Duffield et al.Nick Duffield, Carsten Lund, and Mikkel Thorup. Priority sampling for estimation of arbitrary subset sums. Journal of the ACM, 54(6), December 2007. doi: 10.1145/1314690.1314696. URL https://doi.org/10.1145/1314690.1314696. Article 32 proved that for any two distinct items i≠ji \ne j:

Cov(w^i,w^j)=0\text{Cov}(\hat{w}_i, \hat{w}_j) = 0

As a result, the variance of a subset sum equals the sum of the individual variances:

Var(W^Q)=∑i∈QVar(w^i)\text{Var}(\hat{W}_Q) = \sum_{i \in Q} \text{Var}(\hat{w}_i)

4. High-Performance Implementations

4.1 Systems Optimization Strategies

  1. O(1)O(1) Branch-Light Fast-Path Rejection: Cache τ=r(k)\tau = r_{(k)} in a dedicated field. Over 99%99\% of items in large streams fail ri<τr_i < \tau and are rejected immediately without touching heap memory, as long as the weights do not trend upward along the stream (equal or i.i.d. weights, or items in random order; see §4.4).
  2. IEEE-754 Bit-Level Floating Point Generation: Construct uniform ui∈(0,1)u_i \in (0, 1) by ORing z >> 12 into the mantissa of double 1.0 (0x3FF0000000000000), forcing the lowest mantissa bit to 1, and subtracting 1.0. 51 hash bits survive, and uiu_i is an odd multiple of 2−522^{-52} between 2−522^{-52} and 1−2−521 - 2^{-52}: the forced bit is what keeps uiu_i from being 00. (The crate’s hash, §7.4, keeps all 52 bits on the midpoint grid instead.)
  3. Preconditions: each id is offered at most once, with its weight already aggregated per key (a repeated id is a repeated item), and weights are positive and finite; update drops any other weight.
  4. In-Place Heap Replacement: Overwrite root heap[0] directly and run sift_down(0) instead of executing sequential pop() and push() calls.

4.2 Rust Implementation

use std::cmp::Ordering;

/// A single entry in the Priority Sampling Bottom-k Sketch.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct SketchEntry {
    pub rank: f64,      // Priority rank r_i = u_i / w_i
    pub weight: f64,    // True item weight w_i
    pub id: u64,        // Item identifier
    pub payload: u32,   // Dimension tag / group ID for subset predicates
}

impl PartialEq for SketchEntry {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.rank == other.rank && self.id == other.id
    }
}
impl Eq for SketchEntry {}

impl PartialOrd for SketchEntry {
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SketchEntry {
    #[inline(always)]
    fn cmp(&self, other: &Self) -> Ordering {
        self.rank
            .total_cmp(&other.rank)
            .then_with(|| self.id.cmp(&other.id))
    }
}

/// SplitMix64's finalizer, applied to the seed once, so that seeds `s` and `s + 1` do not
/// hash `id` and `id + 1` alike.
fn mix_seed(seed: u64) -> u64 {
    let mut z = seed.wrapping_add(0x9E3779B97F4A7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
    z ^ (z >> 31)
}

/// Each `id` is offered at most once, with its weight already aggregated per key: a
/// repeated `id` is a repeated item, and `merge` assumes an `id` in both sketches
/// carries the same weight (so its two copies have equal ranks and sort adjacent).
pub struct PrioritySketch {
    k: usize,
    seed: u64, // mix_seed(seed): independent seeds give unrelated hashes
    threshold: f64, // Cached r_(k) for O(1) fast-path rejection
    heap: Vec<SketchEntry>,
}

impl PrioritySketch {
    pub fn with_capacity(k: usize, seed: u64) -> Self {
        assert!(k >= 2, "Capacity k must be >= 2");
        Self {
            k,
            seed: mix_seed(seed),
            threshold: f64::INFINITY,
            heap: Vec::with_capacity(k),
        }
    }

    #[inline(always)]
    fn hash_to_unit_float(&self, id: u64) -> f64 {
        let mut z = (id ^ self.seed).wrapping_add(0x9E3779B97F4A7C15);
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
        z ^= z >> 31;

        let bits = 0x3FF0_0000_0000_0000_u64 | (z >> 12) | 1;
        f64::from_bits(bits) - 1.0
    }

    #[inline]
    pub fn update(&mut self, id: u64, weight: f64, payload: u32) {
        if !(weight > 0.0 && weight.is_finite()) {
            return; // also drops NaN, which every comparison would let through
        }

        let u = self.hash_to_unit_float(id);
        let rank = u / weight;

        // FAST PATH: Rejects >99% of stream items with a single register comparison
        if rank >= self.threshold {
            return;
        }

        let entry = SketchEntry { rank, weight, id, payload };

        if self.heap.len() < self.k {
            let idx = self.heap.len();
            self.heap.push(entry);
            self.sift_up(idx);
            if self.heap.len() == self.k {
                self.threshold = self.heap[0].rank;
            }
        } else {
            self.heap[0] = entry;
            self.sift_down(0);
            self.threshold = self.heap[0].rank;
        }
    }

    pub fn estimate_subset<F>(&self, mut predicate: F) -> f64
    where
        F: FnMut(&SketchEntry) -> bool,
    {
        if self.heap.len() < self.k {
            return self.heap.iter().filter(|e| predicate(e)).map(|e| e.weight).sum();
        }

        let inv_tau = 1.0 / self.heap[0].rank;
        let mut sum = 0.0;

        for entry in &self.heap[1..] {
            if predicate(entry) {
                sum += entry.weight.max(inv_tau);
            }
        }
        sum
    }

    #[inline]
    pub fn estimate_total(&self) -> f64 {
        self.estimate_subset(|_| true)
    }

    pub fn merge(&mut self, other: &Self) {
        assert_eq!(self.seed, other.seed, "Seeds must match to merge sketches");

        let mut combined = Vec::with_capacity(self.heap.len() + other.heap.len());
        combined.extend_from_slice(&self.heap);
        combined.extend_from_slice(&other.heap);

        combined.sort_unstable();
        combined.dedup_by_key(|e| e.id);
        combined.truncate(self.k);

        self.heap.clear();
        self.threshold = f64::INFINITY;

        for entry in combined {
            let idx = self.heap.len();
            self.heap.push(entry);
            self.sift_up(idx);
        }
        if self.heap.len() == self.k {
            self.threshold = self.heap[0].rank;
        }
    }

    #[inline(always)]
    fn sift_up(&mut self, mut idx: usize) {
        let item = self.heap[idx];
        while idx > 0 {
            let parent = (idx - 1) >> 1;
            if item <= self.heap[parent] {
                break;
            }
            self.heap[idx] = self.heap[parent];
            idx = parent;
        }
        self.heap[idx] = item;
    }

    #[inline(always)]
    fn sift_down(&mut self, mut idx: usize) {
        let len = self.heap.len();
        let item = self.heap[idx];
        let half = len >> 1;

        while idx < half {
            let mut child = (idx << 1) + 1;
            let right = child + 1;
            if right < len && self.heap[right] > self.heap[child] {
                child = right;
            }
            if item >= self.heap[child] {
                break;
            }
            self.heap[idx] = self.heap[child];
            idx = child;
        }
        self.heap[idx] = item;
    }
}

4.3 C99 Implementation

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

typedef struct {
    double   rank;      // r_i = u_i / w_i
    double   weight;    // w_i
    uint64_t id;        // Item key
    uint32_t payload;   // Subset filter tag
    uint32_t _pad;      // 32-byte alignment padding
} SketchEntry;

typedef struct {
    size_t      k;
    size_t      len;
    uint64_t    seed;
    double      threshold; // Cached heap[0].rank
    SketchEntry heap[];    // Flexible array member
} PrioritySketch;

/* SplitMix64's finalizer, applied to the seed once in ps_create. */
static inline uint64_t mix_seed(uint64_t seed) {
    uint64_t z = seed + 0x9E3779B97F4A7C15ULL;
    z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
    z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
    return z ^ (z >> 31);
}

/* seed is the mixed seed: ids are offered once each, weights aggregated per key. */
static inline double hash_to_unit_float(uint64_t id, uint64_t seed) {
    uint64_t z = (id ^ seed) + 0x9E3779B97F4A7C15ULL;
    z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
    z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
    z ^= z >> 31;

    union { uint64_t u; double d; } conv;
    conv.u = 0x3FF0000000000000ULL | (z >> 12) | 1ULL;
    return conv.d - 1.0;
}

static inline bool entry_gt(const SketchEntry *a, const SketchEntry *b) {
    return (a->rank > b->rank) || (a->rank == b->rank && a->id > b->id);
}

PrioritySketch *ps_create(size_t k, uint64_t seed) {
    if (k < 2) return NULL;
    PrioritySketch *ps = malloc(sizeof(PrioritySketch) + k * sizeof(SketchEntry));
    if (!ps) return NULL;
    ps->k = k;
    ps->len = 0;
    ps->seed = mix_seed(seed);
    ps->threshold = INFINITY;
    return ps;
}

static inline void sift_up(SketchEntry *restrict heap, size_t idx) {
    SketchEntry item = heap[idx];
    while (idx > 0) {
        size_t parent = (idx - 1) >> 1;
        if (!entry_gt(&item, &heap[parent])) break;
        heap[idx] = heap[parent];
        idx = parent;
    }
    heap[idx] = item;
}

static inline void sift_down(SketchEntry *restrict heap, size_t len, size_t idx) {
    SketchEntry item = heap[idx];
    size_t half = len >> 1;
    while (idx < half) {
        size_t child = (idx << 1) + 1;
        size_t right = child + 1;
        if (right < len && entry_gt(&heap[right], &heap[child])) {
            child = right;
        }
        if (!entry_gt(&heap[child], &item)) break;
        heap[idx] = heap[child];
        idx = child;
    }
    heap[idx] = item;
}

void ps_update(PrioritySketch *restrict ps, uint64_t id, double weight, uint32_t payload) {
    if (!(weight > 0.0 && isfinite(weight))) return; /* drops NaN too */

    double u = hash_to_unit_float(id, ps->seed);
    double rank = u / weight;

    if (rank >= ps->threshold) return;

    SketchEntry entry = { .rank = rank, .weight = weight, .id = id, .payload = payload };

    if (ps->len < ps->k) {
        size_t idx = ps->len++;
        ps->heap[idx] = entry;
        sift_up(ps->heap, idx);
        if (ps->len == ps->k) {
            ps->threshold = ps->heap[0].rank;
        }
    } else {
        ps->heap[0] = entry;
        sift_down(ps->heap, ps->k, 0);
        ps->threshold = ps->heap[0].rank;
    }
}

typedef bool (*ps_predicate_fn)(const SketchEntry *entry, void *ctx);

double ps_estimate_subset(const PrioritySketch *restrict ps, ps_predicate_fn pred, void *ctx) {
    double sum = 0.0;
    if (ps->len < ps->k) {
        for (size_t i = 0; i < ps->len; ++i) {
            if (!pred || pred(&ps->heap[i], ctx)) sum += ps->heap[i].weight;
        }
        return sum;
    }

    double inv_tau = 1.0 / ps->heap[0].rank;
    for (size_t i = 1; i < ps->k; ++i) {
        if (!pred || pred(&ps->heap[i], ctx)) {
            double w = ps->heap[i].weight;
            sum += (w > inv_tau) ? w : inv_tau;
        }
    }
    return sum;
}

4.4 Complexity & Memory Profile

  • Memory Usage: 32×k32 \times k bytes. For k=1024k = 1024, total memory is 32 KB32\text{ KB}, fitting inside standard CPU L1 data caches.
  • Stream Update Throughput: a few ns per item, dominated by one hash and one division on the fast rejection path: about 3.2 ns/item for the Rust code above with weights computed on the fly, and about 4.1 ns/item with weights read from an 800 MB array (N=108N = 10^8, k=1024k = 1024, rustc -O, one core of a 2.2 GHz Xeon Gold 6238R; a benchmark, not a crate command).
  • Heap Replacements: When the ranks are exchangeable along the stream (equal or i.i.d. weights, or items in random order), item jj enters with probability k/jk/j, so the expected count is k(HN−Hk)≈kln⁡(N/k)k(H_N - H_k) \approx k \ln(N / k). For N=108N = 10^8 items and k=1024k = 1024, fewer than 12,00012,000 items trigger heap re-sorting. If the weights trend upward along the stream, the ranks ui/wiu_i/w_i trend downward and there are more replacements, up to one per item.

5. Sketching a Recurrence: the Colours of Bitcoin Transactions

Sections 1–4 sketch a stream: items arrive, each is seen once, and the sketch summarises the set seen so far. What follows uses the same ideas for a different job, and was built and measured in the Rust repository coloring-bt-transactions-rs as a new binary, sketch (src/bin/sketch.rs and the modules under src/bin/sketch/). Here every sketch is made from other sketches, mixed with real weights, by a recurrence that runs over the 778,613,440 transaction records of the 2022 Bitcoin chainSatoshi Nakamoto. Bitcoin: A Peer-to-Peer Electronic Cash System, 2008. URL https://bitcoin.org/bitcoin.pdf. The repository’s main binary, coloring-bt-transactions (src/main.rs), computes the same colours exactly, and §5.1–5.4 use it to set out the problem: the rule, the triangular system it solves, and how far an exact solve gets on the 2022 chain before memory stops it.

One thing should be said at the start, because the title of this post promises bottom-kk. The sketch that won is not literally a bottom-kk sketch. It is VarOptk_k with its light items chosen by systematic sampling in block order: a threshold sampler, the sibling of the priority sampling of §2 rather than one of its members. The literal weighted bottom-kk sketch of §2 was built too (prio below) and measured beside it; it lost by a factor of 6 to 21 at the same size (§8.4). Section 5.7 says which of what follows is known and which is new. Section 6 proves what each variant guarantees, section 7 shows the code, section 8 the measurements, and the reasons the threshold sampler wins run through all three. Section 10 turns to two questions that no sketch of a colour answers: from how many blocks a transaction descends, and how much two transactions share. Section 13 draws the exact colours where they still fit, over the first million records.

Every result of a run of sketch quoted below can be recomputed from files on disk by a mode of sketch. Most come from modes that fold nothing and only read what the runs wrote: sketch summarize turns the outputs of chain and eval into the tables of section 8 (the factor above is the column abs_dmean_over_varopt of its errors.tsv, at k=64k = 64, 256256 and 10241024), and sketch summary reads count streams back into the counts of sections 5.4 and 10. Section 7.10 lists the modes and the runs. Results of the main binary (§5.1–5.4, §7.3, §7.12, §13) are crate runs too, but of coloring-bt-transactions, and each is given with its command line or its flags. Two of its whole-chain runs left their logs on disk (colors.moments.log, colors.laplace.log), and the exact sizes of its --sets run are a file on disk; the rest were measured while the main binary was written, and are quoted from its documentation (the crate’s README.md, RUNNING-2022.md and source comments) or from its write-up, a description of the main binary that we wrote earlier and have not published, and each such result says which. What no mode of sketch computes is labelled where it appears: the prototypes and simulations of the design phase, runs of the main binary, benchmarks, wall-clock times from /usr/bin/time, and hand projections.

5.1 Colours

Number the blocks of the chain 0,1,…,L−10, 1, \dots, L - 1, with L=762,261L = 762{,}261 for 2022. The colour of a transaction tt is a probability distribution over blocks, written as a polynomial

Ct=∑b=0L−1ct(b) xb,ct(b)≥0,∑b=0L−1ct(b)=1, C_t = \sum_{b=0}^{L-1} c_t(b)\, x^{b}, \qquad c_t(b) \ge 0, \quad \sum_{b=0}^{L-1} c_t(b) = 1,

where ct(b)c_t(b) is the fraction of tt’s value that was minted in block bb. A coinbase minted in block β\beta has Ct=xβC_t = x^{\beta}. Any other transaction spends inputs i=1,…,ni = 1, \dots, n with amounts aia_i, taken from earlier transactions p1,…,pnp_1, \dots, p_n, and its colour is the amount-weighted mixture of theirs:

Ct=∑i=1nst,i Cpi,st,i=ai∑j=1naj C_t = \sum_{i=1}^{n} s_{t,i}\, C_{p_i}, \qquad s_{t,i} = \frac{a_i}{\sum_{j=1}^{n} a_j} (1)

with equal shares st,i=1/ns_{t,i} = 1/n when the amounts sum to zero. The shares are nonnegative and sum to one, so by induction every colour is a probability distribution.Read for one block, or for a set of blocks, this amount-weighted rule is the haircut taint policy of Möser, Böhme and Breuker, under which a transaction is devalued in proportion to the tainted value among its inputs, recursively; a colour carries the haircut taint of every coinbase at once. Anderson et al. argue for a first-in-first-out rule instead, after the precedent of Clayton’s case. Tironsakkul et al. compare haircut, poison and first-in-first-out with last-in-first-out and “taint in, highest out” on two thefts; each policy carries one number of taint per source, not a distribution over origins.Malte Möser, Rainer Böhme, and Dominic Breuker. Towards Risk Scoring of Bitcoin Transactions. In Rainer Böhme, Michael Brenner, Tyler Moore, and Matthew Smith, editors, Financial Cryptography and Data Security: FC 2014 Workshops, BITCOIN and WAHC 2014, volume 8438 of Lecture Notes in Computer Science, pages 16–32. Springer, 2014. doi: 10.1007/978-3-662-44774-1_2. URL https://doi.org/10.1007/978-3-662-44774-1_2; Ross Anderson, Ilia Shumailov, Mansoor Ahmed, and Alessandro Rietmann. Bitcoin Redux. Workshop on the Economics of Information Security (WEIS 2018), Innsbruck, June 2018. URL https://www.cl.cam.ac.uk/~rja14/Papers/bitcoin-redux.pdf; and Tin Tironsakkul, Manuel Maarek, Andrea Eross, and Mike Just. Probing the Mystery of Cryptocurrency Theft: An Investigation into Methods for Taint Analysis, 2019. URL https://arxiv.org/abs/1906.05754. arXiv:1906.05754 The records come in file order and every input spends an earlier record, so the transactions form a DAG listed in topological order, and (1) is evaluated in one pass. The repository’s main binary does exactly that with --weighted (the loop in src/main.rs’s run()):

coloring-bt-transactions all --weighted < finalBCUTXO_2022.scm

prints every record’s colour as its terms, block and coefficient; without all it stops at a default limit of 1,000,001 records. Two facts make that fold checkable.

  • Mass. A record’s shares sum to one, and computed in f64 they do so to within 1.02×10−131.02 \times 10^{-13} on every record of the chain (measured by the crate’s example matrix --csr, §7.12). Under --stats the main binary audits the fold and prints the worst drift of a colour’s mass from one.No exact --weighted fold has reached the end of the chain (§5.3), so there is no whole-chain drift of the exact colours to quote. The two whole-chain runs that wrote the exact references below (§5.2) carry the colours in f32 band lanes, and their audits report 3.138×10−53.138 \times 10^{-5} (--bands 1024, colors.moments.log) and 1.096×10−41.096 \times 10^{-4} (--bands 1, colors.laplace.log); the moments and Laplace values beside the lanes are carried in f64.
  • Blocks. Which blocks a colour names does not depend on the weights. The terms --weighted prints, zero coefficients included (src/weighted.rs prunes nothing), are exactly the blocks the unweighted fold computes; only the coefficients differ. The blocks with a positive coefficient are the pos support of §10.1, which differs from them only through zero-amount inputs and f64 underflow.

Give every input weight one and a colour becomes a set of blocks, with union in place of the sum: the support recurrence (5) of §10.1. That reading is older; it is what the Scheme program that preceded the crate computed. The main binary keeps two implementations of it, --rings (circular linked lists, the default) and --sets (sorted u32 arrays), which share no code and print byte-identical output: diffing the two is a stronger check of the fast one than any test it could be given alone.

A colour is read through linear functionals: its mean block and its spread, its CDF (“how much of this is older than block xx”) and its Laplace values,

Ft(x)=∑b=0xct(b),Λs(Ct)=∑b=0L−1ct(b) e−sb/L, F_t(x) = \sum_{b=0}^{x} c_t(b), \qquad \Lambda_s(C_t) = \sum_{b=0}^{L-1} c_t(b)\, e^{-s b / L},

at s∈{0.5,1,2,4,8,16,32}s \in \{0.5, 1, 2, 4, 8, 16, 32\}. Their values for every transaction of the chain are on disk, solved as §5.2 shows, and they are what the sketches are measured against in section 8.

5.2 A triangular solve

Number the records 0,1,2,…0, 1, 2, \dots in file order, and read a colour as the row vector of its coefficients (ct(0),…,ct(L−1))(c_t(0), \dots, c_t(L - 1)). Matrices are written as bold letters or, like Π\Pi of §10.6, as Greek capitals, and an entry as Γt,p\Gamma_{t,p}, row before column (Πjb\Pi_{jb} of §10.6 drops the comma). The share matrix Γ\Gamma is square, with a row and a column for every record, and holds the share of tt’s value spent from record pp:

Γt,p=∑1≤i≤npi=pst,i. \Gamma_{t,p} = \sum_{\substack{1 \le i \le n \\ p_i = p}} s_{t,i} .

It is 00 when tt spends nothing of pp, and it is the summed share s¯g\bar s_g of Proposition 28 when pp is the parent qgq_g of a group. A coinbase’s row is zero, and every other row sums to one. Every input spends an earlier record, so Γ\Gamma is strictly lower triangular. Let the colour matrix 𝐂\mathbf{C} have row tt equal to CtC_t, and the coinbase matrix 𝐄\mathbf{E} have row tt equal to eβe_\beta when tt is the coinbase of block β\beta (the eβe_\beta of §10.6, all its mass on β\beta) and 00 otherwise; 𝐈\mathbf{I} is the identity. Row tt of Γ 𝐂\Gamma\,\mathbf{C} is ∑p=0t−1Γt,p Cp\sum_{p=0}^{t-1} \Gamma_{t,p}\, C_p, which is (1) with the inputs grouped by parent, so the recurrence for all records at once reads

𝐂=Γ 𝐂+𝐄  ⟺  (𝐈−Γ) 𝐂=𝐄  ⟺  𝐂=(𝐈−Γ)−1 𝐄. \mathbf{C} = \Gamma\,\mathbf{C} + \mathbf{E} \quad\iff\quad (\mathbf{I} - \Gamma)\,\mathbf{C} = \mathbf{E} \quad\iff\quad \mathbf{C} = (\mathbf{I} - \Gamma)^{-1}\,\mathbf{E} . (2)

𝐈−Γ\mathbf{I} - \Gamma is unit lower triangular, and the one pass of §5.1 is forward substitution on itJohn R. Gilbert and Tim Peierls. Sparse partial pivoting in time proportional to arithmetic operations. SIAM Journal on Scientific and Statistical Computing, 9(5):862–874, 1988. doi: 10.1137/0909058. URL https://doi.org/10.1137/0909058; and Timothy A. Davis. Direct Methods for Sparse Linear Systems. Fundamentals of Algorithms. Society for Industrial and Applied Mathematics, 2006. doi: 10.1137/1.9780898718881. URL https://doi.org/10.1137/1.9780898718881: row tt is solved from rows already solved, with the same arithmetic in the same order.The rows are records: 778,613,440 of them, for 778,613,438 distinct transaction ids. The two BIP-30 duplicate coinbases, records 142,783 and 142,841, repeat the ids of earlier coinbases; each is a coinbase row of its own, and an input that names a duplicated id reads the later record (the insert displaces the older colour, §7.5). The chain has 2,044,897,328 inputs, so Γ\Gamma has at most that many nonzero entries: a parent spent twice by one record adds both shares into one entry. Four things follow from reading it so.

It explains the cost. An entry (Γj)t,r≠0(\Gamma^{j})_{t,r} \ne 0 needs a path of jj edges from rr to tt, and every path extends back to a coinbase, so Γd+1=0\Gamma^{d+1} = 0 for d=max⁡tdtd = \max_t d_t, the longest path of Corollary 12, and the inverse is a finite sum,

(𝐈−Γ)−1=∑j=0dΓj,d=max⁡tdt. (\mathbf{I} - \Gamma)^{-1} = \sum_{j=0}^{d} \Gamma^{j}, \qquad d = \max_t d_t .

Its entry (t,r)(t, r) is the sum, over all paths from rr to tt, of the products of the shares along them: the αt,r\alpha_{t,r} of Theorem 9. The inverse of a sparse triangular matrix fills in along reachability in its graph, and row tt of 𝐂\mathbf{C} has a block wherever tt reaches that block’s coinbase through positive shares: the support St+S^+_t of §10.1 (pos). That fill-in, and its sets form below, are what §5.3 and §5.4 measure. There is nothing to factor and no ordering to choose: 𝐈−Γ\mathbf{I} - \Gamma is already triangular, in the order of the chain, and the fill-in is in the answer, not in a factor that a better ordering could keep sparse.

It names the working set. Forward substitution must keep row pp until the last row tt with Γt,p≠0\Gamma_{t,p} \ne 0 has been solved, and the sets form of the Boolean solve below, which keeps zero-amount inputs, until the last row that spends pp at all. A stream can bound that only by “has an unspent output”; the release oracle of §5.3 answers the second question exactly, and so bounds the first.

It says what can be computed. The solve is linear, so it commutes with every linear map of the colours. For any L×νL \times \nu matrix Φ\Phi,

𝐂 Φ=(𝐈−Γ)−1 (𝐄 Φ). \mathbf{C}\,\Phi = (\mathbf{I} - \Gamma)^{-1}\,(\mathbf{E}\,\Phi) . (3)

It is the same forward substitution, with ν\nu columns on the right instead of L=762,261L = 762{,}261. The memory per live record is ν\nu numbers, flat in the size of the colour, and the result is exact for whatever Φ\Phi projects onto (in exact arithmetic; the main binary carries the moments and Laplace values in f64 and the bands in f32 lanes, §5.1). The functionals of §5.1 are such projections: ν=3\nu = 3 and row bb of Φ\Phi equal to (1,b,b2)(1, b, b^2) for the mass and the first two moments, from which the mean and the spread follow; the column 𝟏{b≤x}\mathbf{1}\{b \le x\} for a cut Ft(x)F_t(x); ν=7\nu = 7 and Φb,j=e−sjb/L\Phi_{b,j} = e^{-s_j b / L}, with s1,…,s7s_1, \dots, s_7 the values of §5.1, for the Laplace values; and ν=1,024\nu = 1{,}024 band indicators for the binned colours. They are the mean and spread of the main binary’s --moments, its --laplace and its --bands 1024, and the exact references of section 8 are such solves:

coloring-bt-transactions all --bands 1024 --moments --stats \
    --release-oracle lastspend-2022.u32 < finalBCUTXO_2022.scm    # colors.moments.zst
coloring-bt-transactions all --bands 1 --laplace --stats \
    --release-oracle lastspend-2022.u32 < finalBCUTXO_2022.scm    # colors.laplace.zst

The first took 1 h 30 min 48 s at a peak of 37.72 GB, the second 38 min 43 s at 5.08 GB (/usr/bin/time -v, at the end of colors.moments.log and colors.laplace.log). The binned colours of colors.bands1024.zst came from a third such run, --bands 1024 under the same release oracle, which read the share matrix of §7.12 in place of the records: 5 h 00 min 18 s at 37.0 GB resident, by the write-up (its log was not kept), and 8.67 TiB of text, which zstd took to the 1.52 TiB of the file on disk.

The L1 sketch of §10.6 is (3) too, with Φb,j=Πjb\Phi_{b,j} = \Pi_{jb} for the blocks b<Lb < L and ν=m\nu = m: Proposition 28 is that equation read row by row. What is not linear in the colour stays outside. The effective number of blocks of a colour, 1/∑b=0L−1ct(b)21 / \sum_{b=0}^{L-1} c_t(b)^2, is quadratic, and no projection gives it: if Φ\Phi has fewer than LL columns, some direction dd with d Φ=0d\,\Phi = 0 changes ∑b=0L−1ct(b)2\sum_{b=0}^{L-1} c_t(b)^2 but not Ct ΦC_t\,\Phi. So the fourth field of a line of colors.moments.zst, the effective number of blocks, is not one of these solves: under --bands the main binary reads it off the bands, and nothing here uses it.

The support is the same solve over the Booleans. With “or” and “and” in place of the sum and the product, and Γ\Gamma replaced by a 0/10/1 matrix, forward substitution yields the supports: the nonzero pattern of Γ\Gamma gives St+S^+_t (pos), and the adjacency of the spend graph, an entry wherever tt spends pp, zero amounts included, gives StS_t of (5) (sets). The series ∑j≥0Γj\sum_{j \ge 0} \Gamma^{j} becomes the reflexive and transitive closure of that graph. The bottom-kk selection KkK_k of §10.3 is not linear, but it passes through unions,

Kk(S1∪⋯∪SG)=Kk(Kk(S1)∪⋯∪Kk(SG)) K_k(S_1 \cup \dots \cup S_G) = K_k\big(K_k(S_1) \cup \dots \cup K_k(S_G)\big)

(Lemma 20), so it can be applied after every union of this solve, as Φ\Phi is applied to the real one, and still yields Kk(St)K_k(S_t) at every record (Theorem 22): that is Cohen’s size estimation for reachability sets.Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534

The sketches of §5.5 are this forward substitution with every solved row replaced by a randomised reduction of itself (unbiased for varopt and prio, §6.2) before any later row reads it.

5.3 Why the exact colours do not fit

The support of CtC_t is the union of the supports of its parents with a positive share (every parent but a zero-amount input, §10.1), so colours only grow. How much must be held is a count, not an extrapolation. The main binary’s driver holds a colour for every transaction with an unspent output, and a colour-free pass over the file counts them: 92,735,490 at the end of the 2022 chain and 92,753,575 at the peak (quoted from the crate’s documentation, src/oracle.rs). A budget of 450 GB, a round figure below the 503 GiB (540 GB) of memory of the machine of these runs, over that count is

450×109 bytes92,735,490≈4,852 bytes a colour, \frac{450 \times 10^{9}\ \text{bytes}}{92{,}735{,}490} \approx 4{,}852\ \text{bytes a colour},

404 weighted terms of 12 bytes (a u32 block and an f64 coefficient), or 1,213 set terms of 4. The weighted fold passes that early in the file, as Table 1 measures on prefixes of it.

Table 1: The exact weighted fold on prefixes of the 2022 chain, a run of the main binary, not of sketch: coloring-bt-transactions <records> --weighted --sum --stats < finalBCUTXO_2022.scm. --sum prints one number a line and walks the same terms as the full output. The store holds a colour for every transaction with an unspent output, with no release oracle, so these means differ from those of Table 2 and §5.4. The first three rows are in the crate’s RUNNING-2022.md; the 3M row is from the main binary’s write-up. No log of these runs was kept.
recordsmean colour held (blocks)distinct terms held (×12 B)resident
500,0001,0871.8 GB–
1,000,0004,72315.2 GB–
1,500,0005,98427.7 GB32 GB
3,000,00012,754102.6 GB107.75 GiB

The mean colour grows as records1.37\text{records}^{1.37}, and the store is terms, not overhead: at 3M records mallinfo2 reports 102.59 GB in use against terms×12=102.57\text{terms} \times 12 = 102.57 GB. Throughput over that span fell from 958,000 records a second to 760. The growth steepens: the local exponent of the live terms rose over successive half-million windows (1.48, 1.45, 1.82, 2.28), and fits that honour the rise put the wall, at the write-up’s budget of 450 GiB, between 4.8M and 8M records, or 8M to 11M with every exact saving the main binary has, under 1.5% of the file in every case (a hand projection). The 3M-record figures, the 760 records a second, the exponents and the fits are from the main binary’s write-up; RUNNING-2022.md records the fall to 3,000 records a second by 1.5M records.

The exact colour of every transaction of the 2022 chain cannot be materialised on this machine, under any per-transaction representation, and it is not close. That is the fill-in of (2): 𝐂\mathbf{C} is a 778,613,440×762,261778{,}613{,}440 \times 762{,}261 matrix whose rows, at depth, cover most of the past. Even with every colour frozen at the 12,754 blocks of the 3M-record prefix, a store of the census’s 92,735,490 colours would be 12.9 TiB weighted, 4.3 TiB as sets or 8.0 TiB at a bit per block, and the text of every record’s colour, at about 22 bytes a term, is over 100 TB.

Freeing colours earlier. “Has an unspent output” is the only question a stream can ask, and the wrong one: what forward substitution needs (§5.2) is whether a later record of this file reads the colour again. Of the 136 million outputs unspent at the end of the chain, 51,815,075 are OP_RETURN, unspendable, and none of the file’s 2,044,897,328 inputs touches them (from src/oracle.rs). A file has a future, so the right question is answered by reading it once first. The main binary’s examples/lastspend.rs writes, in one pass, the last record that spends each transaction,

cargo run --release --example lastspend -- lastspend-2022.u32 < finalBCUTXO_2022.scm

in 5 min 27 s and 2.9 GiB resident, about the size of the array it fills, a file of 3.11 GB (time and memory from the write-up, which writes “2.9 GB”), and --release-oracle lastspend-2022.u32 hands it to the fold; it is the file every sketch run of §7.10 takes with --oracle. The peak of the live colours falls from 92,753,575 to 19,361,261, 4.79 times fewer (from examples/lastspend.rs’s documentation). The two whole-chain runs of §5.2 agree: their --stats progress lines, every 100,000 records, peak at 19,346,275 colours held, at record 291.4M. Over the first 400,000 records the oracle takes --weighted --sum from 947 MB to 258 MB resident and from 5.67 s to 5.26 s, with byte-identical output under every backend (from the write-up). Since a stale oracle would free a colour still wanted and quietly give a wrong answer, the file carries a magic string and a record count, checked before any record is read, and every record is checked against a bound. One subtlety matters later (§7.12): a record that spends the same transaction twice must free it on the lowest input index that names it, because the fold walks its inputs from the last to the first (§7.5), and the lowest index is the one it reaches last.

Under the oracle the distinct live colours of sketch still peak at about 7.6M (7,593,630 distinct live sketches at the peak of the production run, peak sketches in its --stats, §9; distinct, because a record that spends one parent shares that parent’s sketch, §7.2, so this counts fewer than the 19.4M colours held). Multiplied by hundreds of thousands of blocks, that does not fit in any memory.

5.4 How far the exact sets reach

The cheapest exact colour goes further than the weighted one: --sets under the release oracle, four bytes a block rather than twelve, and only the colours the rest of the file reads. It was run for the size of every colour, the number of blocks in it, which is the number of its terms (every coefficient is 1 under --sets):

coloring-bt-transactions all --sets --stats --threads 4 \
    --release-oracle lastspend-2022.u32 < finalBCUTXO_2022.scm | count

With --threads 4, four threads format the printed terms while the main thread folds, byte-identical to a serial run. count is a forty-line C filter outside the crate: it counts the terms of each line, checks that every coefficient is exactly 1, and prints the count, which became finalBCUTXO_2022.sets-counts.31187785.txt (194 MB, one count a line). It is there because the text is long: an earlier --sets run over the first million records, counted by mawk, spent twelve of its fifteen and a half minutes in mawk, and by the end of this run a line has over 150,000 terms. A shell loop, also outside the crate, read the fold’s resident set from /proc every two seconds and would kill it at 480 GiB, or when the machine had less than 10 GiB available.

The guard fired at 480 GiB, with 14 GiB still available and no swap touched, after 31,187,785 records, 4.0% of the file, in 29 h 14 min. Every term of every line had coefficient 1.

recordselapsedratelive block idscolours heldmean heldresident
1,000,0003 min3k/s1.20G184,4666,5188.1 GiB
2,000,00013 min1k/s3.13G347,7589,01115.9 GiB
3,000,00032 min579/s7.11G450,74315,77931.7 GiB
5,000,0001.9 h399/s10.93G547,58019,96947.3 GiB
10,000,0005.8 h312/s22.16G799,46027,72290.0 GiB
15,000,00010.4 h297/s37.66G976,54738,561149.9 GiB
20,000,00015.4 h259/s58.00G1,058,19454,809226.8 GiB
25,000,00021.2 h229/s78.03G1,175,54966,376303.2 GiB
30,000,00027.6 h210/s115.50G1,402,29482,368444.0 GiB
31,100,00029.1 h202/s123.95G1,452,31085,350476.5 GiB
Table 2: The exact --sets fold under the release oracle, a run of the main binary: records folded, wall time, rate, block ids in the colours held, colours held, their mean size, and the resident set. From the run’s --stats progress lines and the guard’s readings, as recorded in the main binary’s write-up; that log was not kept. The colours held are also the colored txs column of colors.moments.log, whose run used the same oracle, and agree with it at every row.

Where the memory goes. Into block ids, as the weighted fold’s went into terms. A colour is an Rc<[u32]>, ascending, so 123.95G live ids are 461.8 GiB at four bytes; the 14.7 GiB between that and the resident set is the hash map of the colours held, the allocator’s slack and the batches in flight to the formatting threads. Nothing is stored for the coefficients. The growth is in the size of a colour held more than in their number: between 5M and 31.1M records the colours held rise 2.7 times and their mean size 4.3 times, and the cost of a million records rises with it, 8.5 GiB between 5M and 10M records, 15 between 15M and 25M, and 28 to 30 from 25M to the end. The rate falls the same way, from 399 records a second to 202, since a union reads and writes both of its operands whole and the operands are now hundreds of kilobytes.A first run, single-threaded and to /dev/null, was stopped by hand at 23,800,000 records after 20.6 h, at a peak of 297.5 GiB. Both runs held the same 77,680,891,395 block ids at that record, as they must; the one above got there 50 minutes sooner and 4.7 GiB larger, the cost of the formatting threads and the pipe. These numbers are from the write-up; no log was kept.

Two panels on log axes of colour size, the number of blocks in a colour, for the first 31.2 million records. Left: records per size, a peak of 2.87 million colours of one block, a long low middle between about 400 and 75 thousand records per bin, and a second peak near 10 million records above 100 thousand blocks. Right: the cumulative share of records, 9.2 percent at one block, flat near 15 to 18 percent from 10 to 100 thousand blocks, then rising almost vertically to 100 percent by 236 thousand blocks, median 174,376.
Figure 1: Colour size, the number of blocks in the support StS_t of a colour, for each of the first 31,187,785 records of the 2022 chain, from the --sets run of §5.4 (main binary, release oracle, stopped by the memory guard at 480 GiB). (a) Records per size: one bin per size below 10, then ten log-width bins a decade. (b) The share of records with at most that many blocks, exactly, one step per distinct size (191,575 of them). Drawn by figs_exact.py, a script outside the crate, from the histogram of finalBCUTXO_2022.sets-counts.31187785.txt.

What the colours look like. Figure 1 shows two populations with almost nothing between them. 2,872,504 records, 9.2%, have a colour of exactly one block, and 15.5% have at most 10,000. Then the cumulative share is flat for more than two decades, and from about 120,000 blocks it climbs nearly vertically: the quartiles are 136,609, 174,376 and 206,256 blocks, the mean is 152,823, and the largest colour has 236,013 blocks. Over the last million of these records the median is about 234,000 (233,620). By the end of the prefix most transactions descend from tens of thousands of blocks or more, and the ones that do not descend from very few. The first million records alone look nothing like this: their median is 3 blocks, the mean 8,411, the largest colour 72,383, and 41% of them have a colour of one block. The large population is what the chain grows into, and it grows at its own front edge: in the snapshots taken every three hours during the run, most of the records added since the one before fell into the top one or two bins, next to the largest colour of the moment (from the write-up). These statistics are computed from finalBCUTXO_2022.sets-counts.31187785.txt and finalBCUTXO_2022.sets-counts.1000001.txt by stats_counts.py, a script kept with the runs’ evidence outside the crate, and sketch reports the two medians as the column ref_p50 of the summary.tsv it writes when it reads the production count file of §10.11 beside these sizes:

sketch summary --in colors.kmv1024.counts.zst \
    --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt \
    --range 0:31187785 --range 30187785:31187785 --out summary

Exact sets, with every saving the main binary has, reach 4% of the chain on this machine, and the last million records cost about 30 GiB. That cost is still rising, so twice the memory would, by a hand extrapolation of that rise, buy a few million records more, not a second 31 million. It is not the code that stops the fold but the size of what is asked for, the fill-in of the Boolean form of (2). Section 10.10 carries the count to the end of the chain by the coordinated bottom-kk of §10.3, exact wherever a support has at most kk blocks.

5.5 Sketching the recurrence

So every colour is replaced by a sketch C^t\hat C_t of at most about kk entries, and the sketches are computed by the same recurrence:

C^t=Rt(Xt),Xt=∑i=1nst,i C^pi, \hat C_t = R_t\big(X_t\big), \qquad X_t = \sum_{i=1}^{n} s_{t,i}\, \hat C_{p_i}, (4)

where XtX_t, the candidate, is the exact mixture of the parents’ sketches, and RtR_t is a randomised reduction back to about kk points, applied only when XtX_t has more than kk points (otherwise C^t=Xt\hat C_t = X_t; this holds for varopt and prio, while coord also applies the threshold inherited from its operands, which can drop terms even below kk, §6.6 and §7.8). A coinbase is C^t=xβ\hat C_t = x^{\beta}, exactly. What one wants from RR is that C^t\hat C_t be an unbiased estimate of CtC_t, still a probability distribution, and accurate on the functionals of §5.1, with an error that does not grow as the recurrence goes deeper into the chain.

In the matrix form of §5.2, (4) is a randomised forward substitution: each row is solved from the rows already solved and then reduced, before any later row reads it. Write δt=C^t−Xt\delta_t = \hat C_t - X_t for the noise of the reduction at a record tt that is not a coinbase, and δt=0\delta_t = 0 for a coinbase and wherever no reduction happens; 𝐂^\hat{\mathbf{C}} for the matrix whose row tt is C^t\hat C_t, and 𝐍\mathbf{N} (for noise) for the matrix whose row tt is δt\delta_t. Row tt of Γ 𝐂^\Gamma\,\hat{\mathbf{C}} is XtX_t (00 for a coinbase), so

𝐂^=Γ 𝐂^+𝐄+𝐍,𝐂^−𝐂=(𝐈−Γ)−1 𝐍. \hat{\mathbf{C}} = \Gamma\,\hat{\mathbf{C}} + \mathbf{E} + \mathbf{N}, \qquad \hat{\mathbf{C}} - \mathbf{C} = (\mathbf{I} - \Gamma)^{-1}\,\mathbf{N} .

The error at every record is a fixed linear image of the noises injected on the way to it. Section 6.3 proves what that implies.

5.6 Why a linear combination of sketches is the crux

In sections 1–4 a merge is a union, S(A∪B)=bottom-k(S(A)∪S(B))S(A \cup B) = \text{bottom-}k(S(A) \cup S(B)), and it is exact because an item has the same weight in AA, in BB and in A∪BA \cup B. Here the operation is a linear combination: the child’s weight of block bb is ∑i=1nst,i cpi(b)\sum_{i=1}^{n} s_{t,i}\, c_{p_i}(b), a sum of weights that may each be present in one parent’s sketch and absent from another’s. And the parents overlap heavily. Counted over records 1.4–1.5M of the chain on the main binary’s exact --weighted merge (quoted from its documentation, src/weighted.rs, and the message of crate commit d8488bf; no log was kept), 97% of the terms a merge writes arrive in runs, the one-sided runs averaging 1,900 blocks and the shared runs 140: colours at depth are near-copies of a few common ancestors, not independent mixtures.

Three consequences shape everything below.

  1. A block’s weight in the child is assembled from several parents’ estimates. If a parent’s sketch does not hold the block, its share of that block is simply unknown; §6.6 shows that this alone breaks the exactness of a coordinated (same-hash) merge whose ranks depend on the weights. With ranks that depend on the block alone it does not: a block kept in the child’s sketch is kept in the sketch of every parent whose support contains it, and its weight is assembled exactly (§10.3).
  2. Each node re-estimates an estimate. For the errors not to compound, each reduction must be unbiased conditionally on its inputs (§6.2), and its randomness must be fresh: independent of the randomness that chose the inputs (§6.5).
  3. Overlap means the parents’ errors are correlated: they share ancestors. Any argument that needs independent parents fails here; the ones below use linearity and conditional expectations only.

5.7 What is known and what is new

The tools of sections 6 and 10 are known. What is new is the problem they are put to and a few results that come from putting them together. Here is the line between the two, so that the proofs below are read for what they are. “New” means that a search of the literature at review time found no earlier statement, not that none exists.

Known.

  • The solve. The recurrence is forward substitution with a unit lower triangular matrix (§5.2). That the solution of a sparse triangular system fills in along reachability in its graph is the observation behind sparse triangular solvers;John R. Gilbert and Tim Peierls. Sparse partial pivoting in time proportional to arithmetic operations. SIAM Journal on Scientific and Statistical Computing, 9(5):862–874, 1988. doi: 10.1137/0909058. URL https://doi.org/10.1137/0909058; and Timothy A. Davis. Direct Methods for Sparse Linear Systems. Fundamentals of Algorithms. Society for Industrial and Applied Mathematics, 2006. doi: 10.1137/1.9780898718881. URL https://doi.org/10.1137/1.9780898718881 that a linear projection commutes with the solve is linearity.
  • The reduction. VarOptk_k with its lights chosen systematically (Definition 1, Theorem 3) is a classical design of survey sampling (Madow, Chao). It is the VarOptk_k of Cohen et al. with one of their requirements traded for the block order. In particle filtering it is the optimal resampling of Fearnhead and Clifford. Its bound on every cut, point 5, is the interval property of systematic sampling that Cohen, Cormode and Duffield set beside structure-aware VarOpt.William G. Madow. On the Theory of Systematic Sampling, II. The Annals of Mathematical Statistics, 20(3):333–354, 1949. doi: 10.1214/aoms/1177729988. URL https://doi.org/10.1214/aoms/1177729988; M. T. Chao. A general purpose unequal probability sampling plan. Biometrika, 69(3):653–656, 1982. doi: 10.1093/biomet/69.3.653. URL https://doi.org/10.1093/biomet/69.3.653; Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Efficient Stream Sampling for Variance-Optimal Estimation of Subset Sums. SIAM Journal on Computing, 40(5):1402–1431, 2011b. doi: 10.1137/10079817X. URL https://doi.org/10.1137/10079817X; Paul Fearnhead and Peter Clifford. On-line inference for hidden Markov models via particle filters. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 65(4):887–899, 2003. doi: 10.1111/1467-9868.00421. URL https://doi.org/10.1111/1467-9868.00421; and Edith Cohen, Graham Cormode, and Nick Duffield. Structure-aware sampling: flexible and accurate summarization. Proceedings of the VLDB Endowment, 4(11):819–830, 2011a. doi: 10.14778/3402707.3402721. URL https://doi.org/10.14778/3402707.3402721 Corollary 4 is summation by parts.
  • Reducing afresh at every step. Replacing every iterate of a linear iteration by an unbiased sparse compression, drawn afresh at each step, is the fast randomised iteration (FRI) of Lim and Weare. One of its compressions, their rule (45), keeps the largest entries, selects the others by one systematic pass with a single uniform, and preserves the total exactly: it is the reduction of Definition 1, except that the lights are not laid out in block order. Greene et al. apply such compressions after every matrix product, and the randomly sparsified Richardson iteration of Weare and Webber does the same with pivotal sampling, which also preserves the total.Lek-Heng Lim and Jonathan Weare. Fast Randomized Iteration: Diffusion Monte Carlo through the Lens of Numerical Linear Algebra. SIAM Review, 59(3):547–587, 2017. doi: 10.1137/15M1040827. URL https://doi.org/10.1137/15M1040827; Samuel M. Greene, Robert J. Webber, Jonathan Weare, and Timothy C. Berkelbach. Beyond Walkers in Stochastic Quantum Chemistry: Reducing Error Using Fast Randomized Iteration. Journal of Chemical Theory and Computation, 15(9):4834–4850, 2019. doi: 10.1021/acs.jctc.9b00422. URL https://doi.org/10.1021/acs.jctc.9b00422; Samuel M. Greene, Robert J. Webber, Timothy C. Berkelbach, and Jonathan Weare. Approximating Matrix Eigenvalues by Subspace Iteration with Repeated Random Sparsification. SIAM Journal on Scientific Computing, 44(5):A3067–A3097, 2022. doi: 10.1137/21M1422513. URL https://doi.org/10.1137/21M1422513; and Jonathan Weare and Robert J. Webber. Randomly Sparsified Richardson Iteration: A Dimension-Independent Sparse Linear Solver, 2023. URL https://arxiv.org/abs/2309.17270. arXiv:2309.17270 What the post adds to them is the setting: a single pass of forward substitution over a DAG, in which every unknown is a probability distribution that is kept and reduced once.
  • Unbiasedness and the error decomposition. Theorem 7 is the tower property. Theorem 9 and Corollary 10 split the error into the noise of each reduction, as the error of a particle filter is split into the noise of its resampling steps.Pierre Del Moral. Feynman-Kac Formulae: Genealogical and Interacting Particle Systems with Applications. Probability and Its Applications. Springer, 2004. doi: 10.1007/978-1-4684-9393-1. URL https://doi.org/10.1007/978-1-4684-9393-1 The difference is that the Markov kernels are replaced by the fixed path coefficients α\alpha of the DAG.
  • Order against independence. In one dimension it is known that ordering the particles before a stratified or systematic resampling beats the Monte Carlo rate N−1/2N^{-1/2}.Mathieu Gerber and Nicolas Chopin. Sequential quasi Monte Carlo. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 77(3):509–579, 2015. doi: 10.1111/rssb.12104. URL https://doi.org/10.1111/rssb.12104; and Mathieu Gerber, Nicolas Chopin, and Nick Whiteley. Negative association, ordering and convergence of resampling methods. The Annals of Statistics, 47(4):2236–2260, 2019. doi: 10.1214/18-AOS1746. URL https://doi.org/10.1214/18-AOS1746 For a functional of bounded variation, Gerber, Chopin and Whiteley bound the error of ordered resampling by the variation times the Kolmogorov distance between the two distributions, which systematic resampling keeps of order 1/N1/N by a discrepancy bound of Niederreiter (their equations (5) and (6)); the one-step Corollary 4 is that argument with the heavy blocks kept. In one dimension the optimal-transport resampling of Li et al. is stratified resampling of the sorted particles.Harald Niederreiter. Random Number Generation and Quasi-Monte Carlo Methods, volume 63 of CBMS-NSF Regional Conference Series in Applied Mathematics. Society for Industrial and Applied Mathematics, 1992. doi: 10.1137/1.9781611970081. URL https://doi.org/10.1137/1.9781611970081; and Yichao Li, Wenshuo Wang, Ke Deng, and Jun S. Liu. Stratification and optimal resampling for sequential Monte Carlo. Biometrika, 109(1):181–194, 2022. doi: 10.1093/biomet/asab004. URL https://doi.org/10.1093/biomet/asab004 Proposition 13 is the textbook variance of Poisson sampling, and Proposition 15 is the unbiasedness of priority sampling passed through Theorem 7.
  • The support. Folding bottom-kk sketches exactly through a graph (Lemma 20, Lemma 21, Theorem 22) is Cohen’s size estimation for reachability sets.Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534 On Bitcoin, the mint centrality of Fiz Pontiveros, Steichen and State counts exactly, for each address, the distinct coinbases it can be traced back to, on a prefix of the chain: the support size, per address and without the sketch.Beltran Borja Fiz Pontiveros, Mathis Steichen, and Radu State. Mint Centrality: A Centrality Measure for the Bitcoin Transaction Graph. In 2019 IEEE International Conference on Blockchain and Cryptocurrency (ICBC). IEEE, May 2019. doi: 10.1109/BLOC.2019.8751401. URL https://doi.org/10.1109/BLOC.2019.8751401 The count estimator of Proposition 25 is the one of inverse sampling without replacement. The Jaccard estimate of Proposition 26 is Broder’s and Beyer et al.’s, and Jw=(1−TV)/(1+TV)J_w = (1 - \mathrm{TV})/(1 + \mathrm{TV}) (Lemma 27) is an identity. The Cauchy projection of Proposition 28 is Indyk’s, and it follows the recurrence because a linear sketch commutes with any linear map.

New.

  • The problem. The post sketches a linear recurrence of probability distributions over a DAG: the colour of every transaction of the chain, the haircut taint of every coinbase at once. It does so with the compression of FRI, applied once at every node of a one-pass forward substitution with fresh randomness and the lights in block order, and adds sketches of the support and of the L1 distance for the questions that reduction cannot answer (§10.2).
  • The rate through the recursion, Corollary 12. Through any DAG of convex mixtures, every functional of bounded variation has a root-mean-square error at most V(g)At/kV(g)\sqrt{A_t}/k at every node, with At≤1+dtA_t \le 1 + d_t. Independent inclusion gives only At/k\sqrt{A_t/k}. Lim and Weare state that their error bound does not carry over to their systematic rule, which they support by experiments only; with the lights in block order and for functionals of bounded variation along it, Corollary 12 is such a bound. Its one-step factor is known (above); what is new is its composition through the DAG. The result is modest, and its proof is elementary once the known pieces are in place. Two things it does not settle are measured instead. The error stays flat with depth (§8.3), an open question (§14). Priority sampling and VarOpt with lights in random order fall at about k−1/2k^{-1/2} at depth (§6.4, §8.4).
  • The universe of each count, §10.4. Every block of a support is at most βt\beta_t, and βt\beta_t depends on the chain and not on the permutation, so [0,βt][0, \beta_t] is a valid universe. That brings a finite-population factor. On the deepest supports of the first 31.2M records it halves the theoretical error of a count that stays exactly unbiased; measured over 16 seeds, the error falls to 57%. Mint centrality counts such supports exactly on a prefix; the sketch, with this universe, counts them for every record of the chain. The result is small but practical.
  • Three minor lemmas.
    • Lemma 23: ranks that depend on the block alone fold the colour weights of the kept blocks exactly.
    • Proposition 19: the harmonic cap of overlapping threshold samples.
    • Proposition 29: samplers with ranks Eb/xbE_b/x_b, P-MinHash among them, have no merge under sums.
  • The measurements.
    • On the 2022 chain, VarOpt in block order beats the literal bottom-kk sketch by 6 to 21 times at the same size.
    • Its error is flat in depth over 778M records.
    • Every result of a run can be recomputed from files on disk by the crate, or is labelled.

6. Proofs

Throughout this section a reduction acts on a vector of candidates v=(vb)b∈Bv = (v_b)_{b \in B} over a set B={b1<b2<⋯<bn}B = \{b_1 < b_2 < \dots < b_n\} of blocks, with every vb>0v_b > 0, total W=∑b∈BvbW = \sum_{b \in B} v_b and n>k≥1n > k \ge 1. In the recurrence W=1W = 1 (record mode, §6.2). Hats denote the reduced vector v^b\hat v_b, and for a block xx the cut at xx and its estimate are

F(x)=∑b∈Bb≤xvb,F^(x)=∑b∈Bb≤xv^b. F(x) = \sum_{\substack{b \in B \\ b \le x}} v_b, \qquad \hat F(x) = \sum_{\substack{b \in B \\ b \le x}} \hat v_b .

A word on notation, because some letters change meaning from sections 2–3. There τ\tau is a threshold on ranks u/wu/w, small ranks are kept, and a kept item is carried at max⁡(w,1/τ)\max(w, 1/\tau). In §6.1–6.5 τ\tau is a threshold on weights: an item is heavy when its weight exceeds τ\tau, and kept lights are carried at weight τ\tau, so this τ\tau plays the part of §2’s 1/τ1/\tau. §6.6 returns to §2’s rank convention for coord. Also, SjS_j below is a cumulative light mass, not a sketch; hh counts heavy items, not a hash; WW is a total mass and W1W_1 the Wasserstein distance; and the mixing shares are always ss (st,is_{t,i}, sas_a, sbs_b, or a bare ss, s′s'), except in Λs\Lambda_s and e−sb/Le^{-sb/L} in Corollary 4 and its proof, where ss is the Laplace parameter of §5.1.

6.1 VarOptk_k by systematic threshold sampling

Definition 1. Let τ>0\tau > 0 solve ∑b∈Bmin⁡(1,vb/τ)=k\sum_{b \in B} \min(1, v_b/\tau) = k. Call bb heavy if vb>τv_b > \tau and light otherwise; let HH be the heavy set, h=∣H∣h = \lvert H \rvert, and ℓ1<⋯<ℓm\ell_1 < \dots < \ell_m the lights in block order. Put S0=0S_0 = 0 and Sj=τ−1∑i=1jvℓiS_j = \tau^{-1} \sum_{i=1}^{j} v_{\ell_i} for j=1,…,mj = 1, \dots, m. Draw UU uniform on (0,1)(0, 1), and keep light ℓj\ell_j if and only if ⌊U+Sj⌋>⌊U+Sj−1⌋\lfloor U + S_j \rfloor > \lfloor U + S_{j-1} \rfloor. The output is

v^b={vbb∈H,τb light and kept,0otherwise. \hat v_b = \begin{cases} v_b & b \in H, \\ \tau & b \text{ light and kept}, \\ 0 & \text{otherwise.} \end{cases}

This is a VarOptk_k-type scheme (inclusion probabilities proportional to weight up to a threshold, and exactly kk points; ChaoM. T. Chao. A general purpose unequal probability sampling plan. Biometrika, 69(3):653–656, 1982. doi: 10.1093/biomet/69.3.653. URL https://doi.org/10.1093/biomet/69.3.653; Cohen, Duffield, Kaplan, Lund and ThorupEdith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Stream sampling for variance-optimal estimation of subset sums. In Proceedings of the Twentieth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA '09, pages 1255–1264. Society for Industrial and Applied Mathematics, 2009a. doi: 10.1137/1.9781611973068.136. URL https://doi.org/10.1137/1.9781611973068.136; and Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Efficient Stream Sampling for Variance-Optimal Estimation of Subset Sums. SIAM Journal on Computing, 40(5):1402–1431, 2011b. doi: 10.1137/10079817X. URL https://doi.org/10.1137/10079817X), with the lights chosen by one systematic pass along the block axis instead of a sequence of random evictions.One random start along the cumulated sizes is the classical systematic design of survey sampling with unequal probabilities, usually traced to Madow. Particle filters use it as systematic resampling.William G. Madow. On the Theory of Systematic Sampling, II. The Annals of Mathematical Statistics, 20(3):333–354, 1949. doi: 10.1214/aoms/1177729988. URL https://doi.org/10.1214/aoms/1177729988; Genshiro Kitagawa. Monte Carlo filter and smoother for non-Gaussian nonlinear state space models. Journal of Computational and Graphical Statistics, 5(1):1–25, 1996. doi: 10.1080/10618600.1996.10474692. URL https://doi.org/10.1080/10618600.1996.10474692; and James Carpenter, Peter Clifford, and Paul Fearnhead. Improved particle filter for nonlinear problems. IEE Proceedings – Radar, Sonar and Navigation, 146(1):2–7, 1999. doi: 10.1049/ip-rsn:19990255. URL https://doi.org/10.1049/ip-rsn:19990255 Fearnhead and Clifford’s optimal resampling for particle filters works the same way. It solves for the same threshold, keeps the heavies at their weight, resamples the lights at weight τ\tau by a stratified pass, and is optimal among unbiased resampling schemes for a squared-error loss.Paul Fearnhead and Peter Clifford. On-line inference for hidden Markov models via particle filters. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 65(4):887–899, 2003. doi: 10.1111/1467-9868.00421. URL https://doi.org/10.1111/1467-9868.00421 Systematic selection gives up one property that Cohen et al. include in their definition of VarOptk_k: no positive covariances between the estimates.Cohen, Cormode and Duffield make the trade explicit for ordered keys: systematic sampling keeps the number of sampled keys in every interval within less than one of its expectation but has positive correlations, while for a VarOpt sample in their sense no bound below two holds on every input.Edith Cohen, Graham Cormode, and Nick Duffield. Structure-aware sampling: flexible and accurate summarization. Proceedings of the VLDB Endowment, 4(11):819–830, 2011a. doi: 10.14778/3402707.3402721. URL https://doi.org/10.14778/3402707.3402721 With four equal lights at v/τ=12v/\tau = \tfrac12 and k=2k = 2, the kept set is either the first and third or the second and fourth, so the first and third have covariance τ2/4\tau^2/4, and their sum has variance τ2\tau^2 against τ2/2\tau^2/2 under independent inclusion. That matters for subset sums that are not intervals of the block axis; it does not matter for the cuts and the bounded-variation functionals read in this post, which Theorem 3(5) bounds directly. The accumulator of the code, which starts at UU, adds v/τv/\tau and keeps an item each time it crosses an integer, computes exactly this rule (§7.7).

Lemma 2. The threshold τ\tau exists and is unique. At most k−1k - 1 items are heavy, at least one is light, the lights hold exactly (k−h)τ(k - h)\tau of the mass, and τ≤W/k\tau \le W / k.

Proof. Let f(t)=∑b∈Bmin⁡(1,vb/t)f(t) = \sum_{b \in B} \min(1, v_b/t). It is continuous and nonincreasing, equal to n>kn > k for t≤min⁡bvbt \le \min_b v_b, strictly decreasing for t>min⁡bvbt > \min_b v_b (at least one term is vb/tv_b/t there), and tends to 00. So f(t)=kf(t) = k has exactly one solution, and it lies above min⁡bvb\min_b v_b. At t=τt = \tau, f(τ)=h+τ−1∑j=1mvℓj=kf(\tau) = h + \tau^{-1}\sum_{j=1}^{m} v_{\ell_j} = k. If h=kh = k the light sum would be 00, so there would be no lights and n=h=kn = h = k, a contradiction; hence h≤k−1h \le k - 1, a light exists, and ∑j=1mvℓj=(k−h)τ\sum_{j=1}^{m} v_{\ell_j} = (k - h)\tau. Finally f(W/k)≤∑b∈Bvbk/W=k<nf(W/k) \le \sum_{b \in B} v_b k / W = k < n, so W/k>min⁡bvbW/k > \min_b v_b lies where ff is strictly decreasing; if τ>W/k\tau > W/k we would have k=f(τ)<f(W/k)≤kk = f(\tau) < f(W/k) \le k. Hence τ≤W/k\tau \le W/k. ■

Theorem 3 (VarOpt by systematic sampling). Under Definition 1:

  1. exactly k−hk - h lights are kept, so the output has exactly kk points;

  2. block bb is kept with probability πb=min⁡(1,vb/τ)\pi_b = \min(1, v_b / \tau), and v^b=vb/πb\hat v_b = v_b / \pi_b when kept: every estimate is a Horvitz–Thompson weight, equal to vbv_b or to τ\tau;

  3. 𝔼[v^b]=vb\mathbb{E}[\hat v_b] = v_b for every bb;

  4. ∑b∈Bv^b=W\sum_{b \in B} \hat v_b = W for every value of UU: the mass is preserved exactly;

  5. for every cut xx,

    F^(x)−F(x)=τ (⌊U+Sj⌋−Sj), \hat F(x) - F(x) = \tau\,(\lfloor U + S_{j} \rfloor - S_{j}),

    where jj is the number of lights ≤x\le x; hence τ(U−1)<F^(x)−F(x)≤τU\tau(U - 1) < \hat F(x) - F(x) \le \tau U and ∣F^(x)−F(x)∣<τ\lvert \hat F(x) - F(x) \rvert < \tau, deterministically.

Proof of Theorem 3. (1) Each light adds v/τ≤1v/\tau \le 1 to SS, so ⌊U+Sj⌋\lfloor U + S_j \rfloor grows by 00 or 11 at each step, and the number of lights kept is ⌊U+Sm⌋−⌊U⌋\lfloor U + S_m \rfloor - \lfloor U \rfloor. By Lemma 2, Sm=k−hS_m = k - h is an integer, and 0<U<10 < U < 1, so this is k−hk - h.

(2) Heavies are always kept. Light ℓj\ell_j is kept if and only if the interval (U+Sj−1,U+Sj](U + S_{j-1}, U + S_j], of length vℓj/τ≤1v_{\ell_j}/\tau \le 1, contains an integer. With UU uniform, U+Sj−1U + S_{j-1} is uniform modulo 11, and an interval of length λ≤1\lambda \le 1 with a uniform left end modulo 1 contains an integer with probability λ\lambda. So πℓj=vℓj/τ\pi_{\ell_j} = v_{\ell_j}/\tau, and v/π=τv/\pi = \tau.

(3) For a heavy, v^b=vb\hat v_b = v_b. For a light, 𝔼[v^b]=τ⋅vb/τ=vb\mathbb{E}[\hat v_b] = \tau \cdot v_b / \tau = v_b.

(4) By (1) and Lemma 2,

∑b∈Bv^b=∑b∈Hvb+(k−h)τ=∑b∈Hvb+∑j=1mvℓj=W. \sum_{b \in B} \hat v_b = \sum_{b \in H} v_b + (k - h)\tau = \sum_{b \in H} v_b + \sum_{j=1}^{m} v_{\ell_j} = W .

(5) Heavies contribute the same amount to F(x)F(x) and F^(x)\hat F(x). The lights ≤x\le x are ℓ1,…,ℓj\ell_1, \dots, \ell_j, with true mass τSj\tau S_j and estimated mass τ\tau times the number kept,

τ (⌊U+Sj⌋−⌊U⌋)=τ⌊U+Sj⌋. \tau\,\big(\lfloor U + S_j\rfloor - \lfloor U \rfloor\big) = \tau \lfloor U + S_j \rfloor .

Since y−1<⌊y⌋≤yy - 1 < \lfloor y \rfloor \le y, the difference ⌊U+Sj⌋−Sj\lfloor U + S_j \rfloor - S_j lies in (U−1,U](U - 1, U], and 0<U<10 < U < 1 gives the strict bound. ■

Point 4 is why every sketched colour is still a probability distribution: the candidate of a record has mass one, and so has its reduction, for every draw. Point 5 is the property that matters for colours, which are read through their CDF.

Corollary 4. For any function gg of the block, with variation V(g)V(g) over BB,

∣∑b∈Bg(b) (v^b−vb)∣≤τ V(g),V(g)=∑j=1n−1∣g(bj+1)−g(bj)∣, \Big\lvert \sum_{b \in B} g(b)\,(\hat v_b - v_b) \Big\rvert \le \tau\, V(g), \qquad V(g) = \sum_{j=1}^{n-1} \lvert g(b_{j+1}) - g(b_j) \rvert,

with strict inequality when V(g)>0V(g) > 0. In particular, for one reduction of a colour (W=1W = 1): the KS distance is below τ\tau; the mean block moves by less than τ (bn−b1)<τL\tau\,(b_n - b_1) < \tau L; each Laplace value Λs\Lambda_s moves by less than τ\tau; and the Wasserstein distance W1W_1 is below τ (bn−b1)\tau\,(b_n - b_1).

Proof. Let dj=v^bj−vbjd_j = \hat v_{b_j} - v_{b_j} and Dj=∑i=1jdi=F^(bj)−F(bj)D_j = \sum_{i=1}^{j} d_i = \hat F(b_j) - F(b_j) for j=1,…,nj = 1, \dots, n, with D0=0D_0 = 0 and Dn=0D_n = 0 by point 4. Summing by parts,

∑j=1ng(bj) dj=g(bn)Dn−∑j=1n−1Dj (g(bj+1)−g(bj))=−∑j=1n−1Dj (g(bj+1)−g(bj)), \sum_{j=1}^{n} g(b_j)\, d_j = g(b_n) D_n - \sum_{j=1}^{n-1} D_j\, \big(g(b_{j+1}) - g(b_j)\big) = -\sum_{j=1}^{n-1} D_j\,\big(g(b_{j+1}) - g(b_j)\big),

whose absolute value is at most max⁡j∣Dj∣ V(g)≤τV(g)\max_j \lvert D_j \rvert\, V(g) \le \tau V(g), strictly when V(g)>0V(g) > 0 because max⁡j∣Dj∣<τ\max_j \lvert D_j \rvert < \tau. The mean is g(b)=bg(b) = b; e−sb/Le^{-sb/L} is monotone with values in (0,1](0, 1], so its variation is below 11; KS is max⁡j∣Dj∣\max_j \lvert D_j \rvert; and

W1=∑j=1n−1∣Dj∣ (bj+1−bj). W_1 = \sum_{j=1}^{n-1} \lvert D_j \rvert\,(b_{j+1} - b_j).

■

Remark 5. Point 5 also explains a number measured in section 8. For a diffuse colour, whose lights are all tiny against τ\tau, the fractional parts of the SjS_j run densely through [0,1)[0, 1), so the largest CDF error over all cuts is close to τmax⁡(U,1−U)\tau \max(U, 1 - U), whose expectation is 34τ\tfrac34 \tau. The single-shot KS distance of varopt measured on the exact colours was between 0.741τ0.741\tau and 0.750τ0.750\tau for k=16k = 16 to 40964096, a little lower at small kk (§8.8; the column ideal_ks_over_tau of sketch summarize’s floors_eval.tsv).

The code never sorts to find τ\tau; it iterates.

Lemma 6. Start from t0=W/kt_0 = W/k. Given tit_i, let hih_i count the items above tit_i, MiM_i be the sum of the others (computed directly, not as WW minus the heavies) and ti+1=Mi/(k−hi)t_{i+1} = M_i / (k - h_i). Then τ≤ti+1≤ti\tau \le t_{i+1} \le t_i for every ii; and if no item counted in MiM_i exceeds ti+1t_{i+1}, then ti+1=τt_{i+1} = \tau.

Proof. Lower bound. t0≥τt_0 \ge \tau by Lemma 2. Suppose ti≥τt_i \ge \tau. The items above tit_i are above τ\tau, so they contribute hih_i to f(τ)=kf(\tau) = k, and the rest contribute

k−hi=∑b∈Bvb≤timin⁡(1,vb/τ)≤Miτ, k - h_i = \sum_{\substack{b \in B \\ v_b \le t_i}} \min(1, v_b/\tau) \le \frac{M_i}{\tau},

so ti+1=Mi/(k−hi)≥τt_{i+1} = M_i/(k - h_i) \ge \tau. (Also hi≤h≤k−1h_i \le h \le k - 1, so the division is defined.)

Monotonicity. Each of the h0h_0 items above t0=W/kt_0 = W/k exceeds W/kW/k, so

M0=W−∑b∈Bvb>t0vb≤W−h0Wk=(k−h0) t0, M_0 = W - \sum_{\substack{b \in B \\ v_b > t_0}} v_b \le W - h_0 \frac{W}{k} = (k - h_0)\,t_0,

that is t1≤t0t_1 \le t_0. Suppose ti≤ti−1t_i \le t_{i-1}. The items above ti−1t_{i-1} are above tit_i, so hi≥hi−1h_i \ge h_{i-1}, and MiM_i is Mi−1M_{i-1} less the hi−hi−1h_i - h_{i-1} items in (ti,ti−1](t_i, t_{i-1}], each larger than tit_i. With Mi−1=(k−hi−1) tiM_{i-1} = (k - h_{i-1})\,t_i, the definition of tit_i, this gives

Mi≤(k−hi−1) ti−(hi−hi−1) ti=(k−hi) ti, M_i \le (k - h_{i-1})\,t_i - (h_i - h_{i-1})\,t_i = (k - h_i)\,t_i,

that is ti+1≤tit_{i+1} \le t_i.

Stopping. If every item counted in MiM_i is at most ti+1t_{i+1}, and the others exceed ti≥ti+1t_i \ge t_{i+1}, then f(ti+1)=hi+Mi/ti+1=kf(t_{i+1}) = h_i + M_i / t_{i+1} = k, and ti+1=τt_{i+1} = \tau by uniqueness.

Termination. Otherwise some item counted in MiM_i exceeds ti+1t_{i+1}; it is at most tit_i, so it is counted among the heavies at the next pass, and hi+1≥hi+1h_{i+1} \ge h_i + 1. Since hi≤h≤k−1h_i \le h \le k - 1, the stopping condition holds within h+1≤kh + 1 \le k passes (in exact arithmetic). ■

6.2 Unbiasedness through the DAG, with fresh randomness

Let ℱt\mathcal{F}_t be everything drawn up to and including record tt, in file order. The shares st,is_{t,i} are fixed numbers: they come from the amounts, not from any sketch.

Theorem 7 (unbiased recursion). Suppose each reduction RtR_t draws randomness UtU_t independent of ℱt−1\mathcal{F}_{t-1}, and is conditionally unbiased: 𝔼[Rt(X)∣X]=X\mathbb{E}[R_t(X) \mid X] = X coordinate by coordinate. Then 𝔼[C^t∣ℱt−1]=Xt\mathbb{E}[\hat C_t \mid \mathcal{F}_{t-1}] = X_t and 𝔼[C^t(b)]=Ct(b)\mathbb{E}[\hat C_t(b)] = C_t(b) for every record tt and block bb. If, in addition, every reduction preserves mass, every C^t\hat C_t has mass exactly one.

Proof of Theorem 7. XtX_t is a function of the parents’ sketches, which are ℱt−1\mathcal{F}_{t-1}-measurable because parents come earlier in the file. So

𝔼[C^t∣ℱt−1]=𝔼[Rt(Xt)∣ℱt−1]=Xt \mathbb{E}[\hat C_t \mid \mathcal{F}_{t-1}] = \mathbb{E}[R_t(X_t) \mid \mathcal{F}_{t-1}] = X_t

(and trivially so when no reduction happens). By induction in file order, assuming 𝔼[C^p]=Cp\mathbb{E}[\hat C_p] = C_p for every earlier pp,

𝔼[C^t]=𝔼[Xt]=∑i=1nst,i 𝔼[C^pi]=∑i=1nst,i Cpi=Ct. \mathbb{E}[\hat C_t] = \mathbb{E}[X_t] = \sum_{i=1}^{n} s_{t,i}\, \mathbb{E}[\hat C_{p_i}] = \sum_{i=1}^{n} s_{t,i}\, C_{p_i} = C_t .

The base case is a coinbase, C^t=Ct=xβ\hat C_t = C_t = x^{\beta}. Mass: the candidate has mass ∑i=1nst,i⋅1=1\sum_{i=1}^{n} s_{t,i} \cdot 1 = 1, and the reduction keeps it. ■

Nothing in the proof asks the parents to be independent. They are not: they share ancestors, and so they share the errors of those ancestors’ reductions. Linearity of expectation does not care. What the proof does need is that the reduction be unbiased given its input, which is why the randomness must be fresh: it must be independent of whatever chose the input. VarOpt satisfies this by Theorem 3(3) with UtU_t drawn per reduction. Two engineering details keep the proof intact: operands that are the same parent are added before reducing (s C+s′ C=(s+s′) Cs\,C + s'\,C = (s + s')\,C exactly), and zero-share operands are skipped, which changes nothing in XtX_t.

Remark 8. In code, UtU_t is a hash of the seed and the record index (§7.4), so a run is a deterministic function of its input. The theorem treats the hash values as independent uniforms; that is an idealisation of a good counter-based generator, and the seed-replicate tests of §8.5 are the check that it is harmless.

Record mode against the literal fold. run() folds a record’s inputs pairwise, from the last to the first. Applied literally to sketches (reduce=step), that is An=snC^pnA_n = s_n \hat C_{p_n} and Ai=Rt,i(siC^pi+Ai+1)A_i = R_{t,i}(s_i \hat C_{p_i} + A_{i+1}) for i=n−1,…,1i = n - 1, \dots, 1, with C^t=A1\hat C_t = A_1, a reduction after every combine, with a fresh Ut,iU_{t,i} each. The same tower argument shows it is unbiased too. The default (reduce=record) merges a record’s operands exactly and reduces once. Both compute the recurrence (1); they differ only in how often noise is injected. In step mode a record of nn inputs is reduced up to n−1n - 1 times, and the mass folded early is resampled again at every later step. §6.3 shows that every reduction adds a nonnegative term to the variance, so this is the expected direction, though not a proof that step mode must lose (its intermediate reductions have smaller thresholds, τt,i≤(si+⋯+sn)/k\tau_{t,i} \le (s_i + \dots + s_n)/k). Measured, it loses everywhere: 1.24–1.72 times the error of record mode at k=64k = 64, with 6.15 times as many reductions (§8.6; step.tsv and cost.tsv of sketch summarize).

6.3 How the error propagates

Let δr=C^r−Xr\delta_r = \hat C_r - X_r be the noise injected by the reduction at record rr (δr=0\delta_r = 0 when the record is not reduced, i.e. XrX_r has at most kk blocks; we then set τr=0\tau_r = 0, as the code does, so the sums over r⪯tr \preceq t below may run over all ancestors).

Theorem 9 (error decomposition). For every record tt,

C^t−Ct=∑r⪯tαt,r δr, \hat C_t - C_t = \sum_{r \preceq t} \alpha_{t,r}\, \delta_r,

where r⪯tr \preceq t ranges over tt and its ancestors, αt,t=1\alpha_{t,t} = 1, and αt,r=∑i=1nst,i αpi,r\alpha_{t,r} = \sum_{i=1}^{n} s_{t,i}\, \alpha_{p_i, r} for r≠tr \ne t (with αp,r=0\alpha_{p,r} = 0 when rr is not pp or an ancestor of pp): the sum, over all paths from rr to tt in the DAG, of the product of the shares along the path. The coefficients are deterministic and lie in [0,1][0, 1]; αt,r\alpha_{t,r} is the fraction of tt’s value that flowed through rr.

Proof of Theorem 9. For a coinbase both sides are 00. Otherwise

C^t−Ct=(Xt−Ct)+δt=∑i=1nst,i (C^pi−Cpi)+δt, \hat C_t - C_t = (X_t - C_t) + \delta_t = \sum_{i=1}^{n} s_{t,i}\,(\hat C_{p_i} - C_{p_i}) + \delta_t,

and the induction hypothesis on the parents turns this into

∑i=1nst,i∑r⪯piαpi,r δr+δt, \sum_{i=1}^{n} s_{t,i} \sum_{r \preceq p_i} \alpha_{p_i, r}\, \delta_r + \delta_t,

which is the claim with the stated recursion for α\alpha. The α\alpha are built from shares only, so they are deterministic, and αt,r≤∑i=1nst,i=1\alpha_{t,r} \le \sum_{i=1}^{n} s_{t,i} = 1 by induction. ■

Corollary 10. Let φ\varphi be any linear functional of a colour (a cut of the CDF, the mean, a Laplace value). The terms φ(δr)\varphi(\delta_r) are martingale differences in file order, hence orthogonalDavid Williams. Probability with Martingales. Cambridge University Press, 1991. doi: 10.1017/CBO9780511813658. URL https://doi.org/10.1017/CBO9780511813658, and

𝔼[φ(C^t−Ct)2]=∑r⪯tαt,r2  𝔼[φ(δr)2]. \mathbb{E}\big[\varphi(\hat C_t - C_t)^2\big] = \sum_{r \preceq t} \alpha_{t,r}^2\; \mathbb{E}\big[\varphi(\delta_r)^2\big].

Proof. φ(δr)\varphi(\delta_r) is ℱr\mathcal{F}_r-measurable and 𝔼[φ(δr)∣ℱr−1]=0\mathbb{E}[\varphi(\delta_r) \mid \mathcal{F}_{r-1}] = 0 by conditional unbiasedness. For r<r′r < r',

𝔼[φ(δr)φ(δr′)]=𝔼[φ(δr) 𝔼[φ(δr′)∣ℱr′−1]]=0. \mathbb{E}[\varphi(\delta_r)\varphi(\delta_{r'})] = \mathbb{E}\big[\varphi(\delta_r)\, \mathbb{E}[\varphi(\delta_{r'}) \mid \mathcal{F}_{r'-1}]\big] = 0 .

Expand the square; the α\alpha are constants. (Every term is bounded, by Corollary 4, so the expectations exist.) ■

The same split, of the error into the orthogonal noises of the resampling steps, is the standard analysis of particle filters.Pierre Del Moral. Feynman-Kac Formulae: Genealogical and Interacting Particle Systems with Applications. Probability and Its Applications. Springer, 2004. doi: 10.1007/978-1-4684-9393-1. URL https://doi.org/10.1007/978-1-4684-9393-1 There the noise is carried forward by Markov kernels; here it is carried by the fixed coefficients αt,r\alpha_{t,r} of the DAG.

As §5.2 noted, the coefficients are no new object: αt,r\alpha_{t,r} is entry (t,r)(t, r) of (𝐈−Γ)−1(\mathbf{I} - \Gamma)^{-1}, and Theorem 9 is, row by row, the identity of §5.5,

𝐂^−𝐂=(𝐈−Γ)−1 𝐍. \hat{\mathbf{C}} - \mathbf{C} = (\mathbf{I} - \Gamma)^{-1}\,\mathbf{N} .

The AtA_t of Corollary 12 below is the squared Euclidean norm of row tt of (𝐈−Γ)−1(\mathbf{I} - \Gamma)^{-1}.

Proposition 11. For VarOpt in record mode and a cut xx, let fr(x)f_r(x) be the fractional part of SjS_{j} at the cut in reduction rr. Conditionally on ℱr−1\mathcal{F}_{r-1}, the cut error δr(x)\delta_r(x) equals τr(1−fr)\tau_r(1 - f_r) with probability frf_r and −τrfr-\tau_r f_r with probability 1−fr1 - f_r. Hence

𝔼[(F^t(x)−Ft(x))2]=∑r⪯tαt,r2  𝔼[τr2 fr(x) (1−fr(x))]  ≤  14∑r⪯tαt,r2 𝔼[τr2]  ≤  14k2∑r⪯tαt,r2. \mathbb{E}\big[(\hat F_t(x) - F_t(x))^2\big] = \sum_{r \preceq t} \alpha_{t,r}^2\; \mathbb{E}\big[\tau_r^2\, f_r(x)\,(1 - f_r(x))\big] \;\le\; \frac14 \sum_{r \preceq t} \alpha_{t,r}^2\, \mathbb{E}[\tau_r^2] \;\le\; \frac{1}{4k^2} \sum_{r \preceq t} \alpha_{t,r}^2 .

Proof. Write Sj=N+fS_j = N + f with NN an integer. By Theorem 3(5) the error is τ(⌊U+f⌋−f)\tau(\lfloor U + f \rfloor - f), and ⌊U+f⌋=1\lfloor U + f \rfloor = 1 exactly when U≥1−fU \ge 1 - f, which has probability ff. Its conditional variance is τ2f(1−f)≤τ2/4\tau^2 f(1-f) \le \tau^2/4. Combine with Corollary 10. In record mode every candidate has mass 11, so τr≤1/k\tau_r \le 1/k by Lemma 2 when rr is reduced, and τr=0\tau_r = 0 otherwise. ■

The same argument gives the rate in kk through the whole recursion, for every functional of bounded variation.

Corollary 12 (the 1/k rate through the recursion). In record mode, let gg be a function of the block with variation V(g)V(g) over all the blocks 0,…,L−10, \dots, L - 1 in order, and φ(v)=∑b=0L−1g(b) vb\varphi(v) = \sum_{b=0}^{L-1} g(b)\, v_b. For every record tt,

𝔼[φ(C^t−Ct)2]  ≤  V(g) Atk,At=∑r⪯tαt,r2, \sqrt{\mathbb{E}\big[\varphi(\hat C_t - C_t)^2\big]} \;\le\; \frac{V(g)\,\sqrt{A_t}}{k}, \qquad A_t = \sum_{r \preceq t} \alpha_{t,r}^2,

where AtA_t depends on the DAG and the shares only, not on kk, and At≤1+dtA_t \le 1 + d_t, with dtd_t the number of edges of the longest path from a coinbase to tt.

Proof. The variation of gg over the blocks of one candidate, taken in order, is at most V(g)V(g) (the triangle inequality merges the steps it skips). So Corollary 4 and τr≤1/k\tau_r \le 1/k give ∣φ(δr)∣≤τrV(g)≤V(g)/k\lvert\varphi(\delta_r)\rvert \le \tau_r V(g) \le V(g)/k for every reduced record rr, and δr=0\delta_r = 0 for the others. Corollary 10 then gives

𝔼[φ(C^t−Ct)2]≤(V(g)k)2∑r⪯tαt,r2. \mathbb{E}\big[\varphi(\hat C_t - C_t)^2\big] \le \Big(\frac{V(g)}{k}\Big)^2 \sum_{r \preceq t} \alpha_{t,r}^2 .

The α\alpha come from the shares alone. For the bound on AtA_t: αt,r∈[0,1]\alpha_{t,r} \in [0, 1], so αt,r2≤αt,r\alpha_{t,r}^2 \le \alpha_{t,r}, and αt,r\alpha_{t,r} is the probability that a walk from tt, stepping to parent pip_i with probability st,is_{t,i} until it reaches a coinbase, visits rr (it visits rr at most once, the graph being acyclic). The sum of these probabilities is the expected number of records the walk visits, at most 1+dt1 + d_t. ■

What this does and does not bound. The decomposition is exact, and the per-reduction term is tight: one reduction alone has a cut error of order τ≤1/k\tau \le 1/k. Corollary 12 turns this into a proved O(1/k)O(1/k) bound at every record, for the mean, every Laplace value and every cut. What it does not give is a constant independent of depth, because AtA_t is the weak point. Along a chain of near-copies, each record mostly its parent plus a little new value and each reduced, αt,r\alpha_{t,r} stays close to 11 for many ancestors rr, and AtA_t grows linearly with the number of such reductions: the bound by itself only says that the error’s standard deviation is at most of order depth/k\sqrt{\text{depth}}/k. It does not explain why the error does not grow with depth. Yet that is what the chain shows: ∣Δmean∣/sd\lvert \Delta\text{mean} \rvert / \text{sd} is flat from 100M records to the end, at every kk from 16 to 1024 (§8.3). Two things in the decomposition make it plausible without proving it. Most records do not reduce at all (a record whose operands are one parent returns that parent’s sketch), so most ancestors contribute δr=0\delta_r = 0. And mixing spreads α\alpha: the αt,r\alpha_{t,r} over a generation of ancestors sum to at most one, so when value comes from many ancestors ∑r⪯tαt,r2\sum_{r \preceq t} \alpha_{t,r}^2 is much smaller than ∑r⪯tαt,r\sum_{r \preceq t} \alpha_{t,r}. The measured flatness says that, on this chain, the effective sum

∑r⪯tαt,r2 𝔼[τr2fr(x) (1−fr(x))] \sum_{r \preceq t} \alpha_{t,r}^2\, \mathbb{E}\big[\tau_r^2 f_r(x)\,(1 - f_r(x))\big]

stays bounded.

What the recursion costs can be read against a single reduction. A single-shot sketch of the exact colour (the “IDEAL” of §8.7) has one term in the sum. On the first 3M records, where exact colours are available, the recursive sketch’s mean ∣Δmean∣\lvert\Delta\text{mean}\rvert was 29% to 67% above the single shot’s, for k=16k = 16 to 40964096, in the stratum of colours with more than 32,768 blocks (the eval3m run of §8.7, read by sketch summarize into ideal.tsv: metric abs_dmean_L, stratum fix:>32768, column excess). If both errors had the same shape, those ratios would correspond to variance ratios of 1.292≈1.661.29^2 \approx 1.66 to 1.672≈2.791.67^2 \approx 2.79: the whole ancestry contributes between about two-thirds of a single-reduction term and two such terms (0.660.66 to 1.791.79) beyond the record’s own. That reading is an inference from the measurements, not a consequence of the proposition; it also assumes the record’s own term equals the single shot’s, whereas the record’s reduction uses the threshold of its candidate XtX_t, close to but not equal to that of the exact colour CtC_t.

6.4 Why the error falls as 1/k1/k, not 1/k1/\sqrt{k}

For VarOpt by systematic sampling, one reduction has a CDF error below τ\tau, and τ\tau is at most 1/k1/k (more precisely, τ=Wlight/(k−h)≤W/k\tau = W_{\text{light}}/(k - h) \le W/k): the error of every functional of Corollary 4 is O(1/k)O(1/k), deterministically, by Theorem 3(5).

Proposition 13. If instead each light bb is kept independently with probability vb/τv_b/\tau and weight τ\tau (Poisson sampling with Horvitz–Thompson weights), the cut error is unbiased with variance ∑i=1jvℓi(τ−vℓi)\sum_{i=1}^{j} v_{\ell_i}(\tau - v_{\ell_i}), where jj is the number of lights ≤x\le x. For a diffuse colour, whose lights are all small against τ≈W/k\tau \approx W/k, this is about τF(x)≈F(x)/k\tau F(x) \approx F(x)/k, so the error’s standard deviation is of order 1/k1/\sqrt{k}.

Proof. Each light contributes an independent term τBb−vb\tau B_b - v_b, with BbB_b Bernoulli(vb/τv_b/\tau): mean 00, variance τ2(vb/τ)(1−vb/τ)=vb(τ−vb)\tau^2 (v_b/\tau)(1 - v_b/\tau) = v_b(\tau - v_b). Sum over the lights up to xx. ■

Priority sampling (prio) is not Poisson sampling, but its Horvitz–Thompson weights have zero pairwise covariance (§3.5), and conditionally on the leave-one-out threshold TbT_b, the kk-th largest of the priorities vc/ucv_c/u_c of the other blocks c≠bc \ne b (§6.5’s convention; it is 1/τ−b1/\tau_{-b} of §3.1 with kk shifted by one, and it equals τq\tau_q whenever bb is kept), its raw weight max⁡(vb,Tb) 𝟏{vb/ub>Tb}\max(v_b, T_b)\,\mathbf{1}\{v_b/u_b > T_b\} has variance vb (Tb−vb)+v_b\,(T_b - v_b)^{+}. So, for one reduction with unnormalised weights,

Var⁡F^(x)=∑b∈Bb≤x𝔼[vb (Tb−vb)+]. \operatorname{Var}\hat F(x) = \sum_{\substack{b \in B \\ b \le x}} \mathbb{E}\big[v_b\, (T_b - v_b)^{+}\big].

With Tb≈W/kT_b \approx W/k this is the same F(x)/kF(x)/k order. That last step, the concentration of TbT_b, is argued and not proved here; the measured slope of prio’s errors against kk is −0.49-0.49 to −0.54-0.54 (§8.4; sketch summarize’s slopes.tsv, every metric but TV1024).

The two estimators differ in how the lights are spread. Systematic sampling takes exactly one light per interval of τ\tau of light mass along the block axis: a stratified sample whose strata are consecutive slices of the colour. Its errors cannot pile up along the axis; at every cut they are bounded by one stratum’s mass. Independent inclusion lets them pile up, as a random walk does. Sequential Monte Carlo knows this gain: ordering the particles before a stratified or systematic resampling beats the N−1/2N^{-1/2} rate.Mathieu Gerber and Nicolas Chopin. Sequential quasi Monte Carlo. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 77(3):509–579, 2015. doi: 10.1111/rssb.12104. URL https://doi.org/10.1111/rssb.12104; and Mathieu Gerber, Nicolas Chopin, and Nick Whiteley. Negative association, ordering and convergence of resampling methods. The Annals of Statistics, 47(4):2236–2260, 2019. doi: 10.1214/18-AOS1746. URL https://doi.org/10.1214/18-AOS1746 What Corollary 12 adds is that the gain composes through a DAG of mixtures.

Remark 14. What is proved for the recursion is the rate: Corollary 12 bounds the root-mean-square error of every bounded-variation functional by V(g)At/kV(g)\sqrt{A_t}/k, because each reduction’s error is at most τrV(g)\tau_r V(g), a per-reduction variance of order τr2\tau_r^2. Under independent inclusion the per-reduction variance is of order τr\tau_r (Proposition 13), and the same decomposition gives only At/k\sqrt{A_t/k}. What is not proved is uniformity in depth, since AtA_t can grow (§6.3). Measured: local log-log slopes of −0.93-0.93 to −0.97-0.97 for the recursive sketch’s ∣Δmean∣\lvert\Delta\text{mean}\rvert from k=16k = 16 to 10241024 over the whole chain (§8.2), and, for the single-shot IDEAL on exact colours, −1.17-1.17 for KS, −1.14-1.14 for W1W_1 and −1.12-1.12 for the largest Laplace error (§8.7), from slopes.tsv and ideal_slopes.tsv of sketch summarize.

That the difference comes from the systematic pass, and not from the thresholds, was checked in the design phase with a prototype (not the final binary and not a crate run, and on a prefix of the chain): a VarOpt with the same thresholds whose lights were chosen in random order rather than along the block axis, run through the real recursion. On the first 1.1M records its mean W1W_1 over colours wider than kk went from 1,883 to 70 blocks for k=16k = 16 to 10241024, against 898 to 5.3 for the block-ordered prototype, and on the colours wider than 1024 blocks its log-log slope was −0.88-0.88, like fresh priority sampling’s −0.84-0.84, against −1.32-1.32 for the block-ordered one. Streamed deeper, at 10M records its mean-block error was 4,457 and 3,182 blocks at k=64k = 64 and 128128, against 932 and 479; and in the 10–30M window its median ∣Δmean∣/sd\lvert\Delta\text{mean}\rvert/\text{sd} was 0.0740.074 and 0.0520.052, against 0.0160.016 and 0.00820.0082. Without the block order, VarOpt behaves like priority sampling: both share the same slope on the shallow 1.1M prefix (about k−0.85k^{-0.85}) and both settle to about 1/k1/\sqrt{k} at depth (4,457/3,182=1.404{,}457 / 3{,}182 = 1.40 and 0.074/0.052=1.420.074 / 0.052 = 1.42 across the doubling from k=64k = 64 to 128128).

6.5 Priority bottom-kk on the recursion

prio is the weighted bottom-kk sketch of §2 applied at every node: priorities qb=vb/ubq_b = v_b / u_b with fresh uniforms ubu_b for this reduction, the kk largest kept, τq\tau_q the (k+1)(k+1)-th largest priority, and each kept block carried at max⁡(vb,τq)\max(v_b, \tau_q). Priorities are written v/uv/u here, the reciprocals of §2’s ranks u/wu/w, so the kk largest priorities are the kk smallest ranks and τq\tau_q is §2’s 1/τ1/\tau. (Section 2 keeps k−1k - 1 items and uses the kk-th as the threshold; prio keeps kk and uses the (k+1)(k+1)-th. They are the same scheme with kk shifted by one.)

Proposition 15. The raw Horvitz–Thompson weights of prio, never renormalised inside the recursion, are unbiased at every node: 𝔼[C^t(b)]=Ct(b)\mathbb{E}[\hat C_t(b)] = C_t(b).

Proof. Conditionally on the candidate XX, the proof of §3.2 applies with the leave-one-out threshold computed from the fresh priorities of the other candidates, which are independent of ubu_b: 𝔼[v^b∣X]=vb\mathbb{E}[\hat v_b \mid X] = v_b. That is the hypothesis of Theorem 7, whose proof uses nothing else. ■

Two things are lost against VarOpt. The mass is no longer preserved: the raw total of a node is a random variable with mean one, and along the DAG it wanders as a martingale (from 0.66 to 1.48 between the 5th and 95th percentiles, in one simulation of the design phase). And what is emitted must be a distribution, so it is normalised, p^b=v^b/∑c∈Bv^c\hat p_b = \hat v_b / \sum_{c \in B} \hat v_c, which is a ratio estimator: consistent, with a bias that vanishes as kk grows (of order 1/k1/k at a single node; its size deep in the recursion, where the raw total wanders, was not analysed), but not unbiased. Example 16 is the one measurement of it.

Example 16. Parent A holds one heavy block of weight 0.50.5 and 100 light blocks; parent B holds 300 blocks of equal weight. Each is reduced by prio to k=8k = 8, and the child 0.5 A+0.5 B0.5\,A + 0.5\,B is reduced again. Over 200,000 replicates the normalised estimate of the heavy block averaged 𝔼[p^heavy]=0.2690\mathbb{E}[\hat p_{\text{heavy}}] = 0.2690 against the exact 0.250.25 (z=125z = 125), while the raw Horvitz–Thompson weight averaged 0.249980.24998 (z=−0.9z = -0.9). (Measured in a simulation during the design; the test suite therefore asserts unbiasedness of prio’s raw weights, not of its output.)

Fresh randomness is not optional either. The design phase also tried coordinated priority sampling with Horvitz–Thompson re-estimation, one ubu_b per block for the whole run, and it diverged: in one prototype the raw mass reached 10710^{7} to 102810^{28}, and in another its mean distance from 1, ∣mass−1∣\lvert\text{mass} - 1\rvert, was about 101010^{10}. The proof of §3.2 needs the rank rbr_b to be independent of the threshold and of the weight vbv_b it is applied to. With shared keys, the blocks present in a node’s input were themselves selected because their ubu_b was small, so ubu_b given the input is no longer uniform but biased small. The nominal inclusion probability min⁡(1,vb/τ)\min(1, v_b/\tau) then understates how likely the block is to be kept again, the Horvitz–Thompson weight vb/πv_b/\pi over-inflates it, and the inflation compounds multiplicatively along the DAG: a block with a small key is kept and inflated to the threshold, its small key gives it a high priority at the next node, so it is kept and inflated again. (This is the mechanism as we understand it; the divergence itself is what was measured.)

6.6 Coordinated bottom-kk: exact on disjoint supports, biased under overlap

Here τ\tau is again a threshold on ranks, as in §2, not the weight threshold of §6.1–6.5. coord keeps one key ub∈(0,1)u_b \in (0, 1) per block for the whole run, ranks a weight vv at ub/vu_b / v, and stores exact weights rather than estimates.One key per item, shared by many weight assignments over the same items (here, all the colours over the blocks), is the coordinated weighted sampling of Cohen, Kaplan and Sen.Edith Cohen, Haim Kaplan, and Subhabrata Sen. Coordinated weighted sampling for estimating aggregates over multiple weight assignments. Proceedings of the VLDB Endowment, 2(1):646–657, 2009b. doi: 10.14778/1687627.1687701. URL https://doi.org/10.14778/1687627.1687701 A threshold sample of a vector DD at τ\tau is Tτ(D)={(b,Db):ub/Db<τ}T_\tau(D) = \{(b, D_b) : u_b / D_b < \tau\}; a coord sketch of a colour is meant to be such a sample, with its τ\tau stored beside it.

Lemma 17 (disjoint supports). Let AA and BB have disjoint supports, with exact threshold samples SA=TτA(A)S_A = T_{\tau_A}(A) and SB=TτB(B)S_B = T_{\tau_B}(B), and let D=saA+sbBD = s_a A + s_b B with sa,sb>0s_a, s_b > 0. Put c=min⁡(τA/sa, τB/sb)c = \min(\tau_A/s_a,\ \tau_B/s_b). For every τ≤c\tau \le c, the threshold sample Tτ(D)T_\tau(D) is obtained from the scaled union

{(b,saAb):(b,Ab)∈SA}∪{(b,sbBb):(b,Bb)∈SB} \{(b, s_a A_b) : (b, A_b) \in S_A\} \cup \{(b, s_b B_b) : (b, B_b) \in S_B\}

by keeping the entries ranked below τ\tau. Hence the merge that keeps the candidates ranked below τ′=min⁡(c,r(k+1))\tau' = \min(c, r_{(k+1)}), with r(k+1)r_{(k+1)} the (k+1)(k+1)-th smallest candidate rank, returns Tτ′(D)T_{\tau'}(D) exactly, with at most kk entries; and when c>r(k+1)c > r_{(k+1)} it returns the bottom-kk sketch of DD itself.

Proof. For bb in the support of AA, Db=saAbD_b = s_a A_b because the supports are disjoint, so the rank of bb in DD is ub/(saAb)=(ub/Ab)/sau_b/(s_a A_b) = (u_b/A_b)/s_a. If it is below τ≤τA/sa\tau \le \tau_A / s_a, then ub/Ab<τAu_b / A_b < \tau_A and (b,Ab)∈SA(b, A_b) \in S_A; conversely an entry of SAS_A ranked below τ\tau after scaling is in Tτ(D)T_\tau(D), with the exact weight. The same holds for BB. So every block of DD ranked below cc is a candidate, with its true weight and its true rank. If r(k+1)<cr_{(k+1)} < c, every block of DD ranked at or below r(k+1)r_{(k+1)} is a candidate, so r(k+1)r_{(k+1)} is the (k+1)(k+1)-th smallest rank of DD and the output is DD’s bottom-kk sketch. Otherwise τ′=c\tau' = c and at most kk candidates rank below it. ■

This is test T5 of the code (§7.13), repeated through nested merges. Overlap breaks it, because a block held by one parent’s sketch and not by the other’s has only a lower bound on its weight: the missing parent’s share is unknown and is taken as zero (the “zero rule”).

The share is missing because coord’s rank ub/vu_b / v depends on the weight, and a block’s weight in a parent differs from its weight in the child: the block can rank below the merged sketch’s threshold in the child and outside a parent’s sketch, as b2b_2 does below. With ranks that depend on the block alone the share is never missing: a block kept by the child is kept by every parent whose support holds it (Lemma 21), and the weights of a coordinated merge are then exact (Lemma 23). What such a sketch gives up is the weighting itself: it is a uniform sample of the support, which serves the count and the Jaccard similarity of §10 and not the functionals of §5.1.

Example 18 (overlap). Two blocks b1,b2b_1, b_2 with keys u=(0.3,0.4)u = (0.3, 0.4); k=1k = 1; A=(0.9,0.1)A = (0.9, 0.1), B=(0.1,0.9)B = (0.1, 0.9), sa=sb=12s_a = s_b = \tfrac12, so D=(0.5,0.5)D = (0.5, 0.5). In AA the ranks are (0.333,4)(0.333, 4): SA={(b1,0.9)}S_A = \{(b_1, 0.9)\}, τA=4\tau_A = 4. In BB they are (3,0.444)(3, 0.444): SB={(b2,0.9)}S_B = \{(b_2, 0.9)\}, τB=3\tau_B = 3. The merge sees b1b_1 at 0.450.45 and b2b_2 at 0.450.45 (each from one parent only), with ranks 0.6670.667 and 0.8890.889; c=min⁡(8,6)=6c = \min(8, 6) = 6, so τ′=0.889\tau' = 0.889 and the sketch is {(b1,0.45)}\{(b_1, 0.45)\} at τ′=0.889\tau' = 0.889. The truth: in DD the ranks are (0.6,0.8)(0.6, 0.8), so T0.889(D)={(b1,0.5),(b2,0.5)}T_{0.889}(D) = \{(b_1, 0.5), (b_2, 0.5)\} and the bottom-1 sketch of DD is {(b1,0.5)}\{(b_1, 0.5)\} at τ=0.8\tau = 0.8. The merged sketch matches neither: its weight is a strict lower bound, and its threshold vouches for every block below 0.8890.889 while b2b_2, at true rank 0.80.8, is missing.

Proposition 19 (the harmonic cap). Let SAS_A and SBS_B be exact threshold samples of AA and BB, as in Lemma 17, but without disjointness. A block absent from both sketches has true rank in DD at least cH=1/(sa/τA+sb/τB)c_H = 1 / (s_a/\tau_A + s_b/\tau_B), and cH≤cc_H \le c.

Proof. A block absent from SAS_A has Ab=0A_b = 0 or ub/Ab≥τAu_b/A_b \ge \tau_A, so Ab≤ub/τAA_b \le u_b/\tau_A either way; likewise Bb≤ub/τBB_b \le u_b/\tau_B. Then Db≤ub(sa/τA+sb/τB)D_b \le u_b (s_a/\tau_A + s_b/\tau_B), that is ub/Db≥cHu_b/D_b \ge c_H. And

1cH=saτA+sbτB≥max⁡(saτA,sbτB)=1c. \frac{1}{c_H} = \frac{s_a}{\tau_A} + \frac{s_b}{\tau_B} \ge \max\Big(\frac{s_a}{\tau_A}, \frac{s_b}{\tau_B}\Big) = \frac{1}{c}.

■

So, when the operands are exact threshold samples, the harmonic cap (cap=harm) is safe for the membership of blocks that no operand holds: none of them ranks below it. That is all it guarantees. It does not repair the weights of blocks that one operand holds and another misses, so the output need not be a threshold sample of DD even below the cap: in Example 18 it does not bind (cH=3.43>0.889c_H = 3.43 > 0.889), and b2b_2 is lost because its weight was underestimated, not because it was unseen. Nor does the hypothesis survive the recursion: after the first overlapping merge the operands carry holes and lower-bound weights, and the guarantee no longer applies. Its price is that sketches shrink, though not because the cap decays. cH≤cc_H \le c, by a factor of two when the operands are alike (sa=sb=12s_a = s_b = \tfrac12 and τA=τB=τ\tau_A = \tau_B = \tau give c=2τc = 2\tau and cH=τc_H = \tau); but the shares sum to one, so cHc_H is at least the share-weighted harmonic mean of the operands’ thresholds and never falls below the smallest of them. The shrinkage comes from the candidates whose weights are lower bounds: their ranks are inflated, sit above the tighter cap and are dropped (in the design-phase prototype the sketches fell to 45–55% of kk by 100M records). Measured on the first 3M records at k=64k = 64 it changed nothing (KS 0.06320.0632 against 0.06310.0631 for cap=min on colours above 32,768 blocks, with 2.3% fewer peak entries: the column measured of sketch summarize’s ideal.tsv and peak_entries of eval’s cost.tsv, both of eval3m), so the default stayed cap=min. Neither cap removes the bias of the zero rule, which is why coord lost: its error is almost all bias (§8.4) and does not fall with kk.

7. Implementation

The code below is excerpted from the sketch binary of coloring-bt-transactions-rs, trimmed (// … marks a cut) but not rewritten. It is about 6,500 lines with its tests (about 12,700 with the stores of section 10, and about 23,000 at commit adfe031 with the modes that read the runs’ outputs back, §7.10), adds no dependency, and reuses the repository’s record parser, release oracle, exact weighted store and Laplace tables through #[path] modules. Two subsections are about the repository’s main binary, coloring-bt-transactions, whose exact store, record parser and release oracle sketch reuses: §7.3, the allocator both binaries declare, and §7.12, the share matrix Γ\Gamma of §5.2, which the main binary writes once and reads back.

7.1 Where things are

filewhat it holds
sketch.rscommand line, global allocator, dispatch to the modes
hash.rsevery random draw, as a hash of where it is drawn; the permutation of the blocks and the Cauchy draws of §10
algebra.rsthe sketch type, the Algebra trait, operand grouping, the n-way merge
varopt.rs, prio.rs, coord.rsthe three reductions
driver.rsthe recurrence, driven exactly as run() drives it
exact.rsthe exact colour as an Algebra, bit-identical to --weighted, with its sets and pos supports
feed.rsone parse broadcast to many stores; reference files read in lock-step
metrics.rsmean, spread, Laplace, KS, W1W_1, TV over 1024 bands; tt and χ2\chi^2 quantiles
eval.rs, chain.rs, modes.rsthe modes eval, chain, check, emit, decode
encode.rsthe binary output format
kmv.rsthe coordinated bottom-kk of the support: store, capped merges, estimators, count stream
l1.rsthe Cauchy projection of the colour: store, scale MLE, weighted Jaccard
count.rs, pick.rs, pairs.rsthe modes count, pick, pairs
summarize.rs, summary.rs, select.rs, pairstats.rs, describe.rsthe modes that read other runs’ outputs: summarize, summary, select, pairs-stats, describe
surface.rs, surface_report.rsthe colour surface of section 12 and its report
tests.rstests through the whole pipeline

7.2 A sketch in memory

A sketch is a boxed slice of 8-byte entries in strictly ascending block order, behind an Rc:

/// One term of a sketch: 8 bytes.
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Entry {
    pub b: u32,
    pub w: f32,
}

/// A sketched colour.
#[derive(Debug)]
pub struct Sketch {
    /// Strictly ascending `b`; every `w` positive, finite and normal.
    pub entries: Box<[Entry]>,
    /// varopt: the light weight of this node's own reduction, or 0.  prio: its
    /// `tau_q`, or 0.  coord: the threshold in this sketch's own scale, `+INF`
    /// when exact.
    pub tau: f64,
    /// A reduction happened here or in an ancestor that had a say.  `false`
    /// means the sketch *is* the exact colour, up to f32 storage.
    pub reduced: bool,
}

pub type Handle = Rc<Sketch>;

Weights are f32 in a sketch (relative error 6×10−86 \times 10^{-8} per store, far below anything a kk-point estimate resolves) and f64 inside a merge or a reduction. A weight that rounds to zero or to a subnormal is dropped, and every sketch is allocated at its exact length. On top of the entries an Rc box costs 48 bytes. At k=256k = 256 a full sketch is 2,048 bytes of entries, exactly a jemalloc size class, so only the rare k+1k + 1 output rounds up. The Rc matters more than the layout: most transactions spend one parent, or one parent several times, and their colour is the parent’s, so the record answers the parent’s Rc and costs a reference-count bump.

7.3 The allocator is not a detail

This subsection is about the main binary, whose exact store sketch reuses. At depth the exact fold is not merge-bound but malloc-bound. Its allocation pattern, hundreds of thousands of live blocks of 50 KB to 1 MB freed and reallocated at every merge, is the one glibc’s allocator handles worst: measured over records 1.4M to 1.5M, a malloc costs 26 µs against 47 ns at the head of the chain, a quarter of the fold’s time (a measurement of the main binary, recorded in its Cargo.toml and src/main.rs).

Two changes fix it, and they only work together. One is jemalloc as the global allocator, behind the default feature (--no-default-features gives glibc back). The other is a merge that writes into a fresh, uninitialised allocation at its upper bound and then shrinks it to the length the merge turned out to have, instead of zero-filling a staging buffer and copying out (WeightedSets::intern in src/weighted.rs). The shrink is a downward realloc, which jemalloc does in place and to size, and glibc does not.

Table 3: The main binary on the first 1.5M records of the 2022 chain, coloring-bt-transactions 1500000 --weighted --sum < finalBCUTXO_2022.scm, before and after the two changes: wall time and resident set, a benchmark quoted from the message of the crate commit that made them, d8488bf (no log kept).
1,500,000 records, --weighted --sumtimeresident
glibc + staged merge257.71 s30.61 GiB
jemalloc + in-place merge148.47 s30.48 GiB

The pair is 1.74 times faster, with 0.4% less memory, and its output is md5-identical to the previous build’s (checked over 30,000 records in seven modes). At 800,000 records the same pair is 60.28 s and 9.15 GiB against 38.39 s and 9.59 GiB: 1.57 times faster, but 4.8% more resident, so the memory saving is a property of depth rather than of the change. Depth is where the wall of §5.3 is.--features mimalloc builds the other candidate, kept because it was measured: as fast, but 15% to 24% more resident on the same prefix (Cargo.toml). Setting _RJEM_MALLOC_CONF=thp:always puts jemalloc’s extents on transparent huge pages; it cut the page faults at 1.5M records by 92%, but the system time did not fall and the resident set grew 4% (the comment beside the allocator in src/main.rs).

A global allocator belongs to the binary that declares it, so sketch declares the same one, as its documentation says, “without this line the binary would silently run on the system allocator whatever the features say”:

// src/main.rs and src/bin/sketch.rs, the same three lines
#[cfg(feature = "jemalloc")]
#[global_allocator]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;

sketch --stats prints the allocator it runs on, and the first line of the production run’s emit.err (§9) is sketch emit: allocator jemalloc. The exact store of sketch eval is src/weighted.rs through #[path], so it gets the in-place merge too, and a full k=256k = 256 sketch is 2,048 bytes, a jemalloc size class (§7.2). sketch itself was not timed under glibc.

7.4 Randomness

Every draw is a hash of its coordinates, so a run is a deterministic function of its input (the same seed over the same records writes the same bytes, which is what lets check reproduce a chain run from a stored file), and the draws are exactly as independent as each variant needsThe mixer is the output function of SplitMix64, which Vigna’s public-domain splitmix.c presents as a fixed-increment version of Java 8’s SplittableRandom, the generator of Steele, Lea and Flood.Guy L. Steele, Doug Lea, and Christine H. Flood. Fast splittable pseudorandom number generators. In Proceedings of the 2014 ACM International Conference on Object Oriented Programming Systems Languages & Applications, pages 453–472. Association for Computing Machinery, 2014. doi: 10.1145/2660193.2660195. URL https://doi.org/10.1145/2660193.2660195:

/// Vigna's SplitMix64 output function.  `splitmix64(0) == 0xE220A8397B1DCDAF`.
#[inline]
pub fn splitmix64(x: u64) -> u64 {
    let mut z = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// A hash as a uniform draw strictly inside `(0, 1)`.
#[inline]
pub fn unit(h: u64) -> f64 {
    ((h >> 12) as f64 + 0.5) * (1.0 / (1u64 << 52) as f64)
}

/// The hash of the coordinates `(seed, salt, x, y)`.
#[inline]
pub fn h3(seed: u64, salt: u64, x: u64, y: u64) -> u64 {
    splitmix64(splitmix64(splitmix64(seed ^ salt) ^ x) ^ y)
}

/// `(rec << 20) | j`, the coordinate of one reduction.
#[inline]
pub fn coordinate(rec: u64, j: u64) -> u64 {
    assert!(j <= IDEAL_STEP, "step {} does not fit in the 20 bits kept for it", j);
    (rec << 20) | j
}

/// `varopt`'s systematic offset for the reduction at `x`.
#[inline]
pub fn varopt_offset(seed: u64, x: u64) -> f64 {
    unit(h3(seed, SALT_VAROPT, x, 0))
}

/// `prio`'s priority draw for block `b` in the reduction at `x`.
#[inline]
pub fn prio_draw(seed: u64, x: u64, b: u32) -> f64 {
    unit(h3(seed, SALT_PRIO, x, b as u64))
}

/// `coord`'s coordinated key for block `b`: the same in every sketch of a run.
#[inline]
pub fn coord_key(seed: u64, b: u32) -> f64 {
    unit(h3(seed, SALT_COORD, 0, b as u64))
}
  • Fresh per reduction for varopt and prio: the coordinate holds the record index and the step jj inside the record (j=0j = 0 in record mode, the 1-based fold step in step mode), so no two reductions of a run share a draw. That is the hypothesis of Theorem 7. The largest step value, IDEAL_STEP =220−1= 2^{20} - 1, is reserved for eval’s single-shot reduction, so an IDEAL draw is never one the recursion also made.
  • Coordinated for coord: the key depends on the block only. It is tabulated once per seed for the chain’s 762,261 blocks and a few past them; a block past the table is hashed on the spot, to the same value.
  • Strictly inside (0,1)(0, 1). The top 52 bits plus a half, over 2522^{52}, so the extremes are 2−532^{-53} and 1−2−531 - 2^{-53}, both exact. The obvious 53-bit form ((h >> 11) + 0.5) / 2^53 is wrong: 253−0.52^{53} - 0.5 is not an f64 and rounds to 2532^{53}, which makes the largest draw exactly 11. Theorem 3(5) needs 0<U<10 < U < 1, and prio divides by its draw.
  • Salts keep the three variants’ streams apart at equal seeds.

7.5 The driver

driver.rs copies the loop of src/main.rs’s run() rather than sharing it (that loop is welded to the exact store), and keeps everything that decides which colour is combined with what identical to it: the fold order (inputs from the last to the first, foldr), the shares (the total summed in input order as an f64, equal shares when it is zero), when a colour dies, and the BIP-30 duplicate transaction ids (an insert displaces the older colour, which is released).

let total: f64 = inputs.iter().map(|i| i.amount as f64).sum();
let n = inputs.len() as f64;
let share = |i: &Input| if total > 0.0 { i.amount as f64 / total } else { 1.0 / n };
if let Some(o) = &self.oracle {
    o.last_reads(rec, inputs, &mut self.last_reads);
}
debug_assert!(self.ops.is_empty());
for i in (0..inputs.len()).rev() {
    let prev = inputs[i].prev_tx_id;
    let entry = match self.colors.get_mut(&prev) {
        // …
    };
    let taken = match &self.oracle {
        Some(_) => self.last_reads[i],
        None => entry.1 <= 1,
    };
    let s = share(&inputs[i]);
    if !taken {
        entry.1 = entry.1.saturating_sub(1);
        let h = clone_handle(&entry.0);
        self.ops.push((h, s));
    } else {
        let (h, _) = self.colors.remove(&prev).expect("just looked it up");
        self.ops.push((h, s));
    }
}
let c = self.alg.record(&self.ops, rec);

With the release oracle an input moves its parent’s colour out of the map when it is that colour’s last reader, so the colour is freed as soon as the record that consumed it is done; without it the unspent-output counts decide, as in run(). The map is keyed by transaction id with a multiplicative hash: SipHash’s resistance to chosen keys buys nothing over a file of sequential integers.

7.6 One record: grouping, the n-way merge, one reduction

fn record_mode(&mut self, ops: &[(Handle, f64)], rec: u64) -> Handle {
    self.group(ops);
    assert!(!self.groups.is_empty(), "record {} has no operand with a positive share", rec);
    if self.groups.len() == 1 {
        // sum s_i = 1: the parent's colour is the colour.
        return Rc::clone(&ops[self.groups[0].0].0);
    }
    self.merge_groups(ops);
    let reduced_in = self.groups.iter().any(|&(i, _)| ops[i].0.reduced);
    // … (coord's per-operand caps)
    let out = self.finish(reduced_in, &caps, rec, 0);
    // …
}

group adds the shares of operands that are the same Rc and skips zero shares. Skipping them is not cosmetic: the chain has tens of thousands of zero-value inputs inside records of positive total, and a zero-share parent merged anyway adds up to kk zero-weight candidates. That pushes nn past kk when the real support is smaller, forcing a reduction of an exact colour, and in the textbook VarOpt loop it made the threshold negative.

The candidates are formed by a balanced tree of two-pointer merges, ⌈log⁡2G⌉\lceil \log_2 G \rceil levels for GG groups, in O(Nlog⁡G)O(N \log G):

/// `sa . a + sb . b` over ascending entries, into `out` (appended), zeros
/// dropped.
pub fn merge_two(a: &[Entry], sa: f64, b: &[Entry], sb: f64, out: &mut Vec<(u32, f64)>) {
    out.reserve(a.len() + b.len());
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        let (x, y) = (a[i], b[j]);
        let (bk, v) = if x.b < y.b {
            i += 1;
            (x.b, sa * x.w as f64)
        } else if y.b < x.b {
            j += 1;
            (y.b, sb * y.w as f64)
        } else {
            i += 1;
            j += 1;
            (x.b, sa * x.w as f64 + sb * y.w as f64)
        };
        if v > 0.0 {
            out.push((bk, v));
        }
    }
    // … (the two tails)
}

A heap-based kk-way merge has the same bound and was much slower in a benchmark (not a mode of the crate): over the first 6M records at k=256k = 256 it cost 21 ns a candidate for 3–8 groups and 50 ns above that, against 4.5 ns for a two-pointer pass, because a heap’s sift is a chain of unpredictable branches and the pass is one predictable compare. The tree fixes the summation order, so the result is deterministic. Its scratch vectors are pooled between records and trimmed to 32 MB after a consolidation of thousands of parents.

finish then stores the candidates as they are if there are at most kk of them (they are the exact mixture of the parents’ sketches), and otherwise reduces once:

Variant::VarOpt => {
    if n <= k {
        return Sketch::stored(&self.cand, 0.0, reduced_in);
    }
    let u = hash::varopt_offset(self.cfg.seed, hash::coordinate(rec, j));
    let o = varopt::reduce(&self.cand, k, u, &mut self.vo, &mut self.out);
    self.work.reductions += 1;
    if o.off_by_one(k) {
        self.work.off_by_one += 1;
    }
    Sketch::stored(&self.out, o.tau, true)
}

reduce=step is the same machinery, folding pairwise with merge_two(&h.entries, *s, &acc.entries, 1.0, …) and calling finish after every combine with step index jj.

7.7 The VarOpt reduction

The threshold comes from Lemma 6: a few linear passes, each summing the lights directly.

pub fn threshold(cand: &[(u32, f64)], k: usize, scratch: &mut Scratch) -> f64 {
    let w: f64 = cand.iter().map(|c| c.1).sum();
    let mut thr = w / k as f64;
    for _ in 0..MAX_PASSES {
        let (mut heavy, mut light, mut max_light) = (0usize, 0.0f64, 0.0f64);
        for &(_, v) in cand {
            if v > thr {
                heavy += 1;
            } else {
                light += v;
                max_light = max_light.max(v);
            }
        }
        if heavy >= k {
            break; // only rounding can get here; the sort decides
        }
        let next = light / (k - heavy) as f64;
        if max_light <= next {
            return next.max(max_light);
        }
        thr = next;
    }
    threshold_sorted(cand, k, scratch)
}

The textbook loop starts from WW and subtracts each heavy. On this chain that is wrong in a way that matters: a merge can have a few items holding nearly all the mass and a tail of thousands of tiny ones, and WW minus the heavies is then the cancellation residue of two nearly equal numbers. It came out negative in half of the trials of a simulation run during the design, which made every candidate heavy. One to three passes is the rule, and by Lemma 6 the loop never needs more than h+1≤kh + 1 \le k passes. Geometrically decaying weights (ratio rr), the shape near-copy chains make, are the slow case. Pass ii lowers the threshold by a factor of about (1−r)(k−hi)(1 - r)(k - h_i), which starts near k(1−r)k(1 - r) and falls towards 1 as hih_i nears k−1/(1−r)k - 1/(1 - r), and each pass adds only about log⁡1/r((1−r)(k−hi))\log_{1/r}\big((1 - r)(k - h_i)\big) heavies. With k=64k = 64, r=0.5r = 0.5 that is 16 passes; with k=1024k = 1024, r=0.9r = 0.9 it is 32. After MAX_PASSES =24= 24 the code falls back to threshold_sorted, which partially sorts the top kk (only they can be heavy, since h≤k−1h \le k - 1) and builds the tail sums from the small end, again without differences. The result is clamped to at least the largest light weight, which only rounding can violate and which keeps every v/τ≤1v/\tau \le 1.

The sample itself is one pass:

let (mut heavies, mut lights) = (0, 0);
// The accumulator is kept in [0, 1): subtracting the crossing rather than
// comparing floors keeps its absolute precision at the scale of one item,
// however many items the pass walks.
let mut acc = u;
// A multiply rather than a divide per item; v * (1/tau) and v / tau differ
// by at most an ulp, which moves an inclusion probability by 1e-16.
let inv = 1.0 / tau;
for &(b, v) in cand {
    if v > tau {
        out.push((b, v));
        heavies += 1;
        continue;
    }
    acc += v * inv;
    if acc >= 1.0 {
        out.push((b, tau));
        lights += 1;
        acc -= 1.0;
    }
}

In exact arithmetic it keeps exactly kk points (Theorem 3(1)); in floating point the last crossing can land on either side of an integer, giving k±1k \pm 1. The output is never trimmed back to kk, because trimming would bias it; such events are only counted (k+-1 in --stats), and the code asserts at most k+1k + 1 points. Over the whole chain at k=512k = 512 and 10241024 the count was zero (the column off_by_one of pass B’s cost.tsv, and k+-1 0 in the production run’s --stats).

7.8 prio and coord

prio keeps the kk largest priorities v/uv/u and carries each kept block at max⁡(v,τq)\max(v, \tau_q):

// …
q.extend(
    cand.iter()
        .enumerate()
        .map(|(i, &(b, v))| (v / prio_draw(seed, x, b), i as u32)),
);
// Descending by priority: the k largest land in q[..k], the (k+1)-th at k.
q.select_nth_unstable_by(k, |a, b| b.0.total_cmp(&a.0));
let tau = q[k].0;
// …
for &i in keep.iter() {
    let (b, v) = cand[i as usize];
    out.push((b, v.max(tau)));
}

prio’s weights stay raw Horvitz–Thompson inside the recursion (Proposition 15) and are normalised only when emitted. coord merges by Lemma 17: each operand’s (rank) threshold, rescaled to the merged colour, caps the new one.

pub fn cap_of(groups: impl Iterator<Item = (f64, f64)>, mode: Cap) -> f64 {
    match mode {
        Cap::Min => groups
            .filter(|g| g.1.is_finite())
            .map(|(s, tau)| tau / s)
            .fold(f64::INFINITY, f64::min),
        Cap::Harm => {
            let inv: f64 = groups.filter(|g| g.1.is_finite()).map(|(s, tau)| s / tau).sum();
            if inv > 0.0 {
                1.0 / inv
            } else {
                f64::INFINITY
            }
        }
    }
}

Unlike the other two, coord runs its reduction on every record with several operands, not only when there are more than kk candidates: a cap inherited from reduced operands can drop candidates even when there are fewer than kk, and the result then carries a finite threshold. Its reduction keeps the candidates ranked strictly below min⁡(cap,r(k+1))\min(\text{cap}, r_{(k+1)}) (with r(k+1)=∞r_{(k+1)} = \infty when there are at most kk candidates), and its estimate lifts each kept weight to max⁡(vb,1/τ)\max(v_b, 1/\tau) before normalising, which is mandatory there because the zero rule leaves the raw total below one. Every variant emits the same way:

fn emit(&self, c: &Handle, out: &mut Vec<(u32, f64)>) {
    out.clear();
    let finite_coord = self.cfg.variant == Variant::Coord && c.tau.is_finite();
    let lift = if finite_coord { 1.0 / c.tau } else { 0.0 };
    let mut total = 0.0;
    for e in c.entries.iter() {
        let w = (e.w as f64).max(lift);
        total += w;
        out.push((e.b, w));
    }
    if total > 0.0 {
        for x in out.iter_mut() {
            x.1 /= total;
        }
    }
}

For varopt the normalisation is the identity up to f32 rounding whenever the reduction keeps kk points (Theorem 3(1), (4)); on the synthetic DAG of §7.13 (where no k±1k \pm 1 event occurs) mass_raw stays within 10−510^{-5} of 11. In a k±1k \pm 1 event (§7.7) one light more or one fewer is kept at weight τ\tau, the raw mass is W±τW \pm \tau, and emit genuinely rescales the sketch and records raw_mass - 1 (§7.11); no such event occurred on the chain.

7.9 Numerical care, in one place

  • Sums in f64, storage in f32; zero and subnormal weights dropped at storage.
  • No light mass obtained as a difference, in either threshold routine.
  • τ\tau clamped to at least the largest light; a τ≤0\tau \le 0 (heavies holding everything) returns the heavies.
  • The systematic accumulator kept in [0,1)[0, 1) by subtracting each crossing, so its absolute precision is that of one item whatever the length of the pass.
  • Draws strictly inside (0,1)(0, 1).
  • k±1k \pm 1 outputs counted, never trimmed.

7.10 Modes, threads and the commands that were run

  • eval runs the exact store (exact.rs, bit-identical to --weighted) on its own thread beside one thread per sketch configuration, all fed by one parse, and measures every sketch against the whole exact colour every --every records, next to the same variant’s single-shot reduction of the exact colour (the IDEAL). The exact store’s memory caps it at a prefix: 3M records without --force-exact.
  • chain runs the whole chain, one store thread per configuration, and compares each sampled record’s estimate with the exact Laplace values, moments and (optionally) 1024-band binned colours on disk. --every 16 samples every 16th record into the per-bucket summaries (buckets.tsv); --rows-every 16 also writes every 16th of those sampled records, so every 256th record of the chain, to the per-record row files rows.<config>.tsv. Reference threads run zstd -dc on those files and cut them into batches on the same boundaries as the records (8,192 records a batch), checking every line’s transaction id. The bounded channels (8 batches) keep the fastest store from running away from the slowest. Errors are aggregated per 10M-record bucket, over all rows and over reduced rows (a reduction somewhere in the ancestry).
  • emit writes every record’s estimate: a reader thread parses, the store thread folds, an encoder thread writes, so parsing, sketching and the pipe to zstd overlap.
  • check recomputes chain’s metric columns from an emit file, byte for byte, so a stored production file can be validated after the fact; decode turns the binary format into text.

The modes added since (commits 159874d to adfe031) fold nothing. They read files that the runs wrote and compute from them the numbers the post states, and each was checked against the script or ad-hoc program it replaces; their commands are given where their results are.

  • summarize reads what chain and eval wrote and computes the tables of section 8: error against kk and against depth, slopes, bias across seeds, step against record mode, the recursion against one reduction and, with --moments, the floors. It follows the conventions of the Python analysis it replaces, whose means and quantiles of the reduced rows it matches to 2.4×10−122.4 \times 10^{-12} relative.
  • summary reads count streams back into what a whole-chain count is judged by: exactness, quantiles per bucket and per --range, the seeds against each other, and the exact sizes where they exist (§5.4, §10.10, §10.11). Every cell of the mawk and Python passes it replaces comes out equal, except one p90 that Python printed rounded (54 for 53.5).
  • select prefix|chain chooses the records worth comparing from a count stream and writes the file pick --select reads, byte-identical to the Python select.py’s.
  • pairs-stats reduces one or more pairs outputs to the bias, variance, agreement and quantile tables of §10.9 and §10.10, pooling the seeds of runs over the same rows, and computes the other similarities of §10.7 (from commit adfe031).
  • describe says what each production sketch cut out by decode --select is and compares it with its exact colour binned in 1024 bands (section 11). Beside it, pick --bands-ref copies those binned colours during a fold, and pairs --bands adds the binned TV of every pair.
  • surface averages the production sketches, or the binned exact colours, into the matrices of section 12, bit-identical on prefixes to the two programs first used, and surface-report turns them into that section’s tables and checks.

Both binaries run on jemalloc (§7.3).

cargo build --release --bin sketch
cargo test  --release --bin sketch -- --include-ignored

# eval3m: the first 3M records, exact colours side by side (abridged: 26 configs in one pass)
sketch eval --config varopt:16 … --config varopt:4096 \
  --config varopt:64:seed=2 … --config varopt:64:reduce=step --config varopt:256:reduce=step \
  --config prio:16 … --config prio:1024 --config coord:16 … --config coord:1024 --config coord:64:cap=harm \
  --oracle lastspend-2022.u32 --out eval3m --limit 3000000 --every 200 \
  --check-ref --laplace-ref colors.laplace.zst --stats < finalBCUTXO_2022.scm

# pass A: the whole chain, k <= 256, baselines, seeds, step mode, with the binned reference
sketch chain --config varopt:16 --config varopt:32 --config varopt:64 --config varopt:128 --config varopt:256 \
  --config varopt:64:seed=2 --config varopt:64:seed=3 --config varopt:256:seed=2 --config varopt:256:seed=3 \
  --config varopt:64:reduce=step --config prio:64 --config prio:256 --config coord:64 --config coord:256 \
  --oracle lastspend-2022.u32 --out A --limit all --every 16 --rows-every 16 --bucket 10000000 \
  --laplace-ref colors.laplace.zst --moments-ref colors.moments.zst \
  --bands-ref colors.bands1024.zst --stats < finalBCUTXO_2022.scm

# pass B: the whole chain, k = 512 and 1024 (no binned reference)
sketch chain --config varopt:512 --config varopt:1024 --config prio:1024 \
  --oracle lastspend-2022.u32 --out B --limit all --every 16 --rows-every 16 --bucket 10000000 \
  --laplace-ref colors.laplace.zst --moments-ref colors.moments.zst --stats < finalBCUTXO_2022.scm

# section 8's tables from the three passes above (reads files only, refolds nothing)
sketch summarize --chain A --chain B --eval eval3m --moments colors.moments.zst --out tables

# the cost emits (k = 64, 128, 256; and k = 512, stopped at about 400M records):
# splitcount, a small C helper outside the crate, cuts the binary stream at record
# boundaries into 10M-record stretches and pipes each through its own `zstd -q -T16 -12`,
# writing raw and compressed bytes per stretch; nothing is stored
sketch emit --config varopt:256 --oracle lastspend-2022.u32 --limit all --stats \
  < finalBCUTXO_2022.scm 2> emit.k256.err | splitcount 10000000 tmp256 > stretches.k256.tsv
# the two --long=27 runs: the same through splitcount2, which takes the zstd options

# production (section 9)
sketch emit --config varopt:512 --oracle lastspend-2022.u32 --limit all --stats \
  < finalBCUTXO_2022.scm 2> emit.err | zstd -q -T16 -12 --long=27 -o colors.sketch-varopt512.zst

7.11 The output format

From encode.rs, integers as LEB128 varints, z() zigzag, floats little-endian:

header:  "SKETCH01" | u32 version=1 | u8 variant (0 varopt, 1 prio, 2 coord)
         | u8 reduce (0 record, 1 step) | u8 cap (0 min, 1 harm) | u8 0
         | u32 k | u64 seed | u32 floor | u32 0
record:  varint z(tx - (prev_tx + 1))        prev_tx starts at u64::MAX
         u8 tag                              bit 0: shared form, bit 1: reduced
         [f32 tau | f32 (raw_mass - 1)]      only when reduced
         tag bit 0 clear:  varint n | n x varint db | n x f32 p
         tag bit 0 set:    f32 w* | varint m | m x varint db  (p bit-equal to w*)
                           | varint h | h x varint db | h x f32 p
trailer: "SKEND001" | u64 records | u64 sum over records of (tx ^ n), wrapping

Two facts shape it. Block ids sampled from a colour hundreds of thousands of blocks wide have nearly incompressible gaps, so they are written as varint deltas. And all the light terms of a varopt sketch carry the same weight, τ\tau over the total, so the shared form stores that weight once and then only the blocks that have it: four bytes saved per light term, most of a sketch. The encoder does not know which variant wrote a record; it uses the shared form whenever the most frequent f32 bit pattern occurs at least twice, which is lossless whatever wrote it. The reduced bit tells a reader which colours are exact (a record without it is the colour, up to f32). The format is meant for zstd. The encoder’s notes recommend plain -12 without --long, because --long=30’s 1 GiB window must then be passed to every decoder; --long=27 (a 128 MB window) avoids that, since it decodes with a plain zstd -d (verified with cmp), and production uses it. Those notes, and the production line in sketch.rs’s documentation (sketch emit ... | zstd -T16 -12), predate this choice.

7.12 The share matrix on disk

This subsection, like §7.3, is about the main binary. The solve of §5.2 has one coefficient matrix, Γ\Gamma, and every run rebuilds it by parsing the 149,968,404,213 bytes of the records, 193 bytes a record on average, for the five things the fold reads: the block, the transaction id, each input’s amount and the transaction it spends, and the number of outputs. Every projection, every change to what is emitted rather than to what is folded, pays that parse first. The main binary’s examples/matrix.rs writes Γ\Gamma once, in one pass, and --matrix reads it back in place of the records (a run given both a matrix and records on its input is refused):

cargo build --release --example matrix
./target/release/examples/matrix --compact chain2022.foldmat < finalBCUTXO_2022.scm   # 401.2 s
./target/release/examples/matrix --check   chain2022.foldmat < finalBCUTXO_2022.scm   # 461.6 s, 8 MB
./target/release/examples/matrix --verify  chain2022.foldmat                          # 110 s, 5.4 MB
Table 4: The share matrix of the 2022 chain in the three forms examples/matrix writes, against the records. Sizes and times from the crate’s README.md, RUNNING-2022.md and src/matrix.rs (runs of the main binary’s example, wall times; the file itself was not kept).
the 2022 chain asbytesagainst the textexact
records, finalBCUTXO_2022.scm149,968,404,2131.0×yes
--csr, u32 row pointers, u32 columns, f32 shares19,473,632,3807.7×no
--compact, the default10,601,433,51414.1×yes
--structure, no amounts6,126,089,72424.5×shape only

--check reads the compact file back against the records, field for field: 778,613,440 records and 2,044,897,328 inputs (one entry each; a repeated parent is not merged on disk), every block id reconstructed from the coinbase rows alone, the content hashes agreeing. --verify asks the same question without the 150 GB, sweeping the matrix alone against its header’s hash and counts, and it exists because a fold does not check one: of 347,416 single-bit flips inside the rows of a 20,000-record matrix, the reader’s per-row invariants accept 102,220, and a flip at byte 700,007 of a 500,000-record matrix folds to exit status 0, an empty stderr and a different answer. The row checks catch a damaged shape; only the hash catches a damaged number. The fold does not pay the 72% the hash adds to a sweep, and could not use it if it did: a hash settles at the last row, and the fold’s output streams from the first.

The 19.5 GB was the lossy one. The obvious binary form, a CSR with f32 shares, is what --csr still writes, so that its loss is measured rather than argued. An f32 share has a worst relative error of 5.96×10−85.96 \times 10^{-8}, and only 28.10% of the chain’s shares round-trip at all; the sum of a row’s shares, within 1.02×10−131.02 \times 10^{-13} of one in f64 (§5.1), drifts by up to 5.96×10−85.96 \times 10^{-8} before the fold composes anything; and replaying the fold on those shares changes 44.71% of the --sum lines and 98.92% of the coefficients of the terms output. The same f32 is harmless in a sketch (§7.2), whose error is that of a kk-point estimate; in an exact solve it is the only error. The fix is not a wider float. A share is ai/∑j=1naja_i / \sum_{j=1}^{n} a_j and both are integers, so the compact file stores the raw u64 satoshi amounts, which is exact and smaller (4.48 GB of deltas against 8.18 GB of f32): amounts within a row are nothing like uniformly distributed, and a float is 32 bits of entropy by construction.

sectionbytessharewhat it is
columns5,317,886,05750.2%2,044,897,328 parents, zigzag deltas along each row
amounts4,475,343,79042.2%1,475,397,681 satoshi values, zigzag deltas
heads804,399,8547.6%one byte a row: input and output counts, a nibble each, and escapes
blocks762,2610.0%one varint per coinbase row, none elsewhere
header and indexes3,041,5520.0%the 64-byte header; GROUPS, 16 bytes for each of the 190,092 groups of 4,096 rows; TXFIX, the four rows where the id breaks its sequence (the BIP-30 duplicates and the steps back), in 12 bytes, and the two counts
Table 5: Where the 10,601,433,514 bytes of the compact share matrix go: one self-contained row per record, in file order, with LEB128 varints and zigzag deltas throughout, as in the output format of §7.11. From the crate’s README.md and src/matrix.rs. The last row is the remainder of the total, 64 + 190,092 × 16 + 16 bytes; the README.md’s 3,041,488 leaves out the header.

Three rows of Table 5 are the case against a CSR’s fixed widths. A u32 row pointer costs 3.11 GB to hold a count whose median is 1, where a nibble and an escape cost 0.80; a u32 column costs 8.18 GB where a delta costs 5.32; and 73.14% of the rows have a single input, whose share is exactly 1 on both branches of the share rule, so 569,499,647 amounts need not exist. Those single-parent records are among the ones that answer their parent’s Rc in §7.2.

Two transforms were measured and refused, and both are reserved as flag bits a reader refuses, so that neither is re-derived later and quietly believed. Sorting each row’s parents would save 0.89 GB of the delta chain and change 4.06% of the --sum lines, because the fold walks a row’s inputs from the last to the first (§7.5) and reassociating an f64 sum moves its last bits. Deduplicating a row that spends the same transaction twice would save 0.13 GB and free that colour at the wrong instant, for the reason §5.3 ends its oracle on: the fold counts the multiplicity down, and the oracle frees a colour on the lowest input index that names it.

A run off the records and the same run off the matrix print the same bytes. The largest checks are a --sets pair of 294.6 GB a side at 2,000,000 records and --bands 1024 --moments at 20,000,000 records, 1,149,593,609 bytes a side, and --rings and --sets still hash alike off a matrix. What the matrix saves is less than the size ratio: over 20,000,000 records, 17.8 s off the text against 11.7 s off the matrix with the fold as cheap as it goes (--bands 1 --sum), and 70.5 s against 63.9 s at --bands 1024 --moments, where the fold is most of the work, both with the records warm in the page cache; cold, the two files are 12.5 minutes of reading against 50 seconds. What the matrix buys is not a faster fold but a parse paid once. The whole-chain colors.bands1024.zst of §5.2 was folded off it. sketch does not read the matrix: its runs parse the text.

7.13 The tests

cargo test --release --bin sketch -- --include-ignored passed 106 of 106 at the time of the runs of section 8, and 139 of 139 with the stores of section 10. At commit adfe031, with the modes that read the runs back, cargo test --release --bin sketch passes 196 and ignores 4: the two integration tests that read the chain’s files, the coord bias test below and a benchmark, which --include-ignored runs. What they assert:

  • Randomness (T1). splitmix64’s golden value; unit strictly inside (0,1)(0, 1) at both ends and over a million draws; streams deterministic and distinct across salts and seeds.
  • VarOpt, deterministic (T2). Over 1,000 random draws ×\times 64 offsets (61,056 reductions; the draws with n≤kn \le k are skipped, since the caller stores those untouched): output ascending, a subset of the input, heavies kept with their weight, lights at τ\tau, ∑b∈Bmin⁡(1,vb/τ)=k\sum_{b \in B} \min(1, v_b/\tau) = k to 10−910^{-9} relative, and, except in k±1k \pm 1 events, exactly kk points, the mass to 10−1210^{-12} and every CDF gap below τ\tau (Theorem 3); fewer than 64 k±1k \pm 1 events in those 61,056 reductions. The iterated threshold equals the sorted one on 2,764 cases (3,000 draws, n≤kn \le k skipped), including geometric weights and many-way ties; a few items holding all the mass but a tail of weights near 10−30010^{-300} never overflow k+1k + 1.
  • VarOpt, statistical (T3). Over 200,000 offsets, every coordinate’s mean estimate is its weight, every light’s inclusion frequency is v/τv/\tau, and the mean Laplace value at s=4s = 4 is exact, all within 5 standard errors.
  • prio (T4). The mean raw Horvitz–Thompson weight of every coordinate is its weight within 5 SE, and the output always has kk points.
  • coord (T5, T6). Lemma 17 bit for bit in the f32 world, nested; step mode with the binary cap; cap=harm keeps a rank prefix of what cap=min keeps; against the exact store on overlapping DAGs, stored weights are lower bounds and an infinite τ\tau means exact.
  • The driver (T7, T8). With kk at least every support, every variant in both reduce modes, with and without the oracle, emits the exact colour; with k=64k = 64, every record whose exact support is at most 64 comes out exact; with k=220k = 2^{20} every variant matches the exact store, and the exact store matches a direct reimplementation of run()’s fold bit for bit.
  • Through a DAG (T9, T10). Over 2,000 seeds on a synthetic DAG, varopt’s emitted estimate and prio’s raw weights are unbiased within 5 SE, block by block and for the Laplace value; varopt’s mass stays within 10−510^{-5} of one at every record. coord’s bias is documented by an ignored test rather than gated: worst ∣z∣=19.7\lvert z \rvert = 19.7.
  • Format and determinism. Emitted bytes decode to the text emitted directly, metadata included; the same seed writes the same bytes, another seed does not.
  • Integration. The first 100,000 records of the chain with k=220k = 2^{20}, transaction by transaction, against coloring-bt-transactions 100000 --weighted: worst absolute error 3.34×10−83.34 \times 10^{-8}, worst relative error 2.22×10−72.22 \times 10^{-7} for coefficients of at least 10−610^{-6}.
  • The permutation (T-K1). Perm is a bijection with block(rank(b)) == b on all of [0,2bits)[0, 2^{\text{bits}}) for bits 12, 16 and 20 and three seeds, with its first ranks pinned; seeds share fewer than 1% of fixed points; a block past the universe is a hard error. Over 2162^{16} seeds at 12 bits the rank of a fixed block passes a χ2\chi^2 test on 64 cells (p>10−4p > 10^{-4}), and the ranks of two blocks show no correlation.
  • Capped merges (T-K2). The two-way merge, the tree and the heap equal a brute-force bottom-kk of the union, with the truncation flag exact, over random runs with overlaps, identical and empty runs, k∈{1,2,3,16,64}k \in \{1, 2, 3, 16, 64\}.
  • KMV through the driver (T-K3 to T-K5). On the synthetic streams of T7 (shared parents, repeated inputs, zero amounts, all-zero records, one-group records, the BIP-30 duplicate) and on a random DAG, with and without the oracle, k∈{2,3,16,64}k \in \{2, 3, 16, 64\}: every sketch is the bottom-kk of the brute-force support, full holds exactly when the support exceeds kk, a whole sketch’s count is the support’s size, the sets support equals the exact store’s terms and the pos support its positive-share reachability; permuting or splitting operands changes no byte. A block diluted 101810^{18}-fold at each of 30 steps (10−54010^{-540} in all), whose f64 coefficient underflows to 0, stays in the pos support.
  • Estimators over 2,000 seeds (T-K6 to T-K8). The count over both universes (including dense subsets of [0,β][0, \beta]) and the restricted union count are unbiased within 4 SE, with RMS within 10% of the formula; Jaccard is exact when both sketches are whole, also when their union exceeds kk (where the textbook form is not), and over J∈{0,0.024,0.2,0.95,1}J \in \{0, 0.024, 0.2, 0.95, 1\} its mean is within 4 SE and its SD within 10% of the hypergeometric value; containment is NaN exactly when its sample is empty and otherwise unbiased within 4 SE where its sample is large.
  • The projection (T-L1 to T-L4). The L1 store’s vector equals Π Ct\Pi\,C_t computed from the exact colour, through the grouped and the free path, to 10−610^{-6} relative in f32 and 10−1210^{-12} in f64; over 400 seeds at m∈{128,512}m \in \{128, 512\} and TV∈{0.001,0.01,0.1,0.5,1}\mathrm{TV} \in \{0.001, 0.01, 0.1, 0.5, 1\} the scale MLE has a relative bias of at most 2% and a relative SD times m\sqrt m in [1.30,1.52][1.30, 1.52] (2=1.414\sqrt 2 = 1.414); identical colours give TV̂=0\widehat{\mathrm{TV}} = 0 exactly, disjoint ones a value within 32/m3\sqrt{2/m} of 1, injected infinities a finite one; two seeds are uncorrelated.
  • Streams and modes (T-K9, T-K10, T-P1, T-P2, T-E1). The count stream round-trips with its checksum at fixed width, decode dispatches on the magic and still writes the old text for SKETCH01; the same seed writes the same bytes; pairs equals the pure estimators and is byte-identical at 1 and 8 threads; pick captures each selected record once; eval finds no set mismatch; damaged headers are an error, not a panic; the new modes refuse options they would ignore.
  • Integration (T-I1). The first 1,000,000 records of the chain at k=1024k = 1024 against the exact support sizes: exact wherever the support has at most kk blocks, and every seed gate of a 16-seed family at k=256k = 256 passes.
  • The modes that read runs back. Their sums, medians and linear quantiles equal numpy’s on values numpy printed; summarize and pairs-stats reduce a small sweep and a small pairs run end to end, and select’s file reads back; the exact surface is the same at any thread count; and the old modes refuse the new modes' options.

8. Results

8.1 What was measured

  • Pass A (chain, the whole chain, 14 stores in one pass): varopt at k=16,32,64,128,256k = 16, 32, 64, 128, 256; seeds 2 and 3 at k=64k = 64 and 256256; step mode at k=64k = 64; prio and coord at k=64k = 64 and 256256; with the 1024-band reference.
  • Pass B (chain, the whole chain): varopt at k=512k = 512 and 10241024 and prio at 10241024, one seed, without the band reference. It took 11 h 43 min (wall time from /usr/bin/time -v) and peaked at 164.4 GB of resident memory for the three stores together (the vm_hwm column of its cost.tsv).
  • eval3m (eval, the first 3M records, every 200th record, 15,000 rows a configuration): every sketch against its whole exact colour and against the same variant’s single-shot reduction of it.
  • Cost emits (emit cut into 10M-record stretches, each compressed by its own zstd -T16 -12, §7.10): varopt at k=64,128,256k = 64, 128, 256 over the whole chain, and at k=512k = 512 until it was stopped at about 400M records; two more with --long=27.

The accuracy tables use every 256th record (--every 16 --rows-every 16, §7.10; 3.04M rows), restricted to reduced rows: a larger kk keeps more early colours exact, which would lower an all-rows average for a reason that has nothing to do with how well a sketch approximates. Errors in blocks are converted from fractions of LL; a day is about 144 blocks. Labels: [M] measured, [P] projected from measurements, [E] a rougher estimate (an extrapolated compression ratio). Every number below comes from those runs, whose commands are in §7.10.

One more mode turns their outputs into the tables of this section: sketch summarize reads each pass’s per-record rows, buckets.tsv, seeds.tsv and cost.tsv, and eval3m’s rows.tsv and summary.tsv, groups the rows by 100M-record stretch (S0 to S7, S0-2 for the first 300M, pooled for the whole chain) and writes one TSV per kind of table, without rerunning a fold (--moments adds the floors of §8.8):

sketch summarize --chain A --chain B --eval eval3m --moments colors.moments.zst \
  --out tables

The Python scripts that first made these tables agree with it at every digit printed here (the means and quantiles of the reduced rows to 2.4×10−122.4 \times 10^{-12} relative; the rest differ only by how pandas parses long decimals). Each subsection names the file of tables/ its results come from.

8.2 Error against kk

kkmean |Δmean| (blocks)p90 |Δmean| (blocks)mean |Δmean|/sd (%)mean max |ΔLaplace| (×10⁻³)mean |Δsd|/L (×10⁻³)
169,40119,1866.1716.74.30
324,95110,1743.259.182.33
642,5805,3301.694.891.22
1281,3332,7590.8732.530.615
2566861,4260.4461.290.301
5123497290.2250.6590.143
10241783720.1140.3380.070
prio 64 / 256 / 102415,303 / 7,585 / 3,73133,373 / 16,500 / 8,1589.74 / 4.80 / 2.3524.1 / 12.0 / 5.929.69 / 4.60 / 2.25
coord 64 / 25667,482 / 59,072121,513 / 105,76539.4 / 34.571.0 / 61.612.2 / 13.4
Table 6: Error of the sketched colour against the exact one, whole chain, reduced rows, seed 1, record mode. Rows without a variant name are varopt. All measured. From sketch summarize, errors.tsv, group pooled.
Two log-log panels of mean error against k for varopt, prio and coord, with 1/k and 1/sqrt(k) guides.
Figure 2: Error against kk on the whole chain, reduced rows: the mean absolute error of the mean block, and the mean of the largest Laplace error over the seven ss. varopt follows the 1/k1/k guide from 16 to 1024; prio follows 1/k1/\sqrt{k}; coord barely moves.

varopt’s error halves with every doubling of kk, with no floor up to k=1024k = 1024 (Figure 2). Over k=16..256k = 16..256 the log-log slopes are −0.93-0.93 to −0.96-0.96 for ∣Δmean∣\lvert\Delta\text{mean}\rvert, ∣Δsd∣\lvert\Delta\text{sd}\rvert, the Laplace errors at s=0.5..8s = 0.5..8, the largest Laplace error and the binned W1W_1; −0.90-0.90 and −0.85-0.85 for Λ16\Lambda_{16} and Λ32\Lambda_{32}, the far tail that small sketches undersample. The local slopes steepen with kk: about −0.97-0.97 for ∣Δmean∣\lvert\Delta\text{mean}\rvert from 256 to 512 and from 512 to 1024 over the whole chain (−0.98-0.98 on 0–300M). An approximate law is

∣Δmean∣≈(1.0 to 1.2)⋅sdexactk: \lvert\Delta\text{mean}\rvert \approx (1.0 \text{ to } 1.2)\cdot \frac{\text{sd}_{\text{exact}}}{k}:

the product k⋅∣Δmean∣/sdk \cdot \lvert\Delta\text{mean}\rvert/\text{sd} drifts from 0.990.99 at k=16k = 16 to 1.171.17 at k=1024k = 1024. The slopes are slopes.tsv (an OLS fit per metric and run of consecutive kk), the product is errors.tsv’s k_times_mean_abs_dmean_over_sd.

8.3 Error against depth

Table 7: varopt, mean absolute error of the mean block (in blocks) by stretch of the chain, reduced rows; the exact spread of the reduced rows (shown for k = 64; k = 128 to 1024 differ by at most 0.23%); and the error relative to it. From errors.tsv, groups S0 to S7.
stretch (records)k=128k = 12825625651251210241024exact sd (blocks)512512: |Δmean|/sd (%)10241024: |Δmean|/sd (%)
0–100M77439620110281,7220.2410.121
100–200M1,016522265134117,9570.2240.113
200–300M1,132579294149131,5790.2220.112
300–400M1,328683349179156,0360.2230.114
400–500M1,433746381195173,7600.2180.111
500–600M1,561803409209187,3860.2190.111
600–700M1,661853434221190,8190.2280.116
700–778.6M1,835940481249210,3060.2300.119
Two panels of error per 10-million-record bucket along the chain for varopt at seven k, prio and coord.
Figure 3: Error along the chain, per 10M-record bucket, reduced rows. In blocks (left) varopt’s error grows by about 1.8× from 100–200M to the end, exactly as the colours’ own spread does; relative to that spread (right) it is flat at every kk. coord’s relative error keeps growing. Drawn from buckets.tsv of passes A and B.

There is no accumulation with depth (Figure 3). The error in blocks grows, by about 1.8× from 100–200M to 700–778.6M at every kk, because the colours themselves spread out (their exact sd goes from 118k to 210k blocks). Relative to the spread it is flat: the ratio of the last stretch to 100–200M is 1.01–1.02 for k=16..256k = 16..256, 1.03 at k=512k = 512 and 1.05 at k=1024k = 1024. The deepest stretch is still the one to plan against: its p90 is 3,677 / 1,896 / 978 / 503 blocks for k=128/256/512/1024k = 128 / 256 / 512 / 1024. One thing does grow: varopt’s ∣Δsd∣\lvert\Delta\text{sd}\rvert, by 1.12–1.28× with depth at k≤256k \le 256 (prio’s by 1.8×). As §6.3 explains, the flatness is measured, not proved. The ratios are in depth.tsv, the p90s in errors.tsv at S7.

8.4 The variants compared

  • prio falls as 1/k1/\sqrt{k} (slopes −0.49-0.49 to −0.54-0.54; −0.51-0.51 from 256 to 1024), as the argument after Proposition 13 predicts. Its error is 5.9× varopt’s at k=64k = 64, 11.1× at 256256 and 20.9× at 10241024: prio at 1024 is worse than varopt at 64, and prio at 256 is worse than varopt at 32. Against its own single-shot reduction on exact colours (eval3m, colours above 32,768 blocks) the recursive prio is −13%-13\% to +1%+1\% off: the recursion adds nothing, and its whole error is the sampling error of one priority-sampling reduction.
  • coord does not improve with kk and is mostly bias. Its slopes from 64 to 256 are −0.16-0.16 to +0.08+0.08; its error relative to the spread grows 2.1–2.3× along the chain (depth exponent 0.8–0.9 for ∣Δmean∣\lvert\Delta\text{mean}\rvert); and its signed mean is 0.99 of its mean absolute error for Δ\Deltamean and for Λ0.5\Lambda_{0.5} and Λ2\Lambda_2 (0.94–0.95 for Λ8\Lambda_8, 0.61–0.80 for Λ32\Lambda_{32}). Its estimated colours are systematically too late. On eval3m its excess over its own single shot grows with kk (KS +120%+120\% and W1W_1 +98%+98\% at k=1024k = 1024). This is §6.6 at scale.

The slopes are in slopes.tsv (the ranges leave out TV1024, §8.8), the multiples of varopt in errors.tsv, coord’s depth in depth.tsv and its signed ratios in signed.tsv, the eval3m excesses in ideal.tsv.

8.5 Bias

Left: signed mean error of the mean per bucket for three varopt seeds and prio at k 256. Right: signed mean over mean absolute error per bucket for varopt, prio and coord.
Figure 4: Signed error per 10M-record bucket at k=256k = 256. Left, in blocks: three varopt seeds stay within a few hundred blocks of zero (RMS about 70 blocks over the 78 buckets), while prio swings by up to about 1,800. Right, signed mean over mean absolute error: coord sits at +1+1, all bias. Drawn from pass A’s buckets.tsv; the RMS and the largest swing are in signed.tsv.

varopt is unbiased by Theorem 7, and the chain does not contradict it (Figure 4), but the test is weak. Rows of one run share sketches and ancestry, so per-row standard errors understate the spread of a mean many times over (by 3× to 35× on the first 600k records; that produced “biases” at z=24z = 24 that 16 seeds showed were not there; design-phase prefix runs, not a crate run). The honest test uses independent seeds: three at k=64k = 64 and at k=256k = 256, whole-chain count-weighted signed means, tt with 2 degrees of freedom.

  • ∣t∣≤2.18\lvert t \rvert \le 2.18 at k=64k = 64 and ≤0.94\le 0.94 at k=256k = 256 over Δ\Deltamean and the seven Laplace values (p≥0.16p \ge 0.16).
  • The 95% bound on ∣bias∣\lvert\text{bias}\rvert, ∣mean∣+t0.975,2⋅SE\lvert\text{mean}\rvert + t_{0.975,2}\cdot\text{SE}, is at most 11.4% of the mean absolute error at k=64k = 64 and 16.7% at k=256k = 256. Three seeds cannot do better than that.
  • Per stretch, none of the 128 tt values exceeds the critical 4.30 (the largest is −4.27-4.27); per 10M bucket, 1–2 of 78 reject at k=256k = 256 and 2–6 of 78 at k=64k = 64, against about 3.9 expected (and buckets are serially correlated).
  • On eval3m with 4 seeds, and in an earlier 12-seed check on a prefix of the chain: ∣z∣≤1.21\lvert z \rvert \le 1.21.
  • k=512k = 512 and 10241024 were run with one seed and were not tested for bias.

The tests are bias.tsv (with the bound as bound_over_abs) and bias_buckets.tsv; the eval3m zz are eval’s own seeds.tsv; the 12-seed check is the same mode over the verification’s 10M-record prefix run:

sketch summarize --chain chain10m-seeds --stretch 5000000 --out verify10m

8.6 Record mode against step mode

Figure 5: varopt at k=64k = 64: the error of the literal pairwise fold (a reduction after every combine, seed 1) over the mean error of one reduction per record at seeds 1–3, per bucket, from pass A’s buckets.tsv.Ratio of step-mode to record-mode error per bucket for three metrics at k 64.

Step mode is worse at every depth (Figure 5): over the whole chain, against the mean of three record-mode seeds, 1.49× for ∣Δmean∣\lvert\Delta\text{mean}\rvert, 1.72× for ∣Δsd∣\lvert\Delta\text{sd}\rvert, 1.34× for the largest Laplace error, 1.24× for Λ8\Lambda_8, 1.46× for binned W1W_1 and 1.51× for the band-edge KS, between 1.18× and 2.02× per stretch, with ∣Δsd∣\lvert\Delta\text{sd}\rvert the least uniform (1.26× before 100M, 1.75–2.02× after 200M). It did 6.15× the reductions (1,219,272,266 against 198,333,465) for about the same CPU time (3,951 s against 4,048 s of fold time), and on eval3m it multiplied the KS and W1W_1 excess over the single shot by 2.2–2.6×. The ratios are in step.tsv, the reductions and fold times in cost.tsv, and the eval3m factors are step mode’s paired excess in ideal.tsv over that of record-mode seed 1, in stratum fix:>32768 at k=64k = 64 and 256256.

8.7 The recursion against a single reduction

Left: W1 against k for recursive and single-shot varopt and prio. Right: percentage excess of recursive varopt over single shot for KS, W1, TV1024 and the mean.
Figure 6: The first 3M records, colours with more than 32,768 blocks, against the exact colours. Left: W1W_1 of the recursive sketch and of the same reduction applied once to the exact colour. Right: how much the recursion adds for varopt, in percent. Drawn from eval3m’s summary.tsv and rows.tsv.
Table 8: eval3m, varopt, colours with more than 32,768 blocks: excess of the recursive sketch over the single-shot reduction of the exact colour (paired, every 200th record of the first 3M). From ideal.tsv, stratum fix:>32768.
metricexcess at k=16k = 16excess at k=4096k = 4096
KS+66%+235%
W1W_1+31%+97%
TV over 1024 bands+1%+52%
|Δmean|+29%+67%

The recursion has a price (Figure 6 and the table above), and it grows slowly with kk, but all three errors keep falling: the recursive KS, W1W_1 and largest Laplace error fall as k−1.05k^{-1.05}, k−1.07k^{-1.07} and k−1.05k^{-1.05} over k=16k = 16 to 40964096, the single shot as k−1.17k^{-1.17}, k−1.14k^{-1.14} and k−1.12k^{-1.12}. For colours of 4,097 to 32,768 blocks the W1W_1 excess is only +2% to +28% (stratum fix:(4096,32768]); the exponents are ideal_slopes.tsv. And the price does not grow with depth (§8.3).

8.8 Floors: what TV1024 cannot say

A sketch of kk points of a colour spread over thousands of bands cannot have a small total variation over 1024 bands, however good it is. Recomputed with each row’s own τ\tau, the single-shot VarOpt lower bound on TV1024 is 0.883, 0.746 and 0.375 against the measured 0.919, 0.818 and 0.540 at k=16,64,256k = 16, 64, 256: at least 96%, 91% and 69% of the measured TV1024 is sampling floor, so it does not measure the recursion at k≤256k \le 256 and is left out of the comparisons. The band-edge KS has a floor of about 0.75 τ0.75\,\tau (the remark after Corollary 4; single-shot KS/τ/\tau measured at 0.741–0.750 for k=16k = 16 to 40964096), which on eval3m is about 60% of the measured value at k=16k = 16, falling to about 40% at k=512k = 512 and 30% at k=4096k = 4096 (one over one plus the KS excess of Table 8). The binned W1W_1 has no hard floor (on eval3m the single shot is 60–77% of the measured value for k≤1024k \le 1024, falling to about 51% at k=4096k = 4096). So kk is chosen on ∣Δmean∣\lvert\Delta\text{mean}\rvert, its p90, the Laplace errors and W1W_1.

The floors are in the tables --moments adds: floors_chain.tsv (floor_lb_own_tau, and its share of the measured tv) and floors_eval.tsv (ideal_ks_over_tau, ideal_w1_over_w1); the KS shares are one over one plus ideal.tsv’s excess.

8.9 Cost

configmean / p90 |Δmean| (blocks)≈ days (mean / p90)peak RSSwall timezstd -12-12 --long=27status
varopt 642,580 / 5,330 [M]17.9 / 378.5 GB [M]1.1 h [M]31.3 GB [M]~20 GB [E]Pareto
varopt 1281,333 / 2,759 [M]9.3 / 1912.4 GB [M]1.8–2.0 h [M]65.6 GB [M]41.7 GB [M]Pareto
varopt 256686 / 1,426 [M]4.8 / 9.920.3 GB [M]3.4 h [M]144.5 GB [M]~86 GB [E]Pareto, fallback
varopt 512349 / 729 [M]2.4 / 5.136.3 GB [M]5.1 h [M]~312 GB [P]172.7 GB [M]Pareto, chosen
varopt 1024178 / 372 [M]1.2 / 2.6~68 GB [P]11.4–11.9 h [P]659–721 GB [P]~380–420 GB [E]Pareto, for a tight tolerance
varopt 64, step mode3,866 / – [M]26.8 / –≈ varopt 64 [E]fold time 0.98× varopt 64 [M]≈ varopt 64 [E]–dominated
prio 6415,303 / 33,373 [M]106 / 232≈ varopt 64fold time 1.07× varopt 64 [M]not measured–dominated
prio 2567,585 / 16,500 [M]53 / 115≈ varopt 256fold time 1.12× varopt 256 [M]not measured–dominated
prio 10243,731 / 8,158 [M]26 / 57~68 GB [P]≥ varopt 1024not measured–dominated
coord 6467,482 / 121,513 [M]469 / 844≈ varopt 64fold time 0.77× varopt 64 [M]not measured–dominated
coord 25659,072 / 105,765 [M]410 / 734≈ varopt 256fold time 0.64× varopt 256 [M]not measured–dominated
Table 9: Error against cost over the whole chain. Wall times are of single-configuration emits run beside other jobs (good to about 12 percent), except k = 512, whose wall time and –long=27 size are those of the production run of section 9, which ran almost alone; for step mode, prio and coord only the fold time of pass A is known, given relative to varopt at the same k. Sizes are the emit compressed by zstd with 16 threads.
Two log-log panels: mean and p90 error of the mean against compressed size and against wall time, for varopt k 64 to 1024; measured points filled, projected hollow.
Figure 7: varopt, error against cost for k=64k = 64 to 10241024. Filled markers are measured, hollow ones projected or estimated; the horizontal bars are ranges. Every doubling of kk halves the error and roughly doubles the bytes and the time: there is no knee. The points are the table’s cells, written into the plotting script by hand.

Only the errors (errors.tsv) and the fold-time ratios (cost.tsv’s busy_over_reference) come from sketch summarize. The rest was measured on the cost emits of §7.10: peak memory by their --stats, and, outside the crate, wall times and CPU shares by /usr/bin/time -v and bytes per 10M-record stretch by splitcount and a small Python script. The [P] and [E] cells and the memory fit are hand projections.

  • Size. Measured with zstd -T16 -12 over the whole chain: 31.3, 65.6 and 144.5 GB at k=64,128,256k = 64, 128, 256 (raw 114.7, 212.8 and 411.9 GB), and 151.2 GB for the first 400M records at k=512k = 512 (raw 410.5 GB). Every run parsed all 778,613,440 records with a matching trailer (splitcount checks it), and repeated runs wrote byte-identical output. The whole-chain k=512k = 512 size is projected by scaling the k=256k = 256 tail (400M records to the end) by the k=512/k=256k = 512 / k = 256 ratio: measured over 300–400M, that gives 313.6 GB (403 B a record; raw about 806 GB), and measured over 0–400M, 310.7 GB; k=1024k = 1024 at 659–721 GB (raw about 1.59 TB, which would not fit on the disk: the raw stream must never be written). --long=27 (a 128 MB window) saved 36.4% at k=128k = 128 over the whole chain and 40.7% at k=256k = 256 over 0–350M; at k=512k = 512 the production run measured it over the whole chain, 172.7 GB (221.8 B a record), about 45% below the 312 GB projected without it. The k=64k = 64, 256256 and 10241024 figures with it are estimates. Compressed bytes peak at 580–650M records (238.2 B a record at k=256k = 256 for 600–610M), not at the slowest stretch (290–330M).

  • Memory. Peak RSS (the VmHWM of emit --stats, equal to /usr/bin/time -v’s, which alone gives the stopped k=512k = 512 emit’s; reported in KiB and given here in GB of 10910^9 bytes) 8.51, 12.39, 20.32 and 36.34 GB at k=64,128,256,512k = 64, 128, 256, 512. The fit

    VmHWM≈4.5 GB+8.3 B×peak entries,peak entries≈7.485M×k \text{VmHWM} \approx 4.5\ \text{GB} + 8.3\ \text{B} \times \text{peak entries}, \qquad \text{peak entries} \approx 7.485\text{M} \times k

    (peak entries from --stats) projects about 68 GB at k=1024k = 1024, consistent with pass B. Live sketches hold about 0.985 k0.985\,k entries each at the peak. The machine has 503 GiB, so memory constrains no kk here.

  • Time. 1 h 07 min, 1 h 47 min to 2 h 00 min, and 3 h 23 min at k=64,128,256k = 64, 128, 256; about 2 h 52 min to 400M records at k=512k = 512, projected to 6.3–6.6 h for the whole chain (in pass A’s bucket_cost.tsv, the 378.6M-record tail takes 1.22–1.28× the fold time of the first 400M at k=64k = 64 to 256256, rising with kk); the production run, with almost nothing beside it, took 5 h 06 min, so the projection, made from emits that shared the machine, was about 25% high. k=1024k = 1024 is projected at 11.4–11.9 h by the same method, and is probably high by a similar margin. The emit uses 120–135% of a core; zstd -12 with 16 threads runs at 230–290 MB/s (a benchmark) against at most about 55 MB/s of output, so it is never the bottleneck.

8.10 The choice of kk

The cost has no knee (Figure 7): every doubling of kk halves the error and roughly doubles the bytes and the time. So the rule is a tolerance: pick the smallest kk whose deep-chain p90 ∣Δmean∣\lvert\Delta\text{mean}\rvert is below the tolerance a downstream analysis can accept for one transaction’s mean colour.

Table 10: The decision rule: deep-chain p90 error of the mean block, by k. From errors.tsv, group S7.
deep-chain p90 |Δmean| (700–778.6M)≈ dayskk
1,896 blocks13256
978 blocks6.8512
503 blocks3.51024

Relative to a colour’s own spread the mean ∣Δmean∣/sd\lvert\Delta\text{mean}\rvert/\text{sd} is 0.45%, 0.23% and 0.11% for k=256,512,1024k = 256, 512, 1024, at every depth. With no stated tolerance, k=512k = 512 is the default: it halves every error of k=256k = 256, its memory is measured, its output takes under a quarter of the 1,291 GB free on the disk (df) even without --long, and it runs overnight. k=1024k = 1024 is feasible and halves the error once more, but costs half the free disk at -12, a 12-hour run, and an emit whose size, time and memory are all projected. k=256k = 256, the only kk with everything measured, is the fallback.

Pass B finished after this choice was made and confirmed it. The whole-chain ∣Δmean∣\lvert\Delta\text{mean}\rvert is 349 and 178 blocks for k=512k = 512 and 10241024 (a ratio of 0.51); the ratio of ∣Δmean∣/sd\lvert\Delta\text{mean}\rvert/\text{sd} between the last stretch and 100–200M is 1.03 and 1.05; pass B’s peak resident memory was 164.4 GB for its three stores; its fold time at k=1024k = 1024 was 1.90× that at k=512k = 512, and its wall time 11 h 43 min; and prio at 1024 is 20.9× worse than varopt at 1024. All but the wall time are in the files above (memory and fold times in cost.tsv).

9. The Production Run

Started on 2026-11-13, with the build used for every measurement above:

sketch emit --config varopt:512 --oracle lastspend-2022.u32 --limit all --stats \
  < finalBCUTXO_2022.scm 2> emit.err \
  | zstd -q -T16 -12 --long=27 -o colors.sketch-varopt512.zst

It writes colors.sketch-varopt512.zst: for each of the 778,613,440 transactions, in record order, its colour as a varopt sketch of at most 512 blocks (k±1k \pm 1 in rare rounding events), normalised to sum one, with the bit that says whether it is exact (and, when it is not, its τ\tau and raw mass), in the format of §7.11. It decodes with a plain zstd -d piped into sketch decode, and sketch check recomputes from it the error tables of a chain run.

It ran from 07:39 to 12:45, and the pipeline exited with status 0.

Table 11: The production run. It shared the machine only with the end of pass B and a site build, which is why it beat the projection, made from emits that ran beside other jobs. Wall time and CPU share from /usr/bin/time -v, the size from the file, the rest from the last line emit --stats wrote.
measuredprojected before the run
wall time5 h 05 min 56 s (fold busy 15,797 s; 131% of a core)6.3–6.6 h [P]
peak RSS (VmHWM)35,480,448 KiB = 36.33 GB36.34 GB (measured on 0–400M)
colors.sketch-varopt512.zst172,702,042,699 bytes, 221.8 B a recordabout 175–190 GB [E]; about 312 GB [P] without --long=27
reductions198,939,818–
peak distinct live sketches7,593,630–
k±1k \pm 1 events0–

No reduction rounded to k±1k \pm 1: every sketch in the file has at most 512 entries.

Checked by reading it back. The file was decoded and scored against the exact references, independently of the run that wrote it:

zstd -dc colors.sketch-varopt512.zst \
  | sketch check --out check --every 16 --rows-every 16 --bucket 10000000 \
      --laplace-ref colors.laplace.zst --moments-ref colors.moments.zst

It took 1 h 03 min in 138 MB (from /usr/bin/time -v), read all 778,613,440 records, and found the count and checksum of the file’s trailer correct. Its per-record error rows (rows.varopt-k512-s1-rec.tsv, 3,041,459 of them, every 256th record) and its 2,496 bucket rows (buckets.tsv) are byte for byte those of the varopt-k512-s1-rec store of pass B, which computed them in memory while folding. So the file holds exactly the sketches whose accuracy section 8 reports: over the whole chain, 349 blocks mean and 729 blocks p90 error on the mean block (Table 6, §8.2). A plain zstd -d decodes it; a 128 MB window needs no flag.

A second product sits beside it: colors.kmv1024.counts.zst, the size of every transaction’s support, counted by the coordinated bottom-kk of section 10, exactly when the support has at most 1024 blocks and by an unbiased estimate otherwise. Section 10.11 says how to read it.

10. Counting and Comparing Colours

Sections 5–9 read a colour through linear functionals: its mean, its CDF, its Laplace values. Two questions about transactions are not of that kind. From how many blocks does a transaction descend? And how much do two transactions share? The varopt sketches cannot answer either (§10.2), and nothing about them needs to change for the answers: two more stores, folded by the same driver beside or instead of varopt, answer them, one exactly through the whole DAG (§10.3–10.5) and one through a linear sketch (§10.6).

10.1 What is asked

Both questions are about the support of a colour, the blocks it descends from, and the support has a recurrence of its own, the set-valued shadow of (1):

St={β} for a coinbase of block β,St=⋃i=1nSpi otherwise. S_t = \{\beta\} \ \text{for a coinbase of block } \beta, \qquad S_t = \bigcup_{i=1}^{n} S_{p_i} \ \text{otherwise.} (5)

It comes with two semantics, and every number below names which one it is about:

  • sets keeps every input, zero-amount ones included. It is what the repository’s --sets computes, the exact sizes of the first 31,187,785 records are on disk (finalBCUTXO_2022.sets-counts.31187785.txt), and it is the default.
  • pos keeps the operands with a positive share, St+=⋃i:st,i>0Spi+S^+_t = \bigcup_{i : s_{t,i} > 0} S^+_{p_i}: the blocks reachable through positive-share edges. In exact arithmetic this is {b:ct(b)>0}\{b : c_t(b) > 0\}, the support of the weighted colour, since ct(b)c_t(b) is a sum over paths of products of shares. In f64 a coefficient can underflow to zero while its block stays reachable: record 2,499,382 has 96,213 terms, 9,392 of them exactly 0, every one an underflow. On this chain the two supports nearly coincide; their k=1024k = 1024 seed-1 count streams differ in 104 of the 31,187,785 records.

Three measures are asked of it.

  • Count, ∣St∣\lvert S_t \rvert: the number of blocks a transaction’s coins descend from (under sets, through zero-amount inputs too). §5.4 gives its scale: a median of about 174,000 blocks over the first 31.2M records.

  • Jaccard similarity and containment, shared ancestry:

    J(x,y)=∣Sx∩Sy∣∣Sx∪Sy∣,∣Sx∩Sy∣∣Sx∣. J(x, y) = \frac{\lvert S_x \cap S_y \rvert}{\lvert S_x \cup S_y \rvert}, \qquad \frac{\lvert S_x \cap S_y \rvert}{\lvert S_x \rvert} .
  • Weighted Jaccard similarity, shared value:

    Jw(x,y)=∑b=0L−1min⁡(cx(b),cy(b))∑b=0L−1max⁡(cx(b),cy(b)). J_w(x, y) = \frac{\sum_{b=0}^{L-1} \min\big(c_x(b), c_y(b)\big)}{\sum_{b=0}^{L-1} \max\big(c_x(b), c_y(b)\big)} .

On this chain the last two say very different things. Among 255 deep transactions spread over the first 3M records (the deep selection of §10.9, every support of at least 1,024 blocks), the median JJ of a pair is 0.157 but the median JwJ_w is 1.4×10−41.4 \times 10^{-4}, and 92% of the pairs have Jw<0.01J_w < 0.01: old supports are largely shared, while a colour’s weight sits on its recent blocks, which two transactions far apart in time do not share. Inside a window of three blocks (the window selection) the median JJ is 0.994 and the median JwJ_w is 0.18. Over the whole chain the weights overlap more: among 512 deep transactions spread from 2010 to 2022 (§10.10) the median JJ of a pair is 0.48 and the median estimated JwJ_w is 0.21, still 0.18 for pairs more than 60,000 blocks apart. These medians are read off the pair runs R3 and R7 of §10.9 and §10.10 by sketch pairs-stats (§10.8), in its quantiles.tsv (the 92% in jw-strata.tsv).

10.2 Why the VarOpt sketches cannot answer

The production file of §9 holds a sketch of every colour, and it is tempting to read counts and similarities off it. It cannot be done, for four reasons.

  1. Its randomness is fresh at every reduction (§6.2), so two sketches are not coordinated: a block in both supports is kept in both sketches only by coincidence, and the overlap of two kept sets does not estimate the overlap of the supports.
  2. Kept lights are carried at τ\tau (Definition 1), so a kept light’s true weight, and with it its inclusion probability vb/τv_b/\tau, is not in the sketch: a Horvitz–Thompson count ∑b∈K1/πb\sum_{b \in K} 1/\pi_b over the kept set KK cannot be formed from it, even after a single reduction.
  3. A block dropped at an ancestor is gone for every descendant: the candidate of a record holds only blocks its parents’ sketches kept.
  4. Blocks reached only through zero-amount inputs have weight 0 and are skipped (§6.2), so they are in the sets support and in no weighted sketch.

The weighted similarity has a natural plug-in, (1−TV̂)/(1+TV̂)(1 - \widehat{\mathrm{TV}})/(1 + \widehat{\mathrm{TV}}) of the two sketches (JwJ_w is a function of TV, §10.6), and it is biased low. With Qx,QyQ_x, Q_y the two sketches, min⁡\min is concave, so by Jensen, block by block,

𝔼[min⁡(Qx(b),Qy(b))]≤min⁡(𝔼Qx(b),𝔼Qy(b))=min⁡(xb,yb). \mathbb{E}\big[\min(Q_x(b), Q_y(b))\big] \le \min\big(\mathbb{E} Q_x(b), \mathbb{E} Q_y(b)\big) = \min(x_b, y_b).

The sum of minima, 1−TV̂1 - \widehat{\mathrm{TV}}, is biased low, and TV̂\widehat{\mathrm{TV}} high. That alone does not sign the bias of the plug-in, a convex function of TV̂\widehat{\mathrm{TV}}; what does is the size of the loss on the light blocks. Heavy blocks are exact; a light block shared by two independent reductions is kept by both with probability (xb/τx)(yb/τy)(x_b/\tau_x)(y_b/\tau_y) and then counts min⁡(τx,τy)\min(\tau_x, \tau_y), so it contributes about xbyb/max⁡(τx,τy)x_b y_b / \max(\tau_x, \tau_y), far less than min⁡(xb,yb)\min(x_b, y_b), and the plug-in came out low in every stratum measured (§10.9). Within one run the two sketches share the reductions of their common ancestors, so the bias depends on how many fresh reductions separate a pair from its common ancestry, and it grows with depth. Measured:

  • Two independent varopt sketches (k=512k = 512, seeds 1 and 2) of the same colour give a plug-in JwJ_w with mean 0.963 and minimum 0, against the truth 1 (a design-phase prototype on the colours of the first 2M records, not a crate run).
  • On pairs of reduced colours with Jw∈[0.1,0.5)J_w \in [0.1, 0.5), the bias of the same-run plug-in grows from −0.014-0.014 over records 0–1M to −0.079-0.079 over 1–1.5M and −0.111-0.111 over 1.5–2M (same prototype).
  • On the prefix runs of §10.9 the same-run plug-in of varopt:512 underestimates JwJ_w by 0.171 on average over the 32,640 pairs of the window selection (mean 0.029 against 0.200), by 0.268 for Jw∈[0.2,0.5)J_w \in [0.2, 0.5) and by 0.430 for Jw∈[0.5,0.9)J_w \in [0.5, 0.9) (the table of weighted errors in §10.9, from the jw-strata.tsv of sketch pairs-stats, whose strata, weighted by their pairs, give the overall mean).

The plug-in is therefore not shipped; pairs writes it only to document this. The Wasserstein distance between two varopt sketches has no such problem. It is a metric under which each sketch is close to its colour (section 8 measures W1(Qx,x)W_1(Q_x, x): a reduction moves mass only between nearby blocks), so by the triangle inequality it is off by at most those two errors. TV is a metric too, but under TV a sketch is far from its colour, since its kept lights are carried at τ\tau: that is the bias above. W1W_1 serves below as a “temporal distance” between transactions.

10.3 A coordinated bottom-kk of the support is exact through the DAG

A word on notation, as in §6. In the rest of §10, τ\tau is a threshold on ranks, small ranks kept, as in §2 and §6.6, not the weight threshold of §6.1–6.5 and §10.2, to which §11 returns; and MM is the size of the permutation, the universe of §1.2.1.

Number the blocks 0,…,M−10, \dots, M - 1 with M=220=1,048,576>LM = 2^{20} = 1{,}048{,}576 > L, and let ρ\rho be a uniformly random permutation of [0,M)[0, M), drawn once per run and shared by every sketch: block bb has rank ρ(b)\rho(b), and the ranks are what makes the sketches coordinated. For a set of blocks SS let Kk(S)K_k(S) be its min⁡(k,∣S∣)\min(k, \lvert S \rvert) elements of smallest rank. The kmv store keeps, for every colour, Kk(St)K_k(S_t) as an ascending array of ranks and one bit, full, which says ∣St∣>k\lvert S_t \rvert > k. A sketch that is not full is the support. Throughout, SS, AA, BB are supports, which are functions of the chain alone and independent of ρ\rho.

Lemma 20 (union). For any sets S1,…,SGS_1, \dots, S_G with union SS, Kk(S)=Kk(Kk(S1)∪⋯∪Kk(SG))K_k(S) = K_k\big(K_k(S_1) \cup \dots \cup K_k(S_G)\big). Hence any tree of pairwise merges, each keeping the kk smallest ranks of its two inputs, computes Kk(S)K_k(S), in any order and grouping.

Proof. Let x∈Kk(S)x \in K_k(S), so fewer than kk elements of SS rank below xx. If x∈Six \in S_i, fewer than kk elements of Si⊆SS_i \subseteq S rank below xx, so x∈Kk(Si)x \in K_k(S_i). Hence Kk(S)⊆T⊆SK_k(S) \subseteq T \subseteq S with T=⋃iKk(Si)T = \bigcup_i K_k(S_i). For any such TT, Kk(T)=Kk(S)K_k(T) = K_k(S): if ∣S∣≤k\lvert S \rvert \le k then Kk(S)=SK_k(S) = S and T=ST = S; otherwise TT contains the kk smallest elements of SS, and every other element of TT is an element of SS ranked above all of them, so the kk smallest of TT are those. The tree: by induction on its height, a node over the leaves SiS_i, i∈Ii \in I, whose two subtrees hold the leaves I1I_1 and I2I_2, outputs

Kk(Kk(⋃i∈I1Si)∪Kk(⋃i∈I2Si))=Kk(⋃i∈ISi). K_k\Big(K_k\big(\textstyle\bigcup_{i \in I_1} S_i\big) \cup K_k\big(\bigcup_{i \in I_2} S_i\big)\Big) = K_k\big(\textstyle\bigcup_{i \in I} S_i\big).

■

Lemma 21 (subsets). If T⊆ST \subseteq S and x∈Kk(S)∩Tx \in K_k(S) \cap T, then x∈Kk(T)x \in K_k(T). In particular, for x∈Kk(A∪B)x \in K_k(A \cup B): x∈Ax \in A if and only if x∈Kk(A)x \in K_k(A).

Proof. The elements of TT ranked below xx are elements of SS ranked below xx, of which there are fewer than kk. For the second statement take T=A⊆A∪BT = A \subseteq A \cup B; the converse is Kk(A)⊆AK_k(A) \subseteq A. ■

Theorem 22 (exact through the DAG). Fold KkK_k through the driver of §7.5: a coinbase of block β\beta is {ρ(β)}\{\rho(\beta)\}, not full; a record groups its operands by parent (under pos it skips those of share 0), answers the parent’s own sketch when one group is left, and otherwise merges the groups’ sketches by capped merges, with full set when an operand is full or a merge had elements left over. Then for every record tt the stored sketch is Kk(St)K_k(S_t) (or Kk(St+)K_k(S^+_t)) and full holds if and only if ∣St∣>k\lvert S_t \rvert > k (∣St+∣>k\lvert S^+_t \rvert > k), whatever the fold order, the grouping, the repeated operands, the zero amounts and the release oracle.

Proof of Theorem 22. By induction in file order; parents come earlier, so their sketches are Kk(Spi)K_k(S_{p_i}). A coinbase is Kk({β})K_k(\{\beta\}). Operands that are the same parent are the same set, and a union is idempotent, so grouping changes nothing; one group means St=SpS_t = S_p, and the parent’s sketch is Kk(Sp)K_k(S_p). Otherwise Lemma 20 gives Kk(St)K_k(S_t). Full: if an operand is full, ∣St∣≥∣Spi∣>k\lvert S_t \rvert \ge \lvert S_{p_i} \rvert > k; if a merge had leftovers, the union below it exceeds kk. Conversely, if no operand is full, every operand is its whole support, and if no merge had leftovers the root holds the whole union, so ∣St∣≤k\lvert S_t \rvert \le k. Under sets every operand is kept, which is (5); under pos the skipped operands are exactly those outside the union defining St+S^+_t. The release oracle frees a colour after its last spender has read it and never changes which colour an input reads, and a BIP-30 duplicate displaces the older colour as in run(), the same for the support as for the colour. ■

This is Cohen’s size-estimation framework for reachability, in which min-rank sketches of the sets reachable from every node of a graph are computed by merges along its edges.Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534 Here the sets are a transaction’s ancestor blocks. So the fold has no recursion error. The sketch of a record at any depth is the one-shot bottom-kk of its support, a deterministic function of ρ\rho and StS_t, and every estimate read from it has exactly the law of a one-shot KMV estimate. This is the opposite of §6.3, where the whole difficulty was the error the recursion adds. What the records of one run do share is the permutation: their errors are correlated, and questions of bias are asked across seeds (§10.9).

The same argument gives what §5.6 and §6.6 said a coordinated merge could not have: exact weights.

Lemma 23 (kept weights). Let each sketch also store the colour weight ct(b)c_t(b) of every kept block. Then for every record tt and every b∈Kk(St)b \in K_k(S_t),

ct(b)=∑1≤i≤nb∈Kk(Spi)st,i cpi(b): c_t(b) = \sum_{\substack{1 \le i \le n \\ b \in K_k(S_{p_i})}} s_{t,i}\, c_{p_i}(b):

the child’s kept weights are computed exactly from the parents’ sketches.

Proof. ct(b)=∑i=1nst,i cpi(b)c_t(b) = \sum_{i=1}^{n} s_{t,i}\, c_{p_i}(b) by (1). A term with st,i cpi(b)>0s_{t,i}\, c_{p_i}(b) > 0 has bb in the support of CpiC_{p_i}, which is contained in Spi⊆StS_{p_i} \subseteq S_t (in Spi+⊆St+S^+_{p_i} \subseteq S^+_t under pos, since st,i>0s_{t,i} > 0), so b∈Kk(Spi)b \in K_k(S_{p_i}) by Lemma 21: every nonzero term is held by the corresponding parent’s sketch, and by induction with its exact weight. ■

Remark 24. Lemma 21 is the property coord lacks. Its rank ub/vu_b / v uses the weight, which changes from parent to child, so a block can rank below the child’s merged threshold and outside a parent’s sketch: in Example 18 block b2b_2 ranks 0.8 in DD, inside the merged threshold 0.8890.889, and 4 in AA, outside AA’s sketch, so its share from AA is unknown. Ranks that depend on the block alone keep the lemma, and so would block-level priorities ub/g(b)u_b / g(b) for any fixed function gg of the block: a sample weighted by a prior rather than by the colour, which §14 leaves open.

The exact weights were not shipped.The design-phase prototype stored them and, summing in the exact store’s order, matched the exact colour bit for bit on the kept blocks (14,219 sampled records of the first 3M, four values of kk: maximum difference 0). As an estimator of JwJ_w, though, a uniform sample of the support misses the few heavy recent blocks that hold most of the mass: the ratio ∑b∈Kmin⁡/∑b∈Kmax⁡\sum_{b \in K} \min / \sum_{b \in K} \max over the kept blocks KK was biased upward by 0.051, 0.030 and 0.015 at k=64k = 64, 256 and 1024 for pairs with Jw≥0.9J_w \ge 0.9. Weights also double the memory. §10.6 has a better tool for JwJ_w. The store keeps ranks only.

Table 12: The coordinated bottom-k of the support, as stored by the kmv store.
kmv store
ranka Fisher–Yates permutation of [0,220)[0, 2^{20}), seeded, 8 MiB of tables per seed (both directions)
why a finite permutationthe count is then exactly unbiased in the model actually run, and it can be restricted to the blocks a support can hold (§10.4)
an entry4 bytes (a u32 rank); the block is the inverse permutation of the rank
a sketchat most kk ranks plus the full bit, behind an Rc of about 40 bytes
a record of GG distinct parentsO(Gk)O(Gk) by a balanced tree of two-pointer merges, each capped at kk; one parent costs a reference-count bump
error added by the recursionnone: every sketch is the one-shot KkK_k of its support
limitblocks below 2202^{20}; a larger block is a hard error naming :bits=

10.4 Counting

Proposition 25 (KMV over a finite universe). Let VV be a set of NN blocks fixed independently of ρ\rho, S⊆VS \subseteq V with n=∣S∣n = \lvert S \rvert, and k≥2k \ge 2. If the sketch is not full, n^=∣Kk(S)∣=n\hat n = \lvert K_k(S) \rvert = n. If it is full, let RR be the number of blocks of VV ranked below the kk-th smallest rank of SS (the 0-based position of that rank among the ranks of VV). Then n^=(k−1)N/R\hat n = (k - 1) N / R satisfies 𝔼[n^]=n\mathbb{E}[\hat n] = n exactly, and (k−1)(k−2)N(N−1)/(R(R−1))(k - 1)(k - 2) N (N - 1) / (R (R - 1)) is an unbiased estimate of n(n−1)n(n - 1) for k≥3k \ge 3.

Proof. The restriction of a uniform permutation of [0,M)[0, M) to VV orders VV uniformly at random, so the positions of SS among the NN positions of VV are a uniformly random nn-subset of {0,…,N−1}\{0, \dots, N - 1\}, and RR is its kk-th smallest element. Choosing k−1k - 1 positions below rr and n−kn - k above,

Pr⁡(R=r)=(rk−1)(N−1−rn−k)/(Nn),k−1≤r≤N−n+k−1. \Pr(R = r) = \binom{r}{k-1}\binom{N-1-r}{n-k} \Big/ \binom{N}{n}, \qquad k - 1 \le r \le N - n + k - 1 .

Since k−1r(rk−1)=(r−1k−2)\frac{k-1}{r}\binom{r}{k-1} = \binom{r-1}{k-2},

𝔼[k−1R]=∑r=k−1N−n+k−1(r−1k−2)(N−1−rn−k)/(Nn)=(N−1n−1)/(Nn)=nN, \mathbb{E}\Big[\frac{k-1}{R}\Big] = \sum_{r=k-1}^{N-n+k-1} \binom{r-1}{k-2}\binom{N-1-r}{n-k} \Big/ \binom{N}{n} = \binom{N-1}{n-1} \Big/ \binom{N}{n} = \frac{n}{N},

where the middle sum counts the (n−1)(n-1)-subsets of an (N−1)(N-1)-set by the position r−1r - 1 of their (k−1)(k-1)-th smallest element. Multiplying by NN gives 𝔼[n^]=n\mathbb{E}[\hat n] = n. In the same way

(k−1)(k−2)r(r−1)(rk−1)=(r−2k−3), \frac{(k-1)(k-2)}{r(r-1)}\binom{r}{k-1} = \binom{r-2}{k-3},

and the (n−2)(n-2)-subsets of an (N−2)(N-2)-set, counted by the position r−2r - 2 of their (k−2)(k-2)-th smallest element, give

𝔼[(k−1)(k−2)R(R−1)]=∑r=k−1N−n+k−1(r−2k−3)(N−1−rn−k)/(Nn)=(N−2n−2)/(Nn)=n(n−1)N(N−1). \mathbb{E}\Big[\frac{(k-1)(k-2)}{R(R-1)}\Big] = \sum_{r=k-1}^{N-n+k-1} \binom{r-2}{k-3}\binom{N-1-r}{n-k} \Big/ \binom{N}{n} = \binom{N-2}{n-2} \Big/ \binom{N}{n} = \frac{n(n-1)}{N(N-1)} .

(R≥k−1≥1R \ge k - 1 \ge 1 throughout.) ■

Write n^V\hat n_V for this estimator. Then, for k≥3k \ge 3, n^V2−n^V−(k−1)(k−2)N(N−1)/(R(R−1))\hat n_V^2 - \hat n_V - (k-1)(k-2)N(N-1)/(R(R-1)) is an unbiased estimate of Var⁡(n^V)\operatorname{Var}(\hat n_V), since n(n−1)+n=n2n(n - 1) + n = n^2. The variance itself has no closed form, though it is a finite sum over the law of RR; it is about

Var⁡(n^V)≈n(n−k+1)k−2⋅N−nN−1, \operatorname{Var}(\hat n_V) \approx \frac{n(n - k + 1)}{k - 2} \cdot \frac{N - n}{N - 1},

the continuous-hash value of §1.2.1 times the finite-population factor (§1.2.1 writes NN for the set size and MM for the universe). The approximation slightly overstates it: summed exactly over the law of RR (a numerical summation of the theory, outside the crate), for n/N≤0.9n/N \le 0.9 the variance is below it by under 1% at k≥256k \ge 256, under 3% at k=64k = 64 and up to 11.5% at k=16k = 16. The seed tests of §10.9 check it on the chain.

The proposition leaves the universe VV free, and the choice matters. The textbook choice is the whole permutation, V=[0,M)V = [0, M), with RR the kk-th smallest rank itself: n^M=(k−1)M/R\hat n_M = (k - 1)M/R. But every block of StS_t is at most βt\beta_t, the newest block seen up to record tt (the record’s own block, on a chain read in block order), and βt\beta_t is a function of the chain, not of ρ\rho. So V=[0,βt]V = [0, \beta_t] is a valid universe with N=βt+1N = \beta_t + 1, and RtR_t, the number of blocks b≤βtb \le \beta_t ranked below the kk-th smallest rank of StS_t, gives

n^=(k−1)(βt+1)Rt, \hat n = \frac{(k - 1)(\beta_t + 1)}{R_t},

exactly unbiased as well and never above βt+1\beta_t + 1. Supports on this chain are dense in their universe: the supports of records 3,000,000 and 31,187,785 cover 70% and 84% of [0,βt][0, \beta_t], so at the latter the finite-population factor is about 0.16 where MM’s is 0.78. In the deepest stratum of the first 31.2M records (supports of 131,072 to 262,144 blocks) the theory RSE at k=1024k = 1024 is 0.0144 for n^\hat n against 0.0283 for n^M\hat n_M: half the error, the gain a kk nearly four times larger would bring. The measured RMS over 16 seeds is 0.0152 against 0.0266, 57% of the error, the gain of a kk about three times larger. RtR_t costs one query of a Fenwick tree over rank space per full record, into which the blocks are inserted as the chain’s newest block advances (§10.8). Both estimates are written; n^\hat n is the primary one.

10.5 Jaccard, containment and unions

For two transactions with supports AA and BB and sketches Kk(A)K_k(A), Kk(B)K_k(B):

Proposition 26 (Jaccard). If neither sketch is full, J(A,B)J(A, B) is computed exactly from the two stored sets. If one is, let K=Kk(Kk(A)∪Kk(B))K = K_k\big(K_k(A) \cup K_k(B)\big) and X=∣K∩Kk(A)∩Kk(B)∣X = \lvert K \cap K_k(A) \cap K_k(B) \rvert, and put J^=X/k\hat J = X / k. Then XX is hypergeometric with population nu=∣A∪B∣n_u = \lvert A \cup B \rvert, ∣A∩B∣\lvert A \cap B \rvert successes and kk draws, so 𝔼[J^]=J\mathbb{E}[\hat J] = J and

Var⁡(J^)=J(1−J)k⋅nu−knu−1≤14k. \operatorname{Var}(\hat J) = \frac{J(1 - J)}{k} \cdot \frac{n_u - k}{n_u - 1} \le \frac{1}{4k}.

Proof. A sketch that is not full is its whole support. If one is full, nu>kn_u > k, and K=Kk(A∪B)K = K_k(A \cup B) by Lemma 20; since A∪BA \cup B is fixed and ρ\rho uniform, KK is a uniformly random kk-subset of A∪BA \cup B. By Lemma 21, an element of KK is in Kk(A)K_k(A) if and only if it is in AA, and likewise for BB, so X=∣K∩A∩B∣X = \lvert K \cap A \cap B \rvert: the number of successes among kk draws without replacement. Its mean is kJk J and its variance kJ(1−J)(nu−k)/(nu−1)k J (1 - J)(n_u - k)/(n_u - 1). ■

When neither sketch is full but their union exceeds kk, the textbook formula over KK is still an estimate (it deviated by up to 0.0035 in the design-phase prototype); the exact value is in hand, so it is used. In the even selection of §10.9, 208,335 of the 499,500 pairs have both sketches whole at k=1024k = 1024 and are computed exactly; in 57 of them the union exceeds kk, where the textbook formula would have been an estimate (both counts are columns of errors.tsv from sketch pairs-stats on R3). Neither estimator uses everything: both sketches are complete below the smaller of their two thresholds, so the union is known there, with between kk and 2k2k elements, which could lower the variance for small JJ.Cohen and Kaplan’s estimators for bottom-kk sketches use such samples, which hold more than the kk smallest of the union.Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133

The union count ∣A∪B∣\lvert A \cup B \rvert is exact when neither sketch is full (the union is then in hand, whatever its size). Otherwise it is the count of K=Kk(A∪B)K = K_k(A \cup B), which the proof above has in hand, by Proposition 25 with the pair’s universe N=max⁡(βA,βB)+1N = \max(\beta_A, \beta_B) + 1: exactly unbiased. The intersection J^⋅n^u\hat J \cdot \hat n_u is a product of dependent estimates: consistent, not unbiased.

The containment of AA in BB, ∣A∩B∣/∣A∣\lvert A \cap B \rvert / \lvert A \rvert, is read from the part of AA’s sketch that BB’s sketch can vouch for. Let τB\tau_B be the kk-th smallest rank of BB when BB’s sketch is full and +∞+\infty otherwise, let T={x∈Kk(A):ρ(x)≤τB}T = \{x \in K_k(A) : \rho(x) \le \tau_B\}, and estimate the containment by ∣T∩Kk(B)∣/∣T∣\lvert T \cap K_k(B) \rvert / \lvert T \rvert. TT is the set of elements of AA ranked at most min⁡(τA,τB)\min(\tau_A, \tau_B), and for each of them membership in BB is exact, because BB’s sketch holds every element of BB up to τB\tau_B. So the estimate is a ratio over a random subset of AA whose memberships are known exactly: consistent. It is not unbiased, because τB\tau_B depends on the ranks of BB, and with them on those of A∩BA \cap B; in particular the element at τB\tau_B belongs to BB, so when τB≤τA\tau_B \le \tau_A and that element is in AA, it is a sure hit in TT. That biases the ratio up by about Pr⁡(τB≤τA) c(1−c)/k\Pr(\tau_B \le \tau_A)\, c(1 - c)/k for a containment cc: the full c(1−c)/kc(1 - c)/k when AA is smaller than BB (0.004 at k=64k = 64 in a design-phase simulation, not a crate run), about half of it when the two are the same size, and none when AA is much larger. At k=1024k = 1024 it is at most about 0.00025. With a strict threshold, ρ(x)<τB\rho(x) < \tau_B, the same simulation (20,000 permutations per case) showed no bias within its standard error. The code keeps ≤\le: at k=1024k = 1024 its bias is far below every error measured in §10.9. The estimate is undefined when TT is empty, which happens when AA is much smaller than BB: AA then has few elements below τB\tau_B, about k∣A∣/∣B∣k \lvert A \rvert / \lvert B \rvert on average. pairs writes the size of TT beside every containment, and the ratio J^n^u/n^A\hat J \hat n_u / \hat n_A as a flagged fallback.

10.6 Weighted similarity: a function of L1, and L1 has a linear sketch

The support’s sketch says nothing about weights. The weighted Jaccard similarity needs a different tool, and the shape of the colours makes it simple.

Lemma 27. For probability vectors xx and yy over the blocks 0,…,L−10, \dots, L - 1, with TV=12∥x−y∥1\mathrm{TV} = \tfrac12 \lVert x - y \rVert_1,

∑b=0L−1min⁡(xb,yb)=1−TV,∑b=0L−1max⁡(xb,yb)=1+TV, \sum_{b=0}^{L-1} \min(x_b, y_b) = 1 - \mathrm{TV}, \qquad \sum_{b=0}^{L-1} \max(x_b, y_b) = 1 + \mathrm{TV},

so

Jw(x,y)=1−TV1+TV. J_w(x, y) = \frac{1 - \mathrm{TV}}{1 + \mathrm{TV}} .

Proof. Coordinate by coordinate min⁡(xb,yb)+max⁡(xb,yb)=xb+yb\min(x_b, y_b) + \max(x_b, y_b) = x_b + y_b and max⁡(xb,yb)−min⁡(xb,yb)=∣xb−yb∣\max(x_b, y_b) - \min(x_b, y_b) = \lvert x_b - y_b \rvert. Summing over b=0,…,L−1b = 0, \dots, L - 1, the sum of minima and the sum of maxima add up to ∑b=0L−1(xb+yb)=2\sum_{b=0}^{L-1} (x_b + y_b) = 2 and differ by ∑b=0L−1∣xb−yb∣=2 TV\sum_{b=0}^{L-1} \lvert x_b - y_b \rvert = 2\,\mathrm{TV}. ■

So JwJ_w of two colours depends on their L1 distance alone, and L1 distance has a linear sketch: random projections by a 1-stable law, the Cauchy distribution.Piotr Indyk. Stable distributions, pseudorandom generators, embeddings, and data stream computation. Journal of the ACM, 53(3):307–323, 2006. doi: 10.1145/1147954.1147955. URL https://doi.org/10.1145/1147954.1147955 Let Π\Pi be an m×Mm \times M matrix of independent standard Cauchy draws Πjb\Pi_{jb}, one column per block, drawn once per run (coordinated, like ρ\rho), and let the l1 store keep v(C)=Π C∈ℝmv(C) = \Pi\,C \in \mathbb{R}^m for every colour.

Proposition 28 (the projection commutes with the recurrence). Fold vv through the driver: a coinbase of block β\beta is the column (Πjβ)j(\Pi_{j\beta})_j; a record groups its operands by parent, skipping those of share 0, with GG groups, qgq_g the parent of group gg and

s¯g=∑1≤i≤npi=qgst,i \bar s_g = \sum_{\substack{1 \le i \le n \\ p_i = q_g}} s_{t,i}

its summed share, for g=1,…,Gg = 1, \dots, G; it answers the parent’s own vector when one group is left (G=1G = 1), and otherwise stores ∑g=1Gs¯g vqg\sum_{g=1}^{G} \bar s_g\, v_{q_g}. Then in exact arithmetic vt=Π Ctv_t = \Pi\,C_t for every record tt, at any depth.

Proof. By induction in file order: a coinbase of block β\beta has the colour eβe_\beta, all its mass on β\beta, and Π eβ\Pi\,e_\beta is column β\beta; otherwise

∑g=1Gs¯g Π Cqg=Π∑i=1nst,i Cpi=Π Ct \sum_{g=1}^{G} \bar s_g\, \Pi\,C_{q_g} = \Pi \sum_{i=1}^{n} s_{t,i}\, C_{p_i} = \Pi\,C_t

by linearity, where grouping only reassociates the sum, share-0 operands contribute 0, and one group has s¯g=1\bar s_g = 1 and Ct=CqgC_t = C_{q_g}. ■

There is no reduction, no kk, no per-record randomness: the only error is floating point. The fold accumulates in f64 in group order and stores f32 (or f64); on the first 3M records the stored vector matched Π Ct\Pi\,C_t computed from the exact colour to 6.8×10−76.8 \times 10^{-7} relative in f32 and 5.7×10−145.7 \times 10^{-14} in f64 (§10.9).

For two fixed colours xx and yy, which are functions of the chain and independent of Π\Pi, the differences

dj=vj(x)−vj(y)=∑b=0M−1Πjb (xb−yb),j=1,…,m, d_j = v_j(x) - v_j(y) = \sum_{b=0}^{M-1} \Pi_{jb}\,(x_b - y_b), \qquad j = 1, \dots, m,

are independent over jj and, by 1-stability, each is Cauchy with scale σ=∥x−y∥1=2 TV\sigma = \lVert x - y \rVert_1 = 2\,\mathrm{TV}. The scale is estimated by maximum likelihood, one of the estimators of a Cauchy scale that Li, Hastie and Church compare:Ping Li, Trevor J. Hastie, and Kenneth W. Church. Nonlinear Estimators and Tail Bounds for Dimension Reduction in l1l_1 Using Cauchy Random Projections. Journal of Machine Learning Research, 8(83):2497–2532, 2007. URL https://www.jmlr.org/papers/v8/li07b.html the log-likelihood

ℓ(σ)=∑j=1m[ln⁡σ−ln⁡(σ2+dj2)] \ell(\sigma) = \sum_{j=1}^{m} \big[\ln \sigma - \ln(\sigma^2 + d_j^2)\big]

is stationary where

∑j=1mσ2σ2+dj2=m2, \sum_{j=1}^{m} \frac{\sigma^2}{\sigma^2 + d_j^2} = \frac{m}{2},

whose left side increases from the number of zero djd_j to mm, so the root σ^\hat\sigma is unique (and σ^=0\hat\sigma = 0 when at least half the djd_j are 0, as for equal colours). The Fisher information of a Cauchy scale is 1/(2σ2)1/(2\sigma^2) per observation, so σ^\hat\sigma has relative SD about 2/m\sqrt{2/m}: 0.0625 at m=512m = 512, 0.0442 at m=1024m = 1024. The estimates are

TV̂=σ^2,J^w=1−min⁡(TV̂,1)1+min⁡(TV̂,1), \widehat{\mathrm{TV}} = \frac{\hat\sigma}{2}, \qquad \hat J_w = \frac{1 - \min(\widehat{\mathrm{TV}}, 1)}{1 + \min(\widehat{\mathrm{TV}}, 1)},

whose SD is, by the delta method, about 2 TV/(1+TV)2⋅2/m2\,\mathrm{TV}/(1 + \mathrm{TV})^2 \cdot \sqrt{2/m}, at most 122/m\tfrac12\sqrt{2/m} (0.022 at m=1024m = 1024). The mean of ∣dj∣\lvert d_j \rvert would be the obvious estimator and has no expectation at all; the median is consistent but has relative SD π/(2m)\pi/(2\sqrt m), 11% more than the MLE.

The clipping leaves a floor. For disjoint colours (TV=1\mathrm{TV} = 1, Jw=0J_w = 0), TV̂≈1+ε\widehat{\mathrm{TV}} \approx 1 + \varepsilon with ε\varepsilon about normal with SD 2/m\sqrt{2/m}, and J^w≈max⁡(−ε,0)/2\hat J_w \approx \max(-\varepsilon, 0)/2, whose mean is

𝔼[J^w]≈2/m22π: \mathbb{E}[\hat J_w] \approx \frac{\sqrt{2/m}}{2\sqrt{2\pi}} :

0.0176, 0.0125 and 0.0088 at m=256m = 256, 512 and 1024. Pairs with JwJ_w below a few hundredths cannot be resolved one by one; the unclipped TV̂\widehat{\mathrm{TV}} is written beside J^w\hat J_w for averages over many pairs. On the prefix, where the median JwJ_w of deep pairs across time is 1.4×10−41.4 \times 10^{-4} (§10.1), a weighted map would show only the floor. Over the whole chain it would not (§10.10: only a fifth of the pairs lie below the floor), but there the maps are drawn for windows of a few blocks, where JJ is near 1 and JwJ_w is what tells transactions apart.

Why a linear sketch and not a weighted MinHash? Consistent weighted samplingMark Manasse, Frank McSherry, and Kunal Talwar. Consistent Weighted Sampling. Technical Report MSR-TR-2010-73, Microsoft Research, June 2010. URL https://www.microsoft.com/en-us/research/publication/consistent-weighted-sampling/; and Sergey Ioffe. Improved Consistent Sampling, Weighted Minhash and L1 Sketching. In 2010 IEEE International Conference on Data Mining, pages 246–255. IEEE, 2010. doi: 10.1109/ICDM.2010.80. URL https://doi.org/10.1109/ICDM.2010.80 and P-MinHash, the sampler of Moulton and Jiang,Ryan Moulton and Yunjiang Jiang. Maximally Consistent Sampling and the Jaccard Index of Probability Distributions. In 2018 IEEE International Conference on Data Mining (ICDM), pages 347–356. IEEE, 2018. doi: 10.1109/ICDM.2018.00050. URL https://doi.org/10.1109/ICDM.2018.00050 make two vectors' samples collide with a probability equal to a weighted similarity, and their samples are coordinated, as coord’s are. But a colour is a sum of its parents’ colours, and for the simplest of these samplers no merge exists.

Proposition 29 (no merge under sums, for priority ranks). Let the sample of a nonnegative vector xx be sk(x)=(b∗,rb∗)\mathrm{sk}(x) = (b^*, r_{b^*}), with ranks rb=Eb/xbr_b = E_b / x_b (+∞+\infty when xb=0x_b = 0) and b∗=arg⁡min⁡brbb^* = \arg\min_b r_b, where the EbE_b are independent and identically distributed with a positive density on an interval (0,c)(0, c): exponential for P-MinHash, uniform for priority sampling and for coord’s ub/vu_b / v. Then no function ff satisfies

sk(12x+12y)=f(sk(x),sk(y)) \mathrm{sk}\big(\tfrac12 x + \tfrac12 y\big) = f\big(\mathrm{sk}(x), \mathrm{sk}(y)\big)

almost surely for all probability vectors x,yx, y.

Proof. Over four blocks take x=(12,12,0,0)x = (\tfrac12, \tfrac12, 0, 0), x′=(12,0,0,12)x' = (\tfrac12, 0, 0, \tfrac12) and y=(0,12,12,0)y = (0, \tfrac12, \tfrac12, 0), and the event E1<E2E_1 < E_2, E1<E4E_1 < E_4, E3<E2E_3 < E_2, E2<2min⁡(E1,E3)E_2 < 2\min(E_1, E_3), which has positive probability (it is open and holds at E∝(1,1.5,1.1,2)E \propto (1, 1.5, 1.1, 2), scaled into (0,c)(0, c)). On it sk(x)=sk(x′)=(1,2E1)\mathrm{sk}(x) = \mathrm{sk}(x') = (1, 2E_1) and sk(y)=(3,2E3)\mathrm{sk}(y) = (3, 2E_3). But 12(x+y)=(14,12,14,0)\tfrac12(x + y) = (\tfrac14, \tfrac12, \tfrac14, 0) has ranks (4E1,2E2,4E3,∞)(4E_1, 2E_2, 4E_3, \infty) and sample block 2, while 12(x′+y)=(14,14,14,14)\tfrac12(x' + y) = (\tfrac14, \tfrac14, \tfrac14, \tfrac14) has ranks 4Eb4E_b and a sample block other than 2, since E1<E2E_1 < E_2. The same inputs to ff require two different outputs. ■

Samples of kk follow on the same event intersected with one on which k−1k - 1 further blocks, shared by all three vectors, have ranks small enough to fill the first k−1k - 1 places. The proposition is about this class only, ranks Eb/xbE_b / x_b; consistent weighted sampling as Ioffe defines it ranks by a randomised step function of xbx_b, also nonincreasing in xbx_b, and is not covered by the proof. The same samplers do compose under the coordinate-wise maximum: the rank of bb in max⁡(x,y)\max(x, y) is Eb/max⁡(xb,yb)=min⁡(Eb/xb,Eb/yb)E_b / \max(x_b, y_b) = \min(E_b/x_b, E_b/y_b), so the bottom-kk of max⁡(x,y)\max(x, y) is the bottom-kk of the two samples merged. A union is a maximum of indicator vectors, and the support of a positive mixture is the support of the maximum, which is why the KMV of the support folds exactly and the weighted samples do not. Linearity is what survives the sum. Weighted sampling under sums is possible too, but only from a linear sketch. An L1L_1 sampler draws a block with probability about xb/∥x∥1x_b / \lVert x \rVert_1 from a linear sketch of xx, so it folds through the recurrence as Π\Pi does.Hossein Jowhari, Mert Sağlam, and Gábor Tardos. Tight bounds for Lp samplers, finding duplicates in streams, and related problems. In Proceedings of the 30th ACM SIGMOD-SIGACT-SIGART Symposium on Principles of Database Systems, PODS '11, pages 49–58. Association for Computing Machinery, 2011. doi: 10.1145/1989284.1989289. URL https://doi.org/10.1145/1989284.1989289 Two such samplers, however, do not collide with probability JwJ_w, and for JwJ_w the L1 distance is all that is needed.

10.7 Other similarities from the same sketches

Jaccard similarity and JwJ_w are two of many ways to say how much two transactions share, and the three stores already written answer several others with no new fold. sketch pairs-stats computes them from the outputs of pairs (§10.8): against the exact values, where there are any, in similarity.tsv, and as quantiles in similarity-quantiles.tsv.

Set similarities. Every classical similarity of two sets is a function of their sizes nA=∣A∣n_A = \lvert A \rvert, nB=∣B∣n_B = \lvert B \rvert and of their intersection I=∣A∩B∣I = \lvert A \cap B \rvert:

Dice(A,B)=2InA+nB=2J1+J,cosine(A,B)=InA nB,overlap(A,B)=Imin⁡(nA,nB),Kulczynski(A,B)=12(InA+InB),∣A△B∣=nA+nB−2I=(1−J) ∣A∪B∣, \begin{aligned} \text{Dice}(A, B) &= \frac{2I}{n_A + n_B} = \frac{2J}{1 + J}, & \text{cosine}(A, B) &= \frac{I}{\sqrt{n_A\, n_B}}, \\ \text{overlap}(A, B) &= \frac{I}{\min(n_A, n_B)}, & \text{Kulczynski}(A, B) &= \frac12 \Big( \frac{I}{n_A} + \frac{I}{n_B} \Big), \\ \lvert A \mathbin{\triangle} B \rvert &= n_A + n_B - 2I = (1 - J)\,\lvert A \cup B \rvert , \end{aligned}

the Sørensen–Dice coefficient, the cosine (Ochiai) coefficient, the overlap (Szymkiewicz–Simpson) coefficient, Kulczynski’s and the symmetric difference. Here AA and BB are the supports of two transactions, the blocks their coins descend from (§10.1), and the four ratios are best read through the two containments cA=I/nAc_A = I/n_A, the share of AA’s ancestry that BB shares, and cB=I/nBc_B = I/n_B. Dice is their harmonic mean, cosine their geometric mean, Kulczynski their arithmetic mean and the overlap the larger of the two, so for every pair

J≤Dice≤cosine≤Kulczynski≤overlap, J \le \text{Dice} \le \text{cosine} \le \text{Kulczynski} \le \text{overlap},

with equality throughout when the two supports have the same size. They differ only in how they treat a pair of unequal ancestries, and on this chain that is the common case: an old transaction descends from few blocks, a new one from most of the past.

  • Dice counts the shared blocks twice against the two sizes added, where Jaccard counts them once against the union. It ranks every pair as JJ does and says nothing JJ does not; it is the scale on which much of the literature reports overlap.
  • Cosine is the geometric mean of the two containments. A small ancestry wholly inside a large one has J=nA/nBJ = n_A/n_B but cosine nA/nB\sqrt{n_A/n_B}: it penalises the difference in size less than Jaccard and Dice do.
  • Kulczynski is the plain average of the two containments: how much of AA’s ancestry is shared, and how much of BB’s, weighted alike whatever their sizes.
  • The overlap asks only whether the smaller ancestry lies inside the larger. It is 1 when every block the smaller one descends from is also an ancestor of the larger, however much more the larger has. For an older and a newer transaction it says whether the older one’s sources are all among the newer one’s.
  • The symmetric difference is a count, not a ratio: the number of blocks that are in one ancestry and not in the other, the Hamming distance between the two supports read as bit vectors over the blocks. It says how many minting blocks separate two transactions, where the ratios say what share.

The kmv store estimates all three numbers: the counts by Proposition 25, the intersection as I^=J^ n^u\hat I = \hat J\, \hat n_u (§10.5). Dice is a function of JJ alone, 2J^/(1+J^)2\hat J/(1 + \hat J), and inherits its accuracy: the derivative 2/(1+J)22/(1 + J)^2 is at most 2, and below 1 where JJ is above 0.42. The others are ratios of dependent estimates, as the intersection is: consistent, not unbiased, and clipped to [0,1][0, 1] where they are bounded. The overlap is also the containment of the smaller support in the larger, and read that way (§10.5, the smaller side by its estimated count) its memberships are exact. The symmetric difference counts the elements outside the intersection, and the bottom-kk of the union holds about k(1−J)k(1 - J) of them, so its relative error is about 1/k(1−J)1/\sqrt{k(1 - J)}: fine for supports far apart, useless for near-copies.

Measured on the prefix, with R3’s 16 seeds at k=1024k = 1024 as the unit of the bias test (the runs of §10.9):

measuredeep: meanbiasRMSwindow: meanbiasRMS
Dice, 2J^/(1+J^)2\hat J/(1 + \hat J)0.375+0.0003+0.00030.0120.981−0.0003-0.00030.0029
cosine0.453+0.0003+0.00030.0230.982−0.0002-0.00020.0039
Kulczynski0.628−0.0001-0.00010.0590.983−0.0002-0.00020.0039
overlap, I^/min⁡(n^A,n^B)\hat I / \min(\hat n_A, \hat n_B)0.962−𝟎.𝟎𝟑𝟒\mathbf{-0.034}0.0780.9999−𝟎.𝟎𝟎𝟎𝟗\mathbf{-0.0009}0.0028
overlap, as the smaller side’s containment0.962−0.0001-0.00010.00550.9999+0.00002+0.000020.00017
symmetric difference, relative44,932−0.3%-0.3\%6.5%4,264−𝟏𝟑%\mathbf{-13\%}60%
Bray–Curtis =min⁡(TV̂,1)= \min(\widehat{\mathrm{TV}}, 1), Jw≥0.01J_w \ge 0.010.890−0.003-0.0030.0340.656+0.004+0.0040.029
Bray–Curtis, Jw<0.01J_w < 0.010.998−𝟎.𝟎𝟏𝟔\mathbf{-0.016}0.0300.994−0.016-0.0160.032
Table 13: Other similarities from the same sketches, on the prefix: the mean exact value, the bias (mean over seeds of each seed’s mean error) and the RMS error, for the deep pairs (32,385) and the window pairs (32,640). Set measures from kmv:1024, sets, 16 seeds; Bray–Curtis from l1:1024, f32, 8 seeds. In bold, a bias beyond the two-sided Bonferroni threshold at 1% family-wise over the strata tested (t of 3.6 to 3.8 for the KMV rows, 5.2 for the L1 ones). From similarity.tsv of sketch pairs-stats on R3 (crate adfe031); the Bray–Curtis rows pool the J_w strata of that file, weighted by their pairs.

Dice, cosine and Kulczynski show no bias in any stratum of JJ, and their RMS is that of J^\hat J carried through their formulas. The overlap computed from the counts is biased low, by 0.034 on deep and by 0.075 in its stratum J≤0.05J \le 0.05: the true overlap is near 1, because an older support lies mostly inside a newer one, and the noise above 1 is clipped away. Read as the containment of the smaller support it shows no bias and an RMS of 0.0055, a fourteenth of the other, and it is the one to use. The symmetric difference is within 0.3% on deep, and fails inside the window, where JJ is near 1: 13% low, with an RMS of 60% (66% in the stratum J>0.9J > 0.9).

Over the whole chain (R7, kmv:1024, seed 1, §10.10) inside each window the medians of Dice, cosine and Kulczynski are 0.999, and the overlap is estimated at exactly 1 for at least 99.96% of the pairs: every sampled block of the smaller support is in the larger one. Across the chain selection the medians are 0.65 (Dice), 0.70 (cosine) and 0.74 (Kulczynski), and the overlap is exactly 1 for 99.3% of the pairs where it is defined; 1,025 of the 130,816 are not, the cells where the containment is not.

Weighted similarities that are TV. For two distributions xx and yy over the blocks, the Bray–Curtis dissimilarity is TV itself, since both sum to one,

∑b=0L−1∣xb−yb∣∑b=0L−1(xb+yb)=TV(x,y), \frac{\sum_{b=0}^{L-1} \lvert x_b - y_b \rvert}{\sum_{b=0}^{L-1} (x_b + y_b)} = \mathrm{TV}(x, y),

and the histogram intersection ∑b=0L−1min⁡(xb,yb)\sum_{b=0}^{L-1} \min(x_b, y_b), Czekanowski’s index and the weighted Sørensen index are all 1−TV1 - \mathrm{TV} (Lemma 27). Read on two colours, TV is the share of value that would have to be moved from one minting block to another to turn one colour into the other, however far it moves; and 1−TV1 - \mathrm{TV} is the share of value the two have in common block by block, the part of each transaction’s value that could be the same minted coins in the other’s. They answer the question of Jw=(1−TV)/(1+TV)J_w = (1 - \mathrm{TV})/(1 + \mathrm{TV}) on a different scale: 1−TV1 - \mathrm{TV} is always at least JwJ_w, and the median JwJ_w of 0.21 of the whole-chain pairs (§10.1) is a common share of 0.35. The l1 store answers them as it answers JwJ_w, from TV̂\widehat{\mathrm{TV}}, and with the same floor: in Table 13, min⁡(TV̂,1)\min(\widehat{\mathrm{TV}}, 1) is within 0.004 where Jw≥0.01J_w \ge 0.01 and 0.016 low where Jw<0.01J_w < 0.01, which is the floor of §10.6, 2×0.00882 \times 0.0088, seen from the other side.

Distances between the VarOpt sketches. Every varopt sketch’s CDF is close to its colour’s: Corollary 12 bounds the error at every cut, and section 8 measures the KS distance itself. So a distance between CDFs on the block axis is close too: KS is a metric, and by the triangle inequality the KS distance between two sketches is off by at most the sum of their own KS distances to their colours, as W1W_1 is (§10.2), and unlike TV. The two read the colours along the chain’s time axis. KS is the largest difference, over every block height xx, between the shares of the two transactions’ value minted at or before xx: at the point of the chain’s history where they differ most, how much more of one’s value is older than that point than of the other’s. W1W_1 is the area between the two CDFs, in blocks: how far in time, on average, value would have to move to turn one colour into the other, and when one colour is older than the other at every height, the difference of their mean blocks. TV and 1−TV1 - \mathrm{TV} treat a block a day away and a block ten years away alike; KS and W1W_1 do not. pairs writes KS beside W1W_1: over the whole chain its median is 0.56 across the chain selection and 0.06 to 0.13 inside the windows. pairs does not compute the exact KS of two colours, so it is not checked here.

What would need a new store. The Euclidean distance, the inner product and the cosine of two colours need Gaussian projections in place of Cauchy ones, 2-stable rather than 1-stable,Piotr Indyk. Stable distributions, pseudorandom generators, embeddings, and data stream computation. Journal of the ACM, 53(3):307–323, 2006. doi: 10.1145/1147954.1147955. URL https://doi.org/10.1145/1147954.1147955 linear like Π\Pi and folded the same way. The Jensen–Shannon divergence H(12(x+y))−12(H(x)+H(y))H\big(\tfrac12(x + y)\big) - \tfrac12\big(H(x) + H(y)\big) could come from the maximally skewed stable projections that Clifford and Cosma use to estimate entropy, since the midpoint is linear.Peter Clifford and Ioana Cosma. A simple sketching algorithm for entropy estimation over streaming data. In Proceedings of the Sixteenth International Conference on Artificial Intelligence and Statistics, Proceedings of Machine Learning Research, volume 31, pages 196–206. PMLR, 2013. URL https://proceedings.mlr.press/v31/clifford13a.html Neither was built (§14). The Hellinger distance and the Kullback–Leibler divergence are not linear in the colour, and no linear sketch folds them.

10.8 Implementation

Both stores are Algebras of their own, each on its own thread and fed by the same parse as every other store (§7.10); the SKETCH01 format, the production file and the varopt code are untouched, and the old modes write byte-identical output. That was checked during the implementation against two references: the build of the commit before the stores (f09847c), on emit, decode, eval, chain, check and the first 300 MB of the production file’s decode; and the binary of the section-8 sweep, on chain, an emit of 1M records and the first 1,000,000 records of the production file’s decode. With the final binary, the one of every run below, the emit and eval checks were repeated.

The permutation is a Fisher–Yates shuffleDonald E. Knuth. The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, Massachusetts, 3rd edition, 1997. ISBN 0201896842. URL https://www-cs-faculty.stanford.edu/~knuth/taocp.html driven by the hash of §7.4, built once per seed and shared by every store of that seed:

pub fn new(seed: u64, bits: u32) -> Perm {
    // …
    let m = 1usize << bits;
    let mut fwd: Box<[u32]> = (0..m as u32).collect();
    for i in (1..m).rev() {
        let j = (h3(seed, SALT_KMV, i as u64, 0) % (i as u64 + 1)) as usize;
        fwd.swap(i, j);
    }
    let mut inv = vec![0u32; m].into_boxed_slice();
    for (b, &r) in fwd.iter().enumerate() {
        inv[r as usize] = b as u32;
    }
    Perm { bits, seed, fwd, inv }
}

The modulo bias of each swap is below M/264M / 2^{64}. A Feistel network would also be a bijection and needs no table, but even with ideal round functions it is not a uniform permutation, and both counts of §10.4 are proved exactly unbiased under one; Fisher–Yates with ideal swaps is exactly uniform.

The capped merge of two ascending runs of ranks stops as soon as it holds kk:

/// `K_k(a u b)` of two ascending runs into `out` (cleared first), equal ranks
/// once; answers whether anything was left over, i.e. whether the union has
/// more than `k` elements.  It stops as soon as `out` holds `k`.
pub fn merge_cap(a: &[u32], b: &[u32], k: usize, out: &mut Vec<u32>) -> bool {
    out.clear();
    out.reserve(k.min(a.len() + b.len()));
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        if out.len() == k {
            return true;
        }
        let (x, y) = (a[i], b[j]);
        if x < y {
            out.push(x);
            i += 1;
        } else if y < x {
            out.push(y);
            j += 1;
        } else {
            out.push(x);
            i += 1;
            j += 1;
        }
    }
    let rest = if i < a.len() { &a[i..] } else { &b[j..] };
    let room = k - out.len();
    if rest.len() > room {
        out.extend_from_slice(&rest[..room]);
        true
    } else {
        out.extend_from_slice(rest);
        false
    }
}

and a record is Theorem 22 in code. union_cap runs a balanced tree of merge_caps, or a heap from 2,048 groups on; supports here are nested, so the parents’ sketches nearly coincide and the heap, which pops every duplicate, was slower than the tree below that (a benchmark during the implementation, over the first 15M records at k=1024k = 1024: 106 s of store time with a heap from 3 groups, 26–28 s with the tree).

fn record(&mut self, ops: &[(KHandle, f64)], rec: u64) -> KHandle {
    self.group(ops);
    assert!(!self.groups.is_empty(), "record {} has no operand with a say in its support", rec);
    if self.groups.len() == 1 {
        // The union of one set with itself: the parent's own sketch.
        return Rc::clone(&ops[self.groups[0]].0);
    }
    let groups = &self.groups;
    let any_full = groups.iter().any(|&i| ops[i].0.full);
    let k = self.spec.k;
    let cut = union_cap(groups.len(), |g| &ops[groups[g]].0.r, k, &mut self.out, &mut self.scratch);
    if cut {
        self.work.reductions += 1;
    }
    let full = any_full || cut;
    debug_assert!(self.out.len() <= k && (!full || self.out.len() == k));
    Kmv::new(self.out.as_slice().into(), full)
}

group collects the operands by Rc pointer, as Sketcher::group does (§7.6), and under pos skips those of share 0. The restricted rank RtR_t of §10.4 comes from a Fenwick tree over rank space, grown block by block as the chain’s newest block advances, so a whole run costs one insertion per block and one query per full record:

pub fn grow(&mut self, n: u64) {
    while self.n < n {
        let r = self.perm.rank(u32::try_from(self.n).expect("a block id fits in a u32")) as usize;
        let mut i = r + 1;
        while i < self.tree.len() {
            self.tree[i] += 1;
            i += i & i.wrapping_neg();
        }
        self.n += 1;
    }
}

/// How many inserted blocks rank strictly below `r`.
#[inline]
pub fn below(&self, r: u32) -> u64 {
    let mut i = r as usize;
    let mut s = 0u64;
    while i > 0 {
        s += self.tree[i] as u64;
        i &= i - 1;
    }
    s
}

// …

#[inline]
pub fn count_full(k: usize, n_univ: u64, below: u64) -> f64 {
    (k as f64 - 1.0) * n_univ as f64 / below.max(1) as f64
}

All pair estimates come from one merge walk over the two sketches, which reads membership off each side (Lemma 21), counts the first kk distinct ranks for the Jaccard similarity, and every rank for the containments:

pub fn pair_raw(a: View, b: View, k: usize) -> PairRaw {
    let exact = !a.full && !b.full;
    let (ta, tb) = (a.rk().unwrap_or(u32::MAX), b.rk().unwrap_or(u32::MAX));
    let mut p = PairRaw { exact, ..PairRaw::default() };
    let (mut i, mut j) = (0, 0);
    let mut taken = 0usize;
    while i < a.r.len() || j < b.r.len() {
        // … the next rank `v` of the union, and whether it is in `a` and in `b`
        if exact || taken < k {
            taken += 1;
            p.union += 1;
            if in_a && in_b {
                p.inter += 1;
            }
            if !exact && taken == k {
                p.union_rk = Some(v);
            }
        }
        if in_a && v <= tb {
            p.t_ab += 1;
            p.hit_ab += in_b as u64;
        }
        if in_b && v <= ta {
            p.t_ba += 1;
            p.hit_ba += in_a as u64;
        }
    }
    // …
    p
}

pair_est turns these into J^\hat J (inter / union when exact, inter / k otherwise), its hypergeometric SE, the intersection and the two containments, NaN when their sample is empty.

The l1 store’s record is the sum of Proposition 28, with the shares of repeated parents added first:

fn record(&mut self, ops: &[(LHandle, f64)], rec: u64) -> LHandle {
    self.group(ops);
    assert!(!self.groups.is_empty(), "record {} has no operand with a positive share", rec);
    if self.groups.len() == 1 {
        return Rc::clone(&ops[self.groups[0].0].0);
    }
    self.acc.iter_mut().for_each(|a| *a = 0.0);
    for &(i, s) in &self.groups {
        match &*ops[i].0 {
            Vector::F32(v) => {
                for (a, &x) in self.acc.iter_mut().zip(v.iter()) {
                    *a += s * x as f64;
                }
            }
            Vector::F64(v) => {
                for (a, &x) in self.acc.iter_mut().zip(v.iter()) {
                    *a += s * x;
                }
            }
        }
    }
    stored(&self.acc, self.spec.prec)
}

A coinbase is mm draws tan(pi (u - 1/2)) with u = unit(h3(seed, SALT_L1, b, j)), always finite since unit is strictly inside (0,1)(0, 1) (§7.4). The scale MLE solves its equation by Newton’s method on ln⁡σ\ln \sigma, started at the median of ∣dj∣\lvert d_j \rvert and safeguarded by a bisection bracket, so heavy Cauchy tails cannot throw it off:

pub fn cauchy_scale_mle(d: &[f64]) -> f64 {
    let m = d.len();
    // …
    let half = m as f64 / 2.0;
    let mut a: Vec<f64> = d.iter().map(|x| if x.is_finite() { x.abs() } else { f64::INFINITY }).collect();
    let zeros = a.iter().filter(|&&x| x == 0.0).count();
    if zeros as f64 >= half {
        return 0.0;
    }
    let mid = a.len() / 2;
    let med = *a.select_nth_unstable_by(mid, |x, y| x.total_cmp(y)).1;
    // f(t) = sum 1/(1 + (a/s)^2) - m/2, f'(t) = sum 2 q (1 - q).
    let f = |t: f64| -> (f64, f64) {
        let inv = (-t).exp();
        let (mut v, mut dv) = (0.0f64, 0.0f64);
        for &x in &a {
            let r = x * inv;
            let q = 1.0 / (1.0 + r * r);
            v += q;
            dv += 2.0 * q * (1.0 - q);
        }
        (v - half, dv)
    };
    // … t = ln med; a bracket [lo, hi] with f(lo) < 0 < f(hi)
    for _ in 0..200 {
        let (v, dv) = f(t);
        if v == 0.0 {
            break;
        }
        if v < 0.0 {
            lo = t;
        } else {
            hi = t;
        }
        let mut next = t - v / dv;
        if !(dv > 0.0) || !(next > lo && next < hi) {
            next = 0.5 * (lo + hi);
        }
        let done = (next - t).abs() <= 1e-12 || (hi - lo) <= 1e-12;
        t = next;
        if done {
            break;
        }
    }
    t.exp()
}

Modes. Three modes use the stores, eval and decode learn them, and three more read what they wrote, with no fold:

  • count folds one store per --kmv and writes every record’s count as a fixed-width stream, comparing as it goes with the exact sizes of --sets-counts where they exist. A whole sketch whose length is not the exact size, a full sketch of a support of at most kk, or a whole sketch of a larger one fails the run. It folds no colour, so it costs the parse and a capped merge per record.
  • pick folds any stores once (--config, --kmv, --l1, and the exact store with --exact on a prefix) and dumps the sketches of the records listed in a selection file. Which records are worth comparing (deep ones, a window, an even spread) is known only after a count run, so selection is a second pass (select, below), and sketches of every record are never stored: at k=1024k = 1024 they would be about 3.2 TB.
  • pairs reads a pick directory and computes every pair of each group, by every measure it finds, with the exact values beside them when the exact store was dumped; it writes a long table and a square matrix per group and measure, byte-identical at any thread count.
  • eval --kmv/--l1 checks the sketches against the exact store on a prefix, and decode reads a count stream; with --select it cuts the records of a selection out of a SKETCH01 file, which is how the production varopt sketches of selected records are read without a new fold.
  • select reads a count stream and writes the selection file that pick --select reads: select prefix the deep, window and even groups of §10.9 from a prefix’s stream and the exact sizes, select chain the four groups of §10.10 from the whole stream. It replaced the Python script that made the selections of R3 and R5, and writes the same two selection files byte for byte, in about 40 s where the script took 56 min on the whole stream (wall times).
  • summary reads stored count streams back, several of one run in lock-step, and writes what a whole-chain count is judged by once no reference is left: per stream and per range or bucket of records, the counts and their quantiles (beside the exact ones where --sets-counts reaches), the records counted exactly, the relative standard error se / n_hat, and the seeds against each other (§10.10, §10.11).
  • pairs-stats reads one or more pairs outputs over the same rows, pooling their seeds, and reduces them to the bias, variance, agreement and quantile tables of §10.9 and §10.10, seeds as the unit, and to the other similarities of §10.7 (similarity.tsv, similarity-quantiles.tsv).

On the whole chain the exact colours exist only binned, in colors.bands1024.zst, and three commands read them for a selection: pick --bands-ref copies the selected records' lines of that file beside the fold, pairs --bands adds each pair’s binned TV, an exact lower bound on the TV the L1 store estimates, and checks the L1 estimates against it (§10.10), and describe compares the production varopt sketches that decode --select cut out with their binned colours (§11).

The count stream (kmv.rs):

header (48 B): "KMVCNT01" | u32 version=1 | u32 k | u64 seed | u8 support (0 sets, 1 pos)
               | u8 bits | u16 0 | u32 0 | u64 M | u64 0
record (20 B): u64 tx | u32 block | u32 m | u32 rk
               m  = len, with bit 31 set when full
               rk = the 0-based k-th smallest rank when full, else 0
trailer:       "KMVEND01" | u64 records | u64 sum of (tx ^ m ^ (rk << 32)), wrapping

Record ii is at byte 48+20i48 + 20i; its field m is the sketch’s length, not the dimension mm of §10.6. Both counts are lossless from it: the header’s seed and bits rebuild the permutation, and the running maximum of block is the universe of §10.4.

The commands that were run ($K and $L are lists of --kmv and --l1 specs):

# R1 and R2, concurrently: k = 64, 256, 1024 at seeds 1..16
K=""; for k in 64 256 1024; do for s in $(seq 1 16); do K="$K --kmv $k:seed=$s"; done; done
sketch eval $K --kmv 1024:support=pos --l1 512 --l1 1024 --l1 1024:prec=f64 \
  --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --oracle lastspend-2022.u32 \
  --limit 3000000 --every 97 --l1-every 997 --metric-threads 32 --out R1-eval3m --stats < finalBCUTXO_2022.scm
sketch count $K --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --oracle lastspend-2022.u32 \
  --limit 31187785 --every 97 --zstd --out R2-count31m --stats < finalBCUTXO_2022.scm

# R3: the prefix selections from R2's seed-1 stream, one fold with the exact store, then all pairs
#   $K: k = 1024 at seeds 1..16, k = 128, 512, 2048 at seeds 1..4
#   $L: m = 1024 at seeds 1..8, m = 256, 512 at seeds 1..4
sketch select prefix --counts R2-count31m/counts.kmv-k1024-s1-sets.bin.zst \
  --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --limit 3000000 --out sel
sketch pick --select sel/prefix.txt --config varopt:512 $K --kmv 1024:support=pos $L --l1 1024:prec=f64 \
  --exact --oracle lastspend-2022.u32 --limit 3000000 --out R3-pick3m --stats < finalBCUTXO_2022.scm
sketch pairs --in R3-pick3m --out R3-pairs3m --threads 64
# R3b: more seeds on the same selection (k = 1024 seeds 17..64, k = 128, 512, 2048 seeds 5..16),
#   no exact fold: pairs reuses R3's exact.bin

# R4: the whole chain
sketch count --kmv 1024 --kmv 1024:seed=2 --kmv 1024:seed=3 --kmv 256 --kmv 1024:support=pos \
  --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --oracle lastspend-2022.u32 \
  --limit all --every 4001 --zstd --out R4-countall --stats < finalBCUTXO_2022.scm

# R5 to R7: the whole-chain selections from R4's seed-1 stream, one fold, the production
# varopt sketches of the same records, and all pairs
sketch select chain --counts R4-countall/counts.kmv-k1024-s1-sets.bin.zst --out sel
sketch pick --select sel/chain.txt --kmv 1024 --kmv 1024:seed=2 --kmv 1024:seed=3 \
  --l1 1024 --l1 1024:prec=f64 --l1 512:seed=2 --kmv 1024:support=pos \
  --oracle lastspend-2022.u32 --limit all --out R5-pickall --stats < finalBCUTXO_2022.scm
# (--long=27 is redundant: as section 9 says, a plain zstd -d reads the production file)
zstd -dc --long=27 < colors.sketch-varopt512.zst | sketch decode --select sel/chain.txt > varopt512.sel.txt
sketch pairs --in R5-pickall --varopt-text varopt512.sel.txt --out R7-pairsall --threads 64

10.9 Results on the first 3M and 31.2M records

Four runs on prefixes of the chain, where exact answers exist, with the binary of §10.8 (139 tests passing):

  • R1 (eval, the first 3M records, every 97th record, 30,928 records): 49 KMV stores (k=64,256,1024k = 64, 256, 1024 at 16 seeds each under sets, and k=1024k = 1024 under pos) and three L1 stores against the exact store.
  • R2 (count, the first 31,187,785 records, all of them): 48 KMV stores (k=64,256,1024k = 64, 256, 1024 at 16 seeds) against the exact sizes.
  • R3 (pick and pairs, the first 3M records): three selections, made by sketch select prefix from R2’s seed-1 stream, with the exact store, varopt:512 and L1 stores beside the KMV ones. deep: records with supports of at least 1,024 blocks, one for each of 256 target blocks evenly spaced from the first such record’s block, 44,006, to block 178,609; each target takes such a record of its own block or of the next block that has one (118 moved), and the last target found none left after the window had taken the last deep records: 255 records in blocks 44,006 to 178,081, 32,385 pairs. window: the last 256 such records before record 3M, records 2,999,685 to 2,999,999 in blocks 178,608 to 178,610, 32,640 pairs. even: 1,000 records evenly spaced over the 3M, with no depth condition, 499,500 pairs. R3b added seeds on the same selection, so that k=1024k = 1024 has 64 seeds and k=128,512,2048k = 128, 512, 2048 have 16.

eval and count write their tables as they run: the exactness checks and the count results below are R1’s kmv-rows.tsv (column set_ok), kmv-seeds.tsv and l1-summary.tsv, and R2’s count-check.tsv, count-seeds.tsv and count-strata.tsv. The pair results are read back from R3’s and R3b’s pairs outputs by sketch pairs-stats, in seconds:

sketch pairs-stats --in R3-pairs3m --out R3-stats    # R3's 16 seeds: containment, L1
sketch pairs-stats --in R3-pairs3m --in R3b-pairs3m --out R3all-stats \
  --group deep --group window --group even --group deep+even --group deep+even+window

The second run pools R3b’s seeds with R3’s and gives Table 15 and the paragraph after it (jaccard-seeds.tsv) and panels (a), (b) and (c) of Figure 10 (jaccard-bins.tsv, jw-bins.tsv); the first gives the exact whole pairs and the sidenote (errors.tsv), the containment (containment.tsv), Table 16 and the L1 paragraph (jw-strata.tsv, l1-precision.tsv), and the numbers of the captions of Figure 9 and Figure 11 (groups.tsv, errors.tsv, quantiles.tsv). The Python scripts that first computed these tables agree with them to the digits they printed: 619 numbers of R3’s analysis, none different, and the across-seed tables to 1.2×10−51.2 \times 10^{-5} relative where R3b’s seeds are read from its f32 matrices. Three even figures need columns that only R3’s pairs.even.tsv held, which is no longer on disk, and stay the scripts’ own: the sidenote’s 24.8% and 3.8%, the f32 against f64 difference of 1.08×10−51.08 \times 10^{-5}, and the plug-in curve of panel (c).

Within one run every record and every pair shares one permutation (or one projection), so their errors are correlated: within a 10M-record bucket, the error of a count is mostly one offset shared by all its records. A per-run spread across records says nothing about the estimator; seeds are the unit of every bias and variance claim below. A bias test is Student’s tt over the seeds’ means, Bonferroni-corrected for the strata tested; a variance test compares the mean over records of each record’s variance across seeds with the theory, inside the χ2\chi^2 band that would hold even if all the records of a stratum moved together.

Exactness. In R1 every one of the 49 stores’ 30,928 sampled sketches was compared with the bottom-kk of the exact support, ranked by the same permutation: 1,515,472 comparisons, 0 mismatches, and full was set exactly when the support exceeded kk. The exact store’s support size equalled the --sets size on all 30,928 records. In R2 every whole sketch had exactly the reference size: 4,615,915, 4,715,656 and 4,792,897 records at k=64k = 64, 256 and 1024, for every seed, and no full sketch had a support of kk or fewer blocks. The L1 projection matched Π Ct\Pi\,C_t from the exact colour on 3,010 records with a worst deviation per coordinate, relative to ∑b=0L−1∣Πjb∣ct(b)\sum_{b=0}^{L-1} \lvert \Pi_{jb} \rvert c_t(b), of 5.1×10−75.1 \times 10^{-7} (m=512m = 512, f32), 6.8×10−76.8 \times 10^{-7} (m=1024m = 1024, f32) and 5.7×10−145.7 \times 10^{-14} (m=1024m = 1024, f64). In R3, at every kk, the pairs whose sketches were both whole had J^\hat J equal to the exact JJ in every case: 208,335 even pairs at k=1024k = 1024 (and 190,653, 205,120 and 209,628 at k=128k = 128, 512 and 2048), and 1,953 deep pairs at k=2048k = 2048.

Counts. All 184 seed gates of R2 (92 testable strata, bias and variance) passed, and all 160 of R1. The largest ∣t∣\lvert t \rvert in R2 was 2.08 (k=64k = 64, n^M\hat n_M, supports of 8,192 to 16,384 blocks), against Bonferroni thresholds of 4.20 to 4.36; the across-seed variance over theory ran from 0.57 to 1.49, inside bands of about [0.19,2.76][0.19, 2.76].

kkestimatormean relative error, all full recordsttRMS, deepest stratumtheoryratio
64n^\hat n+0.0066±0.0117+0.0066 \pm 0.01170.560.05490.05880.93
64n^M\hat n_M−0.0012±0.0212-0.0012 \pm 0.0212−0.06-0.060.10090.11510.88
256n^\hat n+0.0075±0.0060+0.0075 \pm 0.00601.260.02690.02900.93
256n^M\hat n_M+0.0045±0.0151+0.0045 \pm 0.01510.290.06670.05681.17
1024n^\hat n+0.0019±0.0035+0.0019 \pm 0.00350.550.01520.01441.05
1024n^M\hat n_M+0.0097±0.0055+0.0097 \pm 0.00551.760.02660.02830.94
Table 14: R2, support=sets, the first 31,187,785 records, 16 seeds per k. Mean relative error of the count over every record whose support exceeds k (26.6M, 26.5M and 26.4M records), as the mean of the 16 seeds’ means plus or minus the standard error across seeds, and its t. RMS: pooled over the 16 seeds, in the deepest stratum (supports of 131,072 to 262,144 blocks, 24,334,496 records), against the theory RSE of section 10.4 with each estimator’s universe. Bias and t from R2’s count-seeds.tsv; RMS and theory from its count-strata.tsv, the RMS as the root mean square of the 16 seeds’ rows.

The ratios are those of 16 draws of a stratum that moves as a whole within a run. One seed’s RMS over theory, in a stratum of more than 100,000 records, ranged from 0.22 to 3.08; pooled over 16 seeds, among the strata of more than 100,000 records the ratio left [0.85,1.2][0.85, 1.2] in a few (0.82–0.84 and 1.23 for n^\hat n at k=64k = 64, 0.75–0.79 for n^M\hat n_M at k=1024k = 1024), all inside the variance bands. Panels (a) and (b) of Figure 8 draw the strata of ∣S∣/k\lvert S \rvert / k with at least 1,000 records, among them some of fewer than 100,000, where the ratio reaches 1.24 for n^\hat n at k=64k = 64 (1.22 for n^M\hat n_M) and 0.78 for n^\hat n at k=1024k = 1024. A per-run accuracy band is not a test, and none is used.

Four panels. Top left: pooled RMS relative error of the count against the support size over k, for k 64, 256 and 1024, with theory curves, for the restricted and the full-universe estimator. Top right: mean relative error of the restricted count with across-seed error bars, all near zero. Third, across the full width: the median count per 10 million records over the whole chain, rising from about 130 to 710 thousand blocks, with its 10th and 90th percentiles, the exact quantiles on the first 31.2 million records, and the median of the newest block plus one, the most a count can be. Fourth, below it on a log scale: the share of records counted exactly, 30 percent at first and between about 0.25 and 2 percent after 60 million records.
Figure 8: Counts against their exact sizes, then over the whole chain; sets. (a) and (b): the first 31,187,785 records, 16 seeds per kk, by stratum of ∣S∣/k\lvert S \rvert / k (log 2), strata with at least 1,000 records. (a) RMS relative error pooled over the seeds, with ±2\pm 2 standard errors across seeds, against the theory RSE of each estimator (lines): the restricted n^\hat n over [0,βt][0, \beta_t] (filled markers, solid lines) and n^M\hat n_M over M=220M = 2^{20} (hollow, dotted). (b) Mean relative error of n^\hat n, with ±2\pm 2 standard errors across seeds. (c) R4, all 778,613,440 records, k=1024k = 1024, seed 1, per 10M records: the median n^\hat n (dots) and its 10th and 90th percentiles (thin lines and band), in thousands of blocks; the exact quantiles (crosses) in the three buckets wholly inside the first 31.2M records; the median βt+1\beta_t + 1 (grey, dotted), the most an n^\hat n can be. Years along the top. (d) The share of the same buckets’ records whose sketch is whole and counted exactly, on a log scale. Records of one seed share one permutation, so their errors are correlated; the spread that counts is across seeds. Drawn from count’s own tables: R2’s count-strata.tsv and count-seeds.tsv for (a) and (b), R4’s count-buckets.tsv for (c) and (d), with βt+1\beta_t + 1 from R4’s 1-in-4001 count-rows sample.

Jaccard similarity. No bias gate failed (0 of 52, groups ×\times kk ×\times strata of JJ). Pooled over seeds, the RMS error matches the hypergeometric SD of Proposition 26, in the table below and in panels (a) and (b) of Figure 10:

selectionpairs, 0<J<10 < J < 1kk (seeds)largest ∣t∣\lvert t \rvertthresholdRMS / hypergeometric SD
deep31,969128 (16)1.083.730.93–1.05
512 (16)0.823.730.89–1.04
1024 (64)2.373.220.98–1.03
2048 (16)0.993.730.93–1.01
window29,749128 (16)0.383.480.87–1.26
512 (16)2.223.480.94–1.29
1024 (64)2.213.050.83–1.02
2048 (16)2.063.480.81–0.86
even200,021128 (16)1.623.730.87–1.12
512 (16)1.793.730.87–1.13
1024 (64)2.203.220.94–1.03
2048 (16)1.523.730.92–1.02
Table 15: R3 and R3b, support=sets, the first 3M records. Strata of the exact J: (0, 0.05], (0.05, 0.2], (0.2, 0.5], (0.5, 0.9], (0.9, 1); the window has no pairs below 0.2. Largest |t| of the across-seed bias test over the strata, with its Bonferroni threshold; range over the strata of the RMS error pooled over seeds, over the hypergeometric SD.

The window is the exception, and it is a small one. Its 256 records have only 110 distinct support sizes, nested within three blocks, so a seed’s error moves almost all of its pairs together and the per-seed spread is heavy-tailed. Its stratum J∈(0.9,1)J \in (0.9, 1) came out at a ratio of 0.83 with 64 seeds (ratio squared 0.70±0.070.70 \pm 0.07); recomputed by brute force from the exact supports with 200 fresh seeds on 3,000 of its 26,899 pairs (a design-phase computation, not a crate run), the ratio squared was 0.955±0.0660.955 \pm 0.066 (in batches of 50 seeds: 1.040, 1.027, 0.700, 1.053). The k=2048k = 2048 shortfall in the window (ratios 0.81–0.86 over 16 seeds; ratio squared 0.73±0.280.73 \pm 0.28, 0.66±0.180.66 \pm 0.18 and 0.67±0.110.67 \pm 0.11, 1.0 to 3.0 standard errors below 1) reflects the same within-window correlation across seeds. Within one seed the fraction of pairs off by more than two hypergeometric SDs was mostly 2–6% per stratum (extremes 0.7% and 12.5%, both in the window, in its (0.5,0.9](0.5, 0.9] and (0.2,0.5](0.2, 0.5] strata).The SE that pairs writes per pair is the plug-in J^(1−J^)/k⋅(n^u−k)/(n^u−1)\sqrt{\hat J(1 - \hat J)/k \cdot (\hat n_u - k)/(\hat n_u - 1)}, which is 0 whenever J^\hat J is 0 or 1. Against it, 18.5% of the window’s pairs and 24.8% of the even selection’s were off by more than two SEs (averages over the 16 seeds of R3); among the pairs with a positive SE, 4.5% of deep, 1.1% of window and 3.8% of even. Coverage should be judged against the true SD, as above.

Containment of one support in another was defined for every pair of deep and window, and for 73.1% and 86.4% of the ordered even pairs (older in newer, newer in older): the undefined ones are small supports against large ones. Across 16 seeds at k=1024k = 1024 no stratum showed a bias (∣t∣≤2.55\lvert t \rvert \le 2.55 against a threshold of 3.62); the RMS error per stratum was 0.002 to 0.016 in deep and window, and up to 0.131 in the even pairs whose containment lies in [0.5,0.9)[0.5, 0.9).

Union counts (the restricted universe of the pair) were unbiased in a separate design-phase check, not a crate run, with 32 seeds on 2.5M records: relative bias −0.0026-0.0026 (t=−0.82t = -0.82) and RMS over theory 1.01 at k=1024k = 1024 on deep pairs. Figure 9 draws one seed’s J^\hat J for the deep selection against the exact values.

For 255 deep transactions of the first 3M records in time order, 2010 to 2012: a strip of support sizes at the left; a matrix with the estimated Jaccard similarity below the diagonal and the exact one above, nearly mirror images; and a triangle of the estimation error below the diagonal, within a few hundredths, in stripes.
Figure 9: The deep selection: 255 transactions with supports of 1,046 to 123,230 blocks, one per evenly spaced target block of the first 3M records, in time order; sets, k=1024k = 1024, seed 1. (a) J^\hat J below the diagonal, the exact JJ above; agreement shows as mirror symmetry. (b) J^−J\hat J - J below the diagonal, clipped at ±0.05\pm 0.05 (RMS 0.0102; 1st and 99th percentiles −0.032-0.032 and +0.022+0.022; none beyond ±0.05\pm 0.05). (c) The strip at the left: log⁡10\log_{10} of the exact support size, from 3 (dark) to 5.2 (light). Year ticks where the rows cross 1 January. Errors share one permutation, so they are correlated across cells (the stripes); the honest spread is across seeds (the Jaccard table above).

Weighted similarity. The L1 store was run at m=1024m = 1024 with 8 seeds and at m=256m = 256 and 512512 with 4 each.

exact JwJ_wpairsm=256m = 256m=512m = 512m=1024m = 1024varopt plug-in
<0.01< 0.013,410+0.014+0.014 / 0.028+0.014+0.014 / 0.024+0.008+0.008 / 0.017−0.003-0.003 / 0.004
[0.01,0.05)[0.01, 0.05)2,553+0.004+0.004 / 0.031+0.006+0.006 / 0.024+0.002+0.002 / 0.019−0.020-0.020 / 0.023
[0.05,0.2)[0.05, 0.2)12,230−0.004-0.004 / 0.041+0.002+0.002 / 0.028−0.003-0.003 / 0.021−0.121-0.121 / 0.127
[0.2,0.5)[0.2, 0.5)13,376+0.002+0.002 / 0.035+0.003+0.003 / 0.025−0.003-0.003 / 0.019−0.268-0.268 / 0.275
[0.5,0.9)[0.5, 0.9)1,050+0.006+0.006 / 0.026+0.006+0.006 / 0.019−0.002-0.002 / 0.015−0.430-0.430 / 0.434
≥0.9\ge 0.921+0.000+0.000 / 0.002+0.000+0.000 / 0.001−0.000-0.000 / 0.001−0.017-0.017 / 0.032
Table 16: R3, the window selection (32,640 pairs, records 2,999,685 to 2,999,999): bias / RMS error of the weighted Jaccard similarity by stratum of its exact value. L1 estimates averaged over 4, 4 and 8 seeds; the varopt plug-in is the one production run’s (k = 512, seed 1).

On the window’s pairs with Jw≥0.05J_w \ge 0.05 (26,677 of them) the L1 store at m=1024m = 1024 has a bias of −0.0029-0.0029 (SE across seeds 0.0029) and an RMS error of 0.0201, against 0.0263 at m=512m = 512 and 0.0379 at m=256m = 256: the 2/m\sqrt{2/m} law of §10.6. Below Jw=0.01J_w = 0.01 the mean estimate is the floor (panel (c) of Figure 10): 0.009–0.011 at m=1024m = 1024, 0.013–0.017 at m=512m = 512, 0.017–0.019 at m=256m = 256 over the three selections, against 0.0088, 0.0125 and 0.0176 predicted for Jw=0J_w = 0. f32 and f64 stores gave the same TV̂\widehat{\mathrm{TV}} to 9.6×10−79.6 \times 10^{-7} relative in the window and 1.9×10−71.9 \times 10^{-7} in deep; in even one pair reached 1.08×10−51.08 \times 10^{-5}, at a TV of 2.1×10−42.1 \times 10^{-4} (an absolute difference of 2.3×10−92.3 \times 10^{-9}). The plug-in column is §10.2’s bias, measured. Figure 11 draws the window’s two matrices, the estimates against the exact values.

Three panels. Top left: RMS error of the Jaccard estimate against the exact J in 13 bins, for k 128, 512, 1024 and 2048, lying on the hypergeometric curves. Top right: mean error by bin with across-seed error bars, within a few thousandths of zero. Bottom: on log-log axes, the mean weighted Jaccard estimate against the exact value by bin, for L1 at three m, which follow the diagonal down to a floor between 0.01 and 0.02, and for the varopt plug-in, which lies far below the diagonal.
Figure 10: The first 3M records (R3 and R3b), sets. (a) RMS of J^−J\hat J - J pooled over seeds (markers, with ±2\pm 2 standard errors) and the hypergeometric SD of §10.5 (lines), in 13 bins of the exact JJ, over the deep and even pairs with at least one full sketch and 0<J<10 < J < 1 (the others are exact); 64 seeds at k=1024k = 1024, 16 at k=128k = 128, 512 and 2048. Measured over predicted runs from 0.82 to 1.15 across the bins. (b) The mean of J^−J\hat J - J in the same bins, with ±2\pm 2 standard errors across seeds, in units of 10−210^{-2}, the four kk slightly offset; the largest ∣t∣\lvert t \rvert is 2.87 (k=1024k = 1024), against a Bonferroni threshold of 3.54 for 13 bins at a family-wise 0.01 (3.00 at 0.05). (c) The weighted similarity over the 564,525 pairs of all three selections, in 11 bins of the exact JwJ_w (the first, Jw<10−3J_w < 10^{-3}, at the left edge): the mean J^w\hat J_w of the L1 store at m=256m = 256 and 512 (4 seeds each) and 1024 (8 seeds), with ±2\pm 2 standard errors across seeds, and the mean plug-in of the production varopt:512 sketches (not used; below 10−410^{-4}, off the axis, in the first bin). The L1 curves follow the diagonal down to the floor of §10.6 (mean J^w\hat J_w 0.019, 0.013 and 0.0089 where Jw<10−3J_w < 10^{-3}); the plug-in is 4 to 10 times too small for JwJ_w from 10−310^{-3} to 0.7. Errors share one permutation or projection within a seed, so the honest spread is across seeds.
For 256 transactions in a window of three blocks, clustered, with a strip of support sizes at the left: the set distance on a log scale, the KMV estimate below the diagonal and the exact value above, mostly below one in a hundred; and the weighted Jaccard similarity, the L1 estimate below and the exact value above, mostly below four tenths (median 0.18).
Figure 11: The window: the last 256 deep transactions before record 3M (records 2,999,685 to 2,999,999, blocks 178,608 to 178,610), ordered by average-linkage clustering on 1−J^1 - \hat J with optimal leaf ordering (on the estimate, since production has no exact values). (a) The set distance 1−J1 - J on a log scale, sets, k=1024k = 1024 seed 1 below the diagonal, exact above; values of 10−310^{-3} or less, including identical supports (8.9% of the pairs), take the end colour. (b) JwJ_w on a linear scale to 0.6 (0.45% of the exact values lie above, counted by the figure script), L1 m=1024m = 1024 seed 1 below, exact above. The strip at the left: log⁡10\log_{10} of the exact support size, from 4.79 (dark) to 5.10 (light). The two matrices say different things: nearly the whole history is shared (median JJ 0.994), while the shared value is a few tenths at most (median JwJ_w 0.18).

Cost. Wall times and peak memory are those of /usr/bin/time -v (VmHWM, in GB of 10910^9 bytes as in §8.9); the busy times and peaks of single stores are each run’s cost.tsv. R1 took 8 min 24 s and 100.2 GB, almost all of it the exact store. R2 folded 48 KMV stores over 31.2M records in 2 min 55 s and 68.0 GB; a k=1024k = 1024 store was busy 146.7 s and peaked at 617,119,725 ranks in 733,466 live sketches. In R3, which folded the exact store and 29 KMV, 17 L1 and one varopt store in one pass (7 min 36 s, 107.6 GB), a k=1024k = 1024 KMV store was busy 11.5 s over the 3M records, an L1 store at m=1024m = 1024 14.3 s and varopt:512 23.9 s; pairs took 56 s for the 564,525 pairs.

10.10 The whole chain

Counts. R4 counted every one of the 778,613,440 records with five stores in one pass: k=1024k = 1024 at seeds 1, 2 and 3, k=256k = 256, and k=1024k = 1024 under pos. It took 1 h 09 min 47 s, at 544% of a core, and 144.2 GB (/usr/bin/time -v).

Table 17: R4, all 778,613,440 records: per store, the time its thread was busy, the peaks of ranks held and of live sketches, and the number of records whose merge had elements left over. The seed changes the peaks not at all and the last column by about 1 percent. From R4’s cost.tsv.
storebusypeak rankspeak live sketchesrecords cut to kk
k=1024k = 1024, seed 13,853 s7,660,615,6887,593,632137,238,198
k=1024k = 1024, seed 23,817 s7,660,615,6887,593,632135,831,031
k=1024k = 1024, seed 33,910 s7,660,615,6887,593,632135,305,680
k=256k = 256, seed 12,143 s1,916,423,3247,593,632102,302,532
k=1024k = 1024, seed 1, pos3,777 s7,660,613,6407,593,630137,238,132

At the peak a k=1024k = 1024 store holds about 1,009 ranks in each of 7.59M live sketches, as many as the production run of §9 keeps alive: 30.6 GB of ranks.

  • Against the exact sizes. On the first 31,187,785 records every hard counter of every store was 0 (R4’s count-check.tsv): no whole sketch of the wrong size, no full sketch of a support of at most kk, no whole sketch of a larger one, no sketch of more than kk ranks. The whole sketches of exactly the reference size were R2’s: 4,792,897 at k=1024k = 1024, at every seed, and 4,715,656 at k=256k = 256.
  • Determinism. The first 623,755,748 bytes of R4’s seed-1 stream, 48+20⋅31,187,78548 + 20 \cdot 31{,}187{,}785, equal R2’s (by cmp): the whole-chain stream extends the one validated against the exact sizes.
  • Seeds against each other. Past record 31,187,785 there is no reference, so the three k=1024k = 1024 seeds were compared with each other: per 10M-record bucket and per pair of seeds, the RMS of the relative difference of their n^\hat n over 2\sqrt 2, against the RMS of the records’ theory RSE. Pooled over the 767,323,643 records full at every seed, the ratio was 0.424 for seeds 1 and 2, 0.966 for 1 and 3, 0.828 for 2 and 3; per bucket it ranged from 0.23 to 1.58. Within a bucket, though, the spread of the differences around their bucket’s mean is only 0.16 to 0.55 of the theory: most of a bucket’s seed difference is one offset shared by its 10M records, as one permutation per seed and heavily overlapping supports make it. The pooled ratios are therefore a handful of effective draws, not 767M, and should scatter around 1 by a factor of about 2. Seeds 1 and 2 sit low all along, as on R2, where seed 1 had the smallest error (RMS over theory 0.37, 0.70 and 0.76 for seeds 1 to 3, in R2’s count-strata.tsv, and 0.50 for the pair 1–2); without a reference this cannot be told from two close offsets. Reported, not gated. The seed gates of the first 31.2M records passed (0 of 52 failed, in R4’s count-seeds.tsv; with 3 seeds they are weak, a tt threshold of 36).
  • Never above the universe. No record has a restricted n^\hat n above βt+1\beta_t + 1 (0 of 778,613,440, in each of the five streams), as Proposition 25 guarantees: a check of the decoding.
  • Counted exactly. 11,289,797 records, 1.450%, have a whole sketch at k=1024k = 1024, and 4,792,897 of them lie in the first 31.2M records. Their supports are small: in a 1-in-4001 sample of the records the median is 2 blocks, the 90th percentile 54 and the largest 983. Under pos exactly as many sketches are full as under sets.
  • The file. The seed-1 stream compresses to 1,842,558,077 bytes (ls), 2.37 B a record, 8.45 times less than its 15,572,268,872 raw bytes; it is the production count file of §10.11.

The comparison of seeds, the check against the universe and the records counted exactly are read back from R4’s streams by sketch summary (§10.8), with no fold:

R="--range 0:31187785 --range 30187785:31187785 --range 0:100000000 --range 100000000:200000000 \
   --range 200000000:300000000 --range 300000000:400000000 --range 400000000:500000000 \
   --range 500000000:600000000 --range 600000000:700000000 --range 700000000:"
S=R4-countall/counts.kmv-k1024
sketch summary --in $S-s1-sets.bin.zst --in $S-s2-sets.bin.zst --in $S-s3-sets.bin.zst \
  --in R4-countall/counts.kmv-k256-s1-sets.bin.zst --in $S-s1-pos.bin.zst \
  --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --bucket 10000000 $R --out R4-summary
sketch summary --in $S-s1-sets.bin.zst --every 4001 --bucket 10000000 $R --out R4-sample

The pooled and per-bucket ratios between seeds are R4-summary/dispersion.tsv; the check against the universe, the records counted exactly and their share are the over_univ, whole, frac_whole and full columns of summary.tsv, and the supports of the whole records in the sample its whole_p50, whole_p90 and whole_max in R4-sample. The first run takes about 5 minutes of wall time. It replaced a mawk pass over three decoded streams, whose 1,404 per-bucket cells it reproduces as mawk printed them, and a Python pass over the 1-in-4001 sample, whose depth table it reproduces up to the rounding of one percentile that falls on a tie.

Panel (c) of Figure 8 follows the counts down the chain. Where the exact sizes exist, a bucket’s median n^\hat n is within 0.5% of the exact median (0.9965, 1.0008 and 1.0047 in the first three 10M-record buckets). The median support grows from 131,000 blocks in the first 10M records to 708,000 in the last 8.6M, and fills more of its universe as it grows: the median of n^/(βt+1)\hat n / (\beta_t + 1) is 0.85 over the first 100M records and 0.93 over the last 78.6M. The share counted exactly (panel (d)) is 30% of the first 10M records, 6.1% of the first 100M, and between 0.25% and 1.9% of every 10M bucket after the first 60M. The finite-population factor shrinks as the supports fill their universe, so the theory RSE falls with depth: over the full records its median is 1.21% in the first 100M, 0.92% over the chain (10th and 90th percentiles 0.82% and 1.19%) and 0.81% in the last 78.6M. n^M\hat n_M, over 2202^{20}, has a median RSE of 2.25% over the chain, about 2.5 times that of n^\hat n. These are columns of R4-summary/summary.tsv: n_p50 against ref_p50 per bucket, n_p50 alone for the median support, fill_p50, frac_whole, and rse_p10, rse_p50, rse_p90 and rse_M_p50 over the ranges of the command above. (Its quantiles are numpy’s linear ones; count’s count-buckets.tsv, drawn in the figure, takes the lower order statistic, and the two differ in about the sixth digit.)

Matrices. R5 folded the stores of the selected records over the whole chain, and R6 read the production varopt sketches of the same records out of colors.sketch-varopt512.zst. The selections were drawn from R4’s seed-1 stream by sketch select chain (§10.8), which prints the ranges below; a record is deep when its k=1024k = 1024 sketch is full, so ∣S∣>1024\lvert S \rvert > 1024 exactly by Theorem 22.

  • w2013 and w2017: the first 256 deep records from blocks 240,000 and 470,000 (records 19,031,618 to 19,031,920 in blocks 240,000 to 240,002, and records 229,491,548 to 229,491,813, all in block 470,000). w2022: the last 256 deep records of the chain, which are its last 256 records, all in block 762,260.
  • chain: 512 target blocks evenly spaced from 50,000 to 762,260; each takes a deep record not already selected, from the first block at or after the target that has one (40 picks moved past their target). All 512 targets found a record: records 51,126 to 778,611,720, in blocks 50,299 to 762,260, with n^\hat n from 1,254 to 711,490 (median 354,641).
  • R5 folded seven stores, four KMV (k=1024k = 1024 at seeds 1, 2 and 3, and seed 1 under pos) and three L1 (m=1024m = 1024 at seed 1 in f32 and in f64, m=512m = 512 at seed 2), over all 778,613,440 records, and dumped the 1,280 selected: 1 h 10 min 05 s at 607% of a core, and 249.8 GB (/usr/bin/time -v), 0.6% below the 251.2 GB that a memory model fitted to R4, outside the crate, predicted (chain.log prints 242.2 GB: its run-time check compared R4’s VmHWM in GiB with the model in GB and so left the model unscaled). A KMV store was busy 3,872 to 3,969 s and reproduced R4’s peaks and counts of cut records exactly; the L1 stores were busy 2,667 s (m=1024m = 1024, f32), 3,374 s (f64) and 2,348 s (m=512m = 512), in R5’s cost.tsv.
  • R6 cut the 1,280 records out of the production file, beside R5.
  • R7 computed the 228,736 pairs (130,816 in chain, 32,640 in each window) in 3.84 s and 0.2 GB (/usr/bin/time -v).

The checks on these pairs were first made by a Python script, r7_checks.py. The crate now makes them from R7’s output, with the same results to the six digits the script printed (at worst 1.1×10−81.1 \times 10^{-8} relative): the first two by pairs-stats (seed-agreement.tsv, seed-pairs.tsv, l1-precision.tsv), the fourth by running pairs again with the binned colours of the selected records (bands-check.tsv), in seconds and without a fold:

sketch pairs-stats --in R7-pairsall --out R7-stats
sketch pairs --in R5-pickall --varopt-text varopt512.sel.txt --bands bands1024.sel.txt \
  --out R7-bands --threads 32

The checks:

  • J^\hat J across seeds 1, 2 and 3. For each cell, ss is the standard deviation of the three seeds’ J^\hat J and σ\sigma the hypergeometric SD of Proposition 26 at their mean J^\hat J and union count. If the estimates were independent and normal, s2/σ2s^2/\sigma^2 would be distributed as χ22/2\chi^2_2/2: mean 1, and s≤3 σs \le \sqrt 3\,\sigma with probability 1−e−3=0.951 - e^{-3} = 0.95. The gate, a mean (s/σ)2(s/\sigma)^2 in [1/3,3][1/3, 3], passed in every group: 0.933 in chain, 0.876 in w2013, 1.154 in w2017, 1.134 in w2022. The share of cells with s≤3 σs \le \sqrt 3\,\sigma, among those with kJkJ and k(1−J)k(1 - J) at least 10, is reported, not gated: 0.976, 0.991, 0.963 and 0.699. The low one is a single offset: in w2022 the difference between seeds 1 and 2 has mean −1.552 σ-1.55 \sqrt 2\,\sigma and a mean (ΔJ^)2/(2σ2)(\Delta \hat J)^2 / (2\sigma^2) of 3.73, against 0.99 and 1.50 for the other two pairs of seeds. Its 32,640 cells share one permutation per seed, so one unlucky pair of permutations moves them all. No pair in these groups has two whole sketches, so no cell is exact.

  • L1 in f32 against f64. The two gave the same TV̂\widehat{\mathrm{TV}} to 7.8×10−57.8 \times 10^{-5} relative at worst (in w2013; 1.9×10−51.9 \times 10^{-5} in chain), with a 99th percentile of at most 3.2×10−73.2 \times 10^{-7} in every group, and a pair at 0 in f64 was 0 in f32: below the 10−410^{-4} that the check allows. The figures use f64 all the same.

  • L1 against the exact JwJ_w could not be checked at full depth. It needs pairs whose two varopt sketches are unreduced, and so are the colours, up to f32; every selected record has more than 1,024 blocks, so its varopt:512 sketch is always reduced. The check stands on the prefix (§10.9).

  • L1 against an exact lower bound. Binning two colours into the same 1,024 bands can only lower their TV, and colors.bands1024.zst holds every record’s exact binned colour; so

    TV̂≥TV1024−32/m  TV̂ \widehat{\mathrm{TV}} \ge \mathrm{TV}_{1024} - 3\sqrt{2/m}\;\widehat{\mathrm{TV}}

    should hold in at least 99% of the pairs. Read for the 1,280 selected records into bands1024.sel.txt (a separate Python and mawk pass over the 1.67 TB file, 3 h 42 min of wall time; pick --bands-ref now copies the same lines during the fold, which R5 predates), it holds in 99.985% of the 130,816 chain pairs at m=1024m = 1024, in 100%, 99.97% and 99.997% of the 32,640 pairs of w2013, w2017 and w2022, and likewise at m=512m = 512 and in f64; every band line’s transaction matched the selection. The bound is far from tight inside a window: the median of TV̂/TV1024\widehat{\mathrm{TV}} / \mathrm{TV}_{1024} (over pairs with TV1024>0.01\mathrm{TV}_{1024} > 0.01, at m=1024m = 1024) is 1.10 in chain but 1.36 to 1.82 in the windows, whose colours differ mostly within bands of 745 blocks. A check that passes, then, and not an exact reference.

Across time, in the whole-chain matrix of Figure 12, the upper triangle has no exact JJ to show, as the prefix’s has, and a containment drawn on [0,1][0, 1] would be a flat field. On the prefix deep pairs, the containment of the older support in the newer is exactly 1 in 81.6% of the cells and at least 0.9 in 90.9%, and the share of cells at 1 grows with the gap: 41% under 5,000 blocks apart, 63% at 5,000–20,000, 86% at 20,000–60,000 and 97% beyond. For nested pairs JJ is just the ratio of the two sizes, which the log⁡10n^\log_{10} \hat n strip already shows. What is informative is the 18.4% of cells that are not nested (5,968 of 32,385), whose log⁡10(1−c)\log_{10}(1 - c) spreads from −2.7-2.7 (p10) through −1.0-1.0 (p50) to −0.01-0.01 (p90), and the KMV estimate tracks the exact value there (721 cells fall below the resolution of k=1024k = 1024). So the upper triangle of the whole-chain matrix shows log⁡10(1−c^old⊆new)\log_{10}(1 - \hat c_{\text{old} \subseteq \text{new}}), clipped to [−3,0][-3, 0]: its floor colour means “nested, to the resolution of kk”.

Over the whole chain the field is flatter still. The containment is defined in 129,791 of the 130,816 cells of chain, and 98.5% of those are at the floor (c^=1\hat c = 1 exactly); only 1,970 cells, 1.5%, are not nested to the resolution of kk, with log⁡10(1−c^)\log_{10}(1 - \hat c) at −2.04-2.04, −0.97-0.97 and −0.39-0.39 (p10, p50, p90), and 316 of them in one row: record 102,455, of block 73,701, with 1,623 blocks, whose median containment in the later supports is 0.917. The containment is undefined in 1,025 cells (0.78%): small early supports (1,250 to 2,400 blocks, in blocks 75,115 to 116,905) against late ones (from block 554,576), where no sampled element of the older support ranks below the newer one’s threshold. The fallback J^n^u/n^A\hat J \hat n_u / \hat n_A is 0 in all of them, since J^\hat J is, and 0 would read as “disjoint”, so they are drawn hatched instead. J^\hat J has percentiles 0.016, 0.48 and 0.89 (p10, p50, p90), and its median by block gap tracks the ratio of the smaller count to the larger (0.989 against 0.990 under 5,000 blocks apart, 0.413 against 0.412 beyond 60,000): nested pairs, as the containment says.

Two matrices for 512 deep transactions spread over the whole chain in time order, 2010 to 2022, with a strip of support sizes at the left. Left: the estimated Jaccard similarity below the diagonal, falling with the time between two transactions; above it the containment of the older support in the newer, at the nested floor nearly everywhere, with a few hatched undefined cells near the top right. Right: the Wasserstein distance between the production VarOpt sketches in years, small near the diagonal and growing with the time between two transactions.
Figure 12: The chain selection: 512 deep transactions, one per evenly spaced target block from block 50,000 to the end of the chain, in time order (blocks 50,299 to 762,260); sets, k=1024k = 1024, seed 1. (a) Below the diagonal, J^\hat J. Above it, log⁡10(1−c^)\log_{10}(1 - \hat c) for the containment c^\hat c of the older support in the newer, clipped to [−3,0][-3, 0]: the floor colour, −3-3 or less, means nested to the resolution of kk (98.5% of the defined cells); grey and hatched, undefined (1,025 cells): no sampled element of the older support ranks below the newer one’s threshold. The strip at the left: log⁡10n^\log_{10} \hat n, from 3 (dark) to 6 (light). (b) W1W_1 between the production varopt:512 sketches of the same records, read out of the production file without a new fold, in years of 144 blocks a day, on a log scale clipped to [0.13,9][0.13, 9]. Year ticks, every other year, where the rows cross 1 January. JwJ_w is not drawn; its quantiles are in the text. Errors share one permutation, so they are correlated across cells; the honest spread is across seeds.

W1W_1, the “temporal distance”, has percentiles 0.48, 1.86 and 4.26 years (p10, p50, p90), and a Spearman correlation of 0.82 with the gap in blocks and of 0.77 with 1−J^1 - \hat J. The weighted similarity is far from the floor across the whole chain, unlike on the prefix: L1 J^w\hat J_w (m=1024m = 1024, f64) has percentiles 0, 0.21 and 0.59 (p10, p50, p90), only 20.5% of the pairs lie below the floor of 0.0088, and its median falls with the gap from 0.55 under 5,000 blocks to 0.18 beyond 60,000. The independent store at m=512m = 512, seed 2, agrees (median 0.18, p90 0.59). On the prefix, deep pairs across time had a median JwJ_w of 1.4×10−41.4 \times 10^{-4} (§10.1): what holds for the first 3M records does not hold for the chain as a whole.

Inside a window, where JJ is close to 1, the weighted similarity is what tells transactions apart, and the three windows differ (Figure 13):

Six matrices in two rows and three columns, for 256 transactions each in 2013, 2017 and 2022, each column clustered. Top row: the estimated set distance on a log scale, mostly a few thousandths or less (median 2 in 1024), with a few bands of larger distance. Bottom row: the weighted Jaccard estimate on a scale from 0 to 1, low and mixed in 2013, mostly between 0.6 and 0.9 in 2017 and 2022.
Figure 13: Three windows of the whole chain, 256 deep transactions each: 2013, the first from block 240,000 (blocks 240,000 to 240,002); 2017, the first from block 470,000 (all in that block); 2022, the last 256 records of the chain (all in block 762,260). Each column is ordered by average-linkage clustering on 1−J^1 - \hat J with optimal leaf ordering, and both rows follow that order. No exact values exist here, so both triangles show the estimate. Top: the set distance 1−J^1 - \hat J, sets, k=1024k = 1024, seed 1, on a log scale; 10−310^{-3} or less, identical sketches included, takes the end colour. Bottom: J^w\hat J_w from L1, m=1024m = 1024, seed 1, f64, on [0,1][0, 1].

In all three the median 1−J^1 - \hat J is 2/10242/1024, two sampled elements apart, and J^=1\hat J = 1 in 21.9%, 32.4% and 36.9% of the pairs. The weighted similarity rises from era to era: J^w\hat J_w has percentiles 0.11, 0.44 and 0.72 (p10, p50, p90) in 2013, 0.40, 0.75 and 0.85 in 2017, and 0.58, 0.78 and 0.87 in 2022, below the floor in 2.7%, 1.6% and 0.02% (5 pairs) of the pairs. The median W1W_1 between two transactions of a window is 0.19, 0.25 and 0.35 years. Under pos, every J^\hat J of the four groups equals the sets one.

The numbers given since the checks, in the text and in the captions, are tables of pairs-stats: of R3-stats for the prefix’s deep pairs, of R7-stats for the whole chain. The percentiles, the shares at 1, at the floor and below the L1 floor, and their split by block gap are in quantiles.tsv; the row of record 102,455 and the undefined cells in cont-rows.tsv; the Spearman correlations in spearman.tsv; pos against sets in support.tsv.

10.11 The production count file

colors.kmv1024.counts.zst, 1,842,558,077 bytes (SHA-256 c8d38950e06278e86b4affc86f1906bbb59712746aba29d2e1d9fce9485a7a7d), is R4’s seed-1 stream, copied after R4’s checks passed. It is one zstd frame with a 4 MiB window, so a plain zstd -d reads it.

It holds, for each of the 778,613,440 transactions in record order, the 20-byte record of §10.8 for the k=1024k = 1024, seed-1, sets sketch of its support. Read it with

zstd -dc colors.kmv1024.counts.zst | sketch decode

which verifies the trailer and writes a comment line naming the stream (# kmv-k1024-s1-sets k=1024 seed=1 support=sets bits=20 M=1048576) and then rec tx block univ full m n_hat se n_hat_M se_M, one line a record. Or read the raw records with numpy, dtype [('tx','<u8'),('block','<u4'),('m','<u4'),('rk','<u4')] at offset 48 with count = (size - 48 - 24) // 20 (the last 24 bytes are the trailer): then m & 0x7fffffff is the sketch’s length, bit 31 says full, and n^M=1023⋅220/rk\hat n_M = 1023 \cdot 2^{20} / \texttt{rk} follows directly, while the restricted n^\hat n needs the permutation, which decode rebuilds from the header.

What an n^\hat n means: when full is clear (every support of at most 1024 blocks, 1.45% of the records) it is ∣St∣\lvert S_t \rvert, the number of blocks the transaction descends from, through zero-amount inputs too. Otherwise it is an exactly unbiased estimate with a standard error of about n(n−k+1)/(k−2)⋅(N−n)/(N−1)\sqrt{n(n - k + 1)/(k - 2) \cdot (N - n)/(N - 1)} blocks, written as se (and as se_M for n^M\hat n_M, with M=220M = 2^{20} in place of NN). The relative error se / n_hat has a median of 0.92% over the chain, 1.2% over its first 100M records and 0.8% over its last 78.6M. These figures, and the 1.45%, are what sketch summary writes for the file itself, the same as for R4’s stream, of which it is a byte copy (cmp):

sketch summary --in colors.kmv1024.counts.zst \
  --sets-counts finalBCUTXO_2022.sets-counts.31187785.txt --bucket 10000000 $R --out prod-summary

with the ranges $R of §10.10; it reads the 778,613,440 records in about 3.5 minutes of wall time. All records share one permutation, so their errors are correlated, by design: two records with nearly the same support get nearly the same error. A second seed’s file is the way to an independent estimate; R4 computed seeds 2 and 3, which are not shipped.

11. Ten Sketched Colours

What the production file holds, read for a few transactions: the sketch C^t\hat C_t of §5.5, a polynomial in xx with at most 512 terms, where the exponent is the block a coin was minted in and the coefficient the sketch’s estimate of the share of tt’s value minted there. The ten below are among the 1,280 records of §10.10 that R6 cut out of colors.sketch-varopt512.zst, each picked for one property of its sketch. Each has exactly 512 terms, and its coefficients sum to 1 to seven digits, as point 4 of Theorem 3 and Theorem 7 say they must. The subscript is the record number.

Terms with equal coefficients are grouped, heaviest group first, and only the first four groups are written out; η(x)\eta(x) is the rest, η(1)\eta(1) its mass. The coefficients are rounded to six digits. All 5,120 terms, as stored, are in ten-colours.txt.

All of this section is read by sketch describe. It takes the 1,280 sketches as sketch decode --select prints them, their exact colours binned in the 1,024 bands (the lines of colors.bands1024.zst read for the check of §10.10) and their n^\hat n. It writes a row per record to describe.tsv, with the columns of Table 18 and a few more, and totals over the 1,280 to summary.tsv; for the records given by --records, also the table’s rows (table.md), the displays below (displays.md) and ten-colours.txt (colours.txt). The Python scripts that did this first gave the same rows and displays, and the same band comparisons to the bit. Several of the ten are extremes of one column of describe.tsv: the second has the largest coefficient, the sixth the most distinct ones, the seventh the smallest age, the tenth the largest n^\hat n.

# the 1,280 records of §10.9's selection: their sketches (R6) and their counts
zstd -dc --long=27 < colors.sketch-varopt512.zst \
  | sketch decode --select sel/chain.txt > varopt512.sel.txt
zstd -dc colors.kmv1024.counts.zst | sketch decode --select sel/chain.txt > counts.sel.tsv
TEN=51126,99576,243275,456104,19031745,69818050,77146563,229491784,778613383,778611720
sketch describe --in varopt512.sel.txt --bands bands1024.sel.txt --counts counts.sel.tsv \
  --select sel/chain.txt --records $TEN --out describe
recordblockgroupdistinct coefficientsheavy entrieslargest coefficientmean blocknewest blockn^\hat nKSW1W_1 (blocks)
51,12650,299chain82630.0150 at each of 1639,92347,9181,5062×10−82 \times 10^{-8}0
99,57672,310chain261090.9942 at 71,92571,90671,9252,2673.8×10−83.8 \times 10^{-8}0
243,275104,360chain333520.9500 at 99,53598,783102,88020,7423.8×10−73.8 \times 10^{-7}0
456,104121,087chain542850.0083 at each of 266,63193,27116,5320.0002810
19,031,745240,001w20131071130.9093 at 239,070236,737239,070190,9198.4×10−58.4 \times 10^{-5}6
69,818,050358,042chain4374390.0100 at 357,814357,545357,937310,1421.8×10−51.8 \times 10^{-5}2
77,146,563366,405chain3083210.0337 at 366,190366,128366,271320,3703.3×10−93.3 \times 10^{-9}0
229,491,784470,000w201735480.0501 at 210,595165,048229,223183,5860.0016142
778,613,383762,260w2022101/5121/512 at each of 512175,122391,528443,3160.0025262
778,611,720762,260chain101/5121/512 at each of 512351,468761,472711,4900.0025524
Table 18: The ten sketches. Heavy entries: those above the threshold tau of the last reduction, kept with their own weight; the others equal tau. Largest coefficient: its value and the block (or the number of blocks) that carries it. Mean and newest block: of the sketch. n hat: the support size from the production count file of section 10.11. KS and W1: the sketch against the exact colour, both read at the 1,024 band edges of colors.bands1024.zst (the exact colours are on disk only binned, in bands of 745 blocks); W1 is the area between the two CDFs so read, rounded to whole blocks. From sketch describe, table.md; describe.tsv has the same columns for all 1,280 records.

The ten, in the order of the table:

  1. The first chain record. It is the first deep record at or after block 50,000; the first deep record of the chain is earlier, record 44,447 in block 44,006, as sketch select chain reports when it makes the selection. Its 512 terms take only 8 values: whole groups of blocks reach it along the same paths through the DAG, so they share one product of shares. The four groups shown, 222 terms, are all above 1/5121/512, which no reduction’s τ\tau can exceed (Lemma 2), so every reduction on the way kept them as they came. Of the 290 terms in η(x)\eta(x), 41 are heavy too, and the other 249 are the lights of this record’s own last reduction, all equal to its τ=1.49×10−9\tau = 1.49 \times 10^{-9}.
C^51126(x)=0.01505 (x46567+x46633+⋯+x47918)⏟16 terms+0.0123652 (x30732+x33941+x34409)+0.00368812 (x13316+x24451+x35892)+0.00355412 (x36099+x36101+⋯+x41649)⏟200 terms+η(x),290 terms with 4 coefficients, η(1)=0.000216719 \begin{aligned} \hat C_{51126}(x) ={}& 0.01505\,\underbrace{(x^{46567} + x^{46633} + \dots + x^{47918})}_{16\ \text{terms}} \\ &+ 0.0123652\,(x^{30732} + x^{33941} + x^{34409}) \\ &+ 0.00368812\,(x^{13316} + x^{24451} + x^{35892}) \\ &+ 0.00355412\,\underbrace{(x^{36099} + x^{36101} + \dots + x^{41649})}_{200\ \text{terms}} \\ &+ \eta(x), \quad \text{290 terms with 4 coefficients},\ \eta(1) = 0.000216719 \end{aligned}
  1. The most concentrated colour. One block, minted 385 blocks earlier, carries 99.42% of the value. Binned, the exact colour puts 0.9949 in that block’s band (blocks 71,520 to 72,264), and so does the sketch.
C^99576(x)=0.994246 x71925+8.25445×10−5 x70186+8.2528×10−5 x70566+8.25116×10−5 (x70432+x70627+⋯+x71402)⏟8 terms+η(x),501 terms with 22 coefficients, η(1)=0.00492931 \begin{aligned} \hat C_{99576}(x) ={}& 0.994246\,x^{71925} \\ &+ 8.25445 \times 10^{-5}\,x^{70186} \\ &+ 8.2528 \times 10^{-5}\,x^{70566} \\ &+ 8.25116 \times 10^{-5}\,\underbrace{(x^{70432} + x^{70627} + \dots + x^{71402})}_{8\ \text{terms}} \\ &+ \eta(x), \quad \text{501 terms with 22 coefficients},\ \eta(1) = 0.00492931 \end{aligned}
  1. One block and a long tail. 95% from block 99,535, and a tail that reaches back to block 9.
C^243275(x)=0.950014 x99535+0.0178931 x99327+0.00582011 (x93408+x93446+x93795)+0.00133668 (x99223+x99305+x99466)+η(x),504 terms with 29 coefficients, η(1)=0.0106228 \begin{aligned} \hat C_{243275}(x) ={}& 0.950014\,x^{99535} \\ &+ 0.0178931\,x^{99327} \\ &+ 0.00582011\,(x^{93408} + x^{93446} + x^{93795}) \\ &+ 0.00133668\,(x^{99223} + x^{99305} + x^{99466}) \\ &+ \eta(x), \quad \text{504 terms with 29 coefficients},\ \eta(1) = 0.0106228 \end{aligned}
  1. Old money in 2011. A diffuse colour, with no coefficient above 0.84%, whose heaviest terms are blocks of early 2009.
C^456104(x)=0.00832831 (x2659+x5065)+0.00832812 (x2775+x3549+⋯+x7312)⏟4 terms+0.00831587 (x1025+x2148)+0.0083124 x80654+η(x),503 terms with 50 coefficients, η(1)=0.925087 \begin{aligned} \hat C_{456104}(x) ={}& 0.00832831\,(x^{2659} + x^{5065}) \\ &+ 0.00832812\,\underbrace{(x^{2775} + x^{3549} + \dots + x^{7312})}_{4\ \text{terms}} \\ &+ 0.00831587\,(x^{1025} + x^{2148}) \\ &+ 0.0083124\,x^{80654} \\ &+ \eta(x), \quad \text{503 terms with 50 coefficients},\ \eta(1) = 0.925087 \end{aligned}
  1. The 2013 window. 91% of the value was minted in one block, 931 blocks earlier.
C^19031745(x)=0.909327 x239070+0.0087706 x235587+0.00719864 x234980+0.00359045 x237394+η(x),508 terms with 103 coefficients, η(1)=0.0711136 \begin{aligned} \hat C_{19031745}(x) ={}& 0.909327\,x^{239070} \\ &+ 0.0087706\,x^{235587} \\ &+ 0.00719864\,x^{234980} \\ &+ 0.00359045\,x^{237394} \\ &+ \eta(x), \quad \text{508 terms with 103 coefficients},\ \eta(1) = 0.0711136 \end{aligned}
  1. The richest structure. 437 distinct coefficients out of 512: the sketch is mostly heavy entries (439), which the last reduction kept with their own weights. Its top band (blocks 357,600 to 358,344) holds 0.5665 of the value, in the sketch and in the exact colour.
C^69818050(x)=0.0100038 x357814+0.00999311 x357928+0.00997362 x357875+0.0099514 x357858+η(x),508 terms with 433 coefficients, η(1)=0.960078 \begin{aligned} \hat C_{69818050}(x) ={}& 0.0100038\,x^{357814} \\ &+ 0.00999311\,x^{357928} \\ &+ 0.00997362\,x^{357875} \\ &+ 0.0099514\,x^{357858} \\ &+ \eta(x), \quad \text{508 terms with 433 coefficients},\ \eta(1) = 0.960078 \end{aligned}
  1. The youngest money of a deep colour. The sketch’s mean block is only 277 blocks before the transaction’s own, though its support is about 320,000 blocks: 99.58% of the value was minted in blocks 365,795 to 366,539, and the sketch puts the same 99.58% there.
C^77146563(x)=0.0336654 x366190+0.0335747 x366239+0.0335313 x366088+0.0334709 x366001+η(x),508 terms with 304 coefficients, η(1)=0.865758 \begin{aligned} \hat C_{77146563}(x) ={}& 0.0336654\,x^{366190} \\ &+ 0.0335747\,x^{366239} \\ &+ 0.0335313\,x^{366088} \\ &+ 0.0334709\,x^{366001} \\ &+ \eta(x), \quad \text{508 terms with 304 coefficients},\ \eta(1) = 0.865758 \end{aligned}
  1. The 2017 window, spending 2013 coins. In block 470,000, mid-2017, the newest block of the sketch is 229,223, from spring 2013; and the exact colour agrees at the bands’ resolution: none of its value was minted after block 229,459.
C^229491784(x)=0.0500903 x210595+0.05 x197851+0.0499097 x210667+0.048659 x192682+η(x),508 terms with 31 coefficients, η(1)=0.801341 \begin{aligned} \hat C_{229491784}(x) ={}& 0.0500903\,x^{210595} \\ &+ 0.05\,x^{197851} \\ &+ 0.0499097\,x^{210667} \\ &+ 0.048659\,x^{192682} \\ &+ \eta(x), \quad \text{508 terms with 31 coefficients},\ \eta(1) = 0.801341 \end{aligned}
  1. Pre-2016 money in 2022: a flat sketch. In the last block of the data, the sketch’s newest block is 391,528, from early January 2016. The exact colour is not quite so old: 0.051% of its value was minted after that block’s band, as late as blocks 495,425 to 496,169, in late 2017. Together those shares are about a quarter of τ=1/512\tau = 1/512; a light entry is kept with probability v/τv / \tau, and the sketch kept none of them. That is VarOpt sampling, not an error: in expectation they are there.
C^778613383(x)=1512 (x2717+x4596+⋯+x391528)⏟512 terms \begin{aligned} \hat C_{778613383}(x) ={}& \tfrac{1}{512}\,\underbrace{(x^{2717} + x^{4596} + \dots + x^{391528})}_{512\ \text{terms}} \end{aligned}
  1. The largest support. About 711,490 distinct blocks, 93% of the 762,261 that existed then, also as a flat sketch. Its 512 blocks are a sample of the whole chain: binned, it puts mass in 498 of the 1,023 bands where the colour has some, and its total variation distance from the binned colour is 0.42, yet at every one of the 1,024 band edges its CDF is within 0.0026 of the exact one (band-edge KS 0.00254), and its W1W_1 is 524 blocks, under four days.
C^778611720(x)=1512 (x3607+x7180+⋯+x761472)⏟512 terms \begin{aligned} \hat C_{778611720}(x) ={}& \tfrac{1}{512}\,\underbrace{(x^{3607} + x^{7180} + \dots + x^{761472})}_{512\ \text{terms}} \end{aligned}

Flat sketches. 543 of the 1,280 sketches of §10.10 are flat (flat in summary.tsv), as 9 and 10 are: 512 coefficients all equal to 1/5121/512. A sketch is flat when no entry of the merged parents' sketch exceeds the threshold τ\tau of the last reduction (Definition 1). Every entry is then light, each is kept with probability v/τv / \tau, and every kept one gets τ\tau; the mass is 1 and exactly kk entries are kept, so τ=1/k\tau = 1/k. A flat sketch is thus an equal-weight sample of 512 blocks, each drawn with probability proportional to its weight in the merged sketch, and is unbiased like any other.

Read with care. Each coefficient estimates the share of one block without bias (Theorem 7), but the estimate of a single light block is crude: it is τ\tau or 0. What a sketch gets right is the colour’s CDF, and the functionals of §5.1. The KS column of the table, against the binned exact colour, runs from 3×10−93 \times 10^{-9}, for colours made of heavy entries, to 0.00250.0025 for the flat sketches, a little over τ=1/512\tau = 1/512. That is allowed: the bound τ\tau of Corollary 4 is for one reduction against its own input, and through the recurrence the errors of the earlier reductions add to it (§6.3).

12. The Colour Surface

A colour is a probability distribution over the blocks (§5.1), and so is its sketch: the coefficients are nonnegative and sum to one (point 4 of Theorem 3). Set side by side in the order of the chain, the 778 million sketches make a surface over two time axes. One axis is the block a transaction is in, when its coins are spent. The other is the block they were minted in. The height is the share of the transaction’s colour minted there. This section draws that surface for the whole chain and reads it.

Too many transactions share a block for the surface to be drawn one transaction at a time, so it is drawn as an average. With BmB_m band mm of 745 blocks (the 1,024 bands of colors.bands1024.zst) and TsT_s the transactions in the blocks of band ss, less the coinbases,

P^(s,m)=1∣Ts∣∑t∈Ts  ∑b∈Bmc^t(b), \hat P(s, m) = \frac{1}{\lvert T_s \rvert} \sum_{t \in T_s} \; \sum_{b \in B_m} \hat c_t(b),

with c^t(b)\hat c_t(b) the coefficient of xbx^b in the production sketch of tt. Each column P^(s,⋅)\hat P(s, \cdot) is a probability distribution over minting bands. By Theorem 7 and linearity it is an unbiased estimate of P(s,m)P(s, m), the same average of the exact colours. Its error does not shrink like 1/∣Ts∣1 / \sqrt{\lvert T_s \rvert}, though. The transactions of one band share ancestors, and the sketch of an ancestor was reduced once and then handed down to all of them, so their errors are correlated. §12.6 measures the error against the exact colours.

Three things the average is not:

  • It is not weighted by value. Each transaction counts once, whatever it moves, so a column is the colour of a transaction drawn at random from its band, not the colour of the bitcoin that moved in it. Value weights need the transactions’ amounts, which neither the sketch file nor the count file holds.
  • “Minted in bb” means paid out by the coinbase of block bb, fees included, as in §5.1: a coinbase has the colour xbx^{b} whatever part of it is fees.
  • The age is the time since minting, measured through every transaction since the coinbase. It is not the time since the coins last moved, which is what the coin-age charts of chain analytics (HODL waves, coin days destroyed) measure.

12.1 How it was computed

Two modes of the crate compute this section. sketch surface reads the files once and writes a surface as sums, by minting band and by age band (<prefix>.mint.f64, <prefix>.age.f64), the transactions of each row (<prefix>.rows.f64) and its counters (<prefix>.surface.tsv). sketch surface-report turns a sketched and an exact surface into the tables and numbers of §12.2 to §12.6 and the series the figures draw, with the calendar from a file of each year’s first block.

  • The sketched surface. sketch surface reads the production file colors.sketch-varopt512.zst on its input and, beside it, the count file of §10.11 for each record’s block. It skips the first record of each block, the coinbase, and adds every other sketch, divided by its mass, to the row of its band. A coefficient at a block later than its transaction’s own would mean that the two files do not line up, and the mode fails on one.
  • The exact surface. With --bands-ref, the same mode reads the exact colours of colors.bands1024.zst, already binned in the same bands, parses the text on --threads and adds the lines in record order, so the sums do not depend on the number of threads.
zstd -dc --long=27 < colors.sketch-varopt512.zst \
  | sketch surface --counts colors.kmv1024.counts.zst --out all
sketch surface --counts colors.kmv1024.counts.zst --bands-ref colors.bands1024.zst \
  --threads 16 --out xall
sketch surface-report --sketched all --exact xall --years years.tsv --out report

The whole-chain surfaces all and xall were computed before these modes existed, by two small Rust programs outside the crate that do the same: surface-aggb, through a copy of the crate’s decoder, and surface-aggxp, with 16 threads parsing the text. surface-aggb read 778,613,440 records, skipped 762,261 coinbases and kept 777,851,179, in 2 h 00 min and 7 MB of memory; surface-aggxp took 4 h 22 min and 0.2 GB, with zstd’s single-threaded decompression as the limit (wall times and peak memory from /usr/bin/time). Both runs kept the same records in every row, and no coefficient sat at a block later than its transaction’s own. sketch surface gives the matrices of surface-aggb bit for bit on the first 3M and 30M records, and on the first 30M those of the single-threaded first version of surface-aggxp; the 16-thread version added in the order its threads finished, and differs from them by at most 2×10−122 \times 10^{-12} relative. sketch surface-report, run on the whole-chain all and xall, reproduces every table and number of §12.2 to §12.6, to the last digit of the Python scripts that first computed them, and refuses two surfaces whose rows differ. As a cross-check of the reader, on the first 3M records a version that reads the text of sketch decode agreed with the sketched surface to 10−1510^{-15} in the averaged surface (1.3×10−111.3 \times 10^{-11} in the raw sums).

The figures are drawn by a Python script outside the crate, from the two surfaces; the report’s surface-age-cdf.tsv, surface-columns.tsv and surface-ratio-curves.tsv hold the series of Figure 16, Figure 18(a) and Figure 17, equal to the script’s to the bit.

12.2 The surface

Two heatmaps over spending time from 2009 to 2022 on the horizontal axis. Left: minting time on the vertical axis; the colour fills the triangle below the diagonal, dark along the diagonal before 2012, then an even blue with horizontal steps at the halvings of 2012, 2016 and 2020 and a pale band along the bottom for coins minted in 2009 and early 2010. Right: the same data with the age of the coins, up to 14 years, on the vertical axis; the halvings become diagonal lines.
Figure 14: The colour surface of the whole chain, from the production sketches: the share of a transaction’s colour minted in each band of 745 blocks (about five days), averaged over the transactions of each spending band (coinbases left out), on a log scale. Each column sums to 1. (a) By minting time. (b) By age, spending time less minting time.

Figure 14 reads from left to right.

  • Before 2012, what is spent was just minted. The mass sits on the diagonal. Of the colour of a transaction of 2011, 59% was minted in the week before and 92% in the year before.
  • Then the mass spreads over the whole past. From 2012 each column covers nearly the whole triangle below the diagonal, at between 10−410^{-4} and 10−210^{-2} per band. By 2022 the median age is 8.1 years, and three quarters of the colour is older than four years (§12.4).
  • The halvings are horizontal steps, at minting blocks 210,000 (November 2012), 420,000 (July 2016) and 630,000 (May 2020). A block after a halving mints half as much, so it is half as large a share of everything that mixes it in. In (b), the same steps run along diagonals.
  • The coins of 2009 and early 2010 stay pale along the bottom of (a), all the way to 2022. They are spent far less often than their share of the supply (§12.5).
  • Dark patches in 2010 and 2011 are single holdings moving, such as the coins minted around blocks 20,000 to 35,000 and spent in late 2010. With few transactions per band in those years, one large holding is visible on its own.

The shares of 2011 and 2022 are rows of Table 19, and surface-check.tsv holds the checks behind the second and third readings: from 2012 on every cell below the diagonal is above zero, 99.3% of them between 10−410^{-4} and 10−210^{-2}, and in the colour of 2022 the ten bands before each halving carry 1.94 to 1.97 times the share of the ten after it.

12.3 In three dimensions

Figure 15: The surface of Figure 14(a) as a height, on cells of 2,980 × 2,980 blocks.A 3D surface over spending time and minting time, with a logarithmic height from one in a million to one. A sharp ridge rises along the diagonal at the early end, and a broad plateau slopes down toward the late end.

The same numbers as a height (Figure 15) show the shape at a glance: a ridge along the diagonal in the first years, then a plateau that falls slowly with age. The rest is hard to read. The near side hides the far one, the perspective changes how high things look, and no value can be read off. The halving steps, clear in Figure 14, are hard to find. The rest of the section reads the surface from the heatmap and from its slices; the 3D view is better suited to exploring the surface interactively than to a page.

12.4 The age of the coins that move

Left: one cumulative curve per year from 2011 to 2022 of the share of a transaction's colour younger than a given age, on a log age axis from one week to 13 years; the curves move right year by year. Right: the median, mean and 25-75 and 10-90 percent bands of the age against spending time; the median rises from near zero in 2012 to about 8.5 years at the end of 2022, with the exact median and mean drawn over the sketched ones.
Figure 16: The columns of Figure 14(b) as distributions of age. (a) For each year, the share of a transaction’s colour younger than a given age, averaged over the year’s transactions. (b) Quantiles and mean of the age in each spending band of 745 blocks from block 50,000 on, from the sketches; the dotted lines are the exact median and mean, from the exact surface, whose ages are differences of bands (§12.6).
Table 19: The age of the coins spent, per year: the columns of the surface averaged over the year’s transactions, coinbases left out. Ages in years since minting, from the block of each term of the sketches, binned in bands of 745 blocks (5.2 days); the shares at one week, one year and four years are interpolated inside a band. 2009, with only about 220 transactions besides its coinbases, is left out. From sketch surface-report, surface-age.tsv (the rows of the sketched surface); surface-tables.md prints the table as here.
year spenttransactionsmean agemedian ageunder a weekunder a yearover 4 years
2010117,8110.290.1622.0%91.9%0.0%
20111,845,9900.190.0158.8%92.1%0.0%
20128,393,8440.750.3518.7%72.0%0.0%
201319,550,0741.391.119.3%47.0%3.8%
201425,171,0921.791.367.7%45.2%13.6%
201545,625,1032.171.474.5%42.7%22.7%
201682,934,2512.832.232.8%32.0%34.5%
2017103,963,9563.943.821.7%17.8%48.4%
201881,173,2694.614.752.6%19.2%56.2%
2019119,946,9764.884.912.4%22.0%57.1%
2020111,939,0875.625.781.5%17.0%63.3%
202198,075,9656.817.281.3%9.9%72.4%
202279,113,5407.428.121.5%12.0%74.6%
  • Coins get older. The median age rose from 1.1 years in 2013 to 8.1 in 2022, when the chain was 13 years old. The rise was uneven: fastest from 2016 to 2017 and from 2020 to 2021 (+1.6 and +1.5 years), slowest from 2014 to 2015 and from 2018 to 2019 (+0.11 and +0.16).
  • Young coins don’t disappear. The share under a week old falls from 59% in 2011 to 1.3–2.6% from 2017 on, and the share under a year old falls to 10–22%. Since 2018 the mean has been below the median: the young part is small but pulls the mean down.
  • The jump at the turn of 2018 in (b), where the median moves from about 4 to 5 years within weeks, coincides with the rise and fall of the price in December 2017 and January 2018. The coins spent then were older than in the months around them.

12.5 What moves against what exists

Coins of every age exist, in known amounts: block bb mints a subsidy of 50⋅2−⌊b/210,000⌋50 \cdot 2^{-\lfloor b / 210{,}000 \rfloor} BTC. If the coins that move were a fair draw from the coins that exist, the colours of a year would put on each minting band its share of the supply. Figure 17 divides the one by the other.

Six curves, for the years spent 2012 to 2022 in steps of two, of the ratio of a minting band's share in the colours to its share in the supply, on a log axis against minting time. All start near 0.1 for 2009, cross 1 around 2012, stay between 1 and 2 in the middle years, and rise to between about 3 and 7.5 for the months just before the year spent.
Figure 17: For the transactions of a year: each minting band’s share of their colour (restricted to the bands minted before the year began, and renormalised) over its share of the coins those bands minted. The supply counts subsidies only; fees, a small part of most coinbases, are left out of it. Above 1, a band’s coins are spent more than their share; below 1, less.
Table 20: Shares of the colour (averaged over the year’s transactions) and of the supply, both over the coins minted before the year began. From sketch surface-report, surface-ratio.tsv (the colour and supply columns; the last column is prev_year).
year spentminted before 2010: colour / supplybefore 2011before block 210,000minted in the year before
20128.4% / 20.1%38.2% / 62.6%100.0% / 100.0%61.8% / 37.4%
20134.2% / 15.1%23.0% / 47.0%96.3% / 98.6%46.2% / 24.9%
20143.6% / 13.1%21.9% / 40.9%69.7% / 85.8%28.6% / 13.0%
20153.0% / 11.7%17.1% / 36.5%51.8% / 76.6%31.6% / 10.8%
20162.6% / 10.7%14.9% / 33.2%44.2% / 69.7%26.8% / 9.0%
20172.7% / 10.0%16.0% / 31.1%45.2% / 65.1%15.2% / 6.5%
20182.8% / 9.6%16.5% / 29.8%46.8% / 62.4%10.3% / 4.2%
20192.6% / 9.2%14.7% / 28.6%41.8% / 60.0%13.0% / 3.9%
20202.3% / 8.8%13.3% / 27.5%38.2% / 57.7%12.7% / 3.8%
20212.3% / 8.6%13.9% / 26.9%39.6% / 56.3%5.8% / 2.5%
20222.3% / 8.5%13.8% / 26.4%39.3% / 55.3%5.9% / 1.7%

The curves have three parts, and those of 2018, 2020 and 2022 lie almost on top of each other up to 2017:

  • The first year is spent least. In the colours of every year from 2013 on, coins minted in 2009 get about a quarter of their share of the supply (0.24 to 0.30 of it), and the oldest bands less than that. In 2022, coins minted before 2010 are 8.5% of the supply but 2.3% of a transaction’s colour. A coin enters a colour only once it moves, and many of the earliest coins never have: lost keys, or coins held since the first year, among them those of the earliest miners.
  • The middle is well mixed. Coins minted from 2012 to about two years before the year spent sit near their share, between about 0.8 and 2 times it.
  • The last months are spent most. The coins of the last month before the year get 2.8 to 6.2 times their share, and the curves rise toward it over the year before. In 2022, the coins minted in the year before, 2021, are 1.7% of the supply and 5.9% of a transaction’s colour. New coins pass through exchanges and payments before they come to rest.

The ratios are columns of surface-ratio.tsv too: ratio_before_2010 for the first year, the mixed_* spread of the bands in the middle, and ratio_last6 for the last month.

The comparison is between two different things: the supply counts bitcoin, and the colour is averaged over transactions. A value-weighted surface would compare like with like, and would need the amounts (§14).

12.6 Sketched against exact

Left: total variation distance between the sketched and the exact column, one point per spending band, on a log axis from about 1e-16 to 1e-1; tiny before 2011, up to about 1e-2 in 2011, and between about 6e-3 and 4e-2 from 2012 on. Right: the difference sketched minus exact for every cell of the triangle, on a symmetric log colour scale from -0.01 to 0.01; mostly pale, with horizontal stripes.
Figure 18: The sketched surface against the exact one, from colors.bands1024.zst. (a) The total variation distance between each sketched column and the exact column. (b) The difference per cell, on a symmetric log scale (linear below 10−510^{-5}).

The two surfaces were computed from the same 777,851,179 transactions, row for row, so any difference comes from the sketches. The numbers below are in surface-check.tsv, with the medians by year in surface-tv-years.tsv and the ages read from bands in the sketched-bands and exact-bands rows of surface-age.tsv; the 0.42 of a single sketch is from §11’s describe.tsv.

  • Columns. The total variation distance between a sketched column and the exact one is at most 0.0029 before 2011 and at most 0.010 in 2011, with few transactions and small colours. From 2012 on, where every column averages at least 27,512 sketches, it is between 0.006 and 0.040, and it grows slowly with time: the median column is at 0.013 in 2013 and at 0.034 in 2022. A single sketch is much further from its binned colour: 0.42 for the tenth sketch of §11.
  • Cells. No cell differs by more than 1.2×10−31.2 \times 10^{-3}, and 99% of the cells where the exact surface is not zero differ by less than 2.4×10−42.4 \times 10^{-4}.
  • Ages. Read the same way from both surfaces, as differences of bands, the mean age of a column is within 0.0028 years (one day) of the exact one in every column. The median is within 0.0044 years from 2012 on, and within 0.00014 years before, except in one 2009 column of two transactions. There the colour’s cumulative share is exactly one half over three empty bands, so the median is not unique and the two surfaces settle on ends 0.042 years (three bands) apart, although the columns themselves agree to within 10−810^{-8}. The shares of Table 19 read from both surfaces this way agree to three decimal places, and so do the 2009 colour shares behind Table 20. Divided by the supply share, they give a ratio of 0.273 sketched against 0.275 exact in 2022. (The table itself reads ages from the blocks of the sketches’ terms, which the exact file, binned, cannot give. Read from band differences, “under a week” is smaller, 44.8% against 58.8% in 2011: a coin minted at the end of a band and spent at the start of the next is one band old, however few blocks apart the two are.)

The errors do not cancel as they would if the sketches were independent. Figure 18(b) is striped along the spending axis: a minting band that a column overstates tends to be overstated in the columns after it too. That is what inherited sampling decisions do. When a reduction keeps or drops a light block for some transaction, every later transaction that spends those coins inherits the choice (§6.3). The surface is accurate to a few parts in a thousand for the questions of §12.4 and §12.5, which sum many cells. It is less accurate for a single cell, where the error can be a sizable fraction of the value.

13. Pictures of the Exact Colours

Below the wall of §5.3 the exact fold of §5.1 still runs, and the main binary draws what it computes. Section 12 averaged sketches over the whole chain; this section draws the head of the chain exactly, record by record, with nothing averaged and nothing sketched. Every picture here is made by coloring-bt-transactions, not by sketch.

13.1 One pixel per transaction and block

--png draws a row per record and a column per block id, each pixel saying what the colour says about that block: one bit under the unweighted backends --rings and --sets, eight under --weighted. --pdf (in a build with --features pdf) and --fold fold that onto a bounded canvas, shading each cell by how much of its rectangle is inked.

--palette reads the weighted samples through the colour ramp of §13.3 instead of as greys. The image data are byte for byte those of the greyscale run; the file grows by 780 bytes, a PLTE chunk of 256 colours and its header (the main binary’s documentation, src/main.rs). What the ramp buys is levels: grey has 254 and an eye reads perhaps thirty, and these weights live in a fraction of a percent.

13.2 The first million, exactly

Figure 19 to Figure 22 are four --fold pages over the head of the 2022 chain, two readings of each of two spans. The readings are the support, under --sets, and the colour CtC_t of (1), under --weighted; §5.1 says why the two share their blocks and differ only in the coefficients. The spans are the 1,000,001 records the driver stops at by default, and 1,024 records, at one row a record, around the Mt.Gox proof-of-reserves. Nothing in them is a projection or a sketch: every cell is drawn from whole colours, each kept until its transaction’s last output is spent, the census rule of §5.3, with no release oracle.

Each page is one greyscale canvas, with no --palette: at most 1024×10241024 \times 1024 cells, each shaded by its coverage through the gamma 1/2.21/2.2 that the driver fixes as TONE in src/image.rs, which lifts sparse ink and keeps its order. The four canvases come from four runs over the records (the script make_provenance_figures.sh of the main binary’s write-up):

coloring-bt-transactions 1000001 --sets --fold history_sets.png < finalBCUTXO_2022.scm
coloring-bt-transactions 1000001 --weighted --gain 1000 --fold history_weighted.png < finalBCUTXO_2022.scm
coloring-bt-transactions --sets --rows 830362..831386 --fold window_sets.png < finalBCUTXO_2022.scm
coloring-bt-transactions --weighted --rows 830362..831386 --gain 2000 --fold window_weighted.png < finalBCUTXO_2022.scm

figs_exact.py, a script outside the crate, adds only the axes and, on the two window pages, the blue marker, and embeds every canvas cell as one image pixel. Timed one at a time under /usr/bin/time -v, at a load average of 3, the support of the history takes 74.5 s and 5.36 GiB, and its weighted page 86.0 s and 16.78 GiB, most of it the 15.2 GB (14.2 GiB) of distinct terms that Table 1 counts at a million records; the two windows take 25.9 s and 25.3 s. These times are quoted from a comment in that script; no log was kept.

A weighted page drawn plainly is near white, because the ink in it genuinely is. Each weighted run therefore declares a --gain, 1000 over the history and 2000 over the window, and its caption quotes it. The gain lifts ink before the gamma and full coverage caps it, so these shades order cells and do not measure them.

A greyscale picture of the first 1,000,001 records, top to bottom, against block ids 0 to 135,659, left to right. Everything right of a frontier curve that bends from the top left down to the bottom right is white; below it the picture is almost solid grey, crossed by white vertical bands of blocks whose coins sat unspent.
Figure 19: The support of the first 1,000,001 records, as a picture of 135,659 block ids by 1,000,001 records folded onto 1024×10241024 \times 1024 cells. A row is about 977 records in file order and a column about 133 block ids, and each cell is shaded by how much of its rectangle is inked, through the gamma 1/2.21/2.2. A transaction cannot descend from a block after its own, so the picture is white right of the frontier curve. Below it dependency is near-total: 95.6% of the cells carry ink, broken by white bands of value that sat unspent. Main binary: coloring-bt-transactions 1000001 --sets --fold history_sets.png < finalBCUTXO_2022.scm; page drawn by figs_exact.py (§13.2).
The same records and block ids in greyscale, now weighted by value: the area below the frontier is mostly near white, with the ink concentrated in a dark rim along the frontier curve and in a few vertical streaks in the first 300,000 records.
Figure 20: The same 1,000,001 records under --weighted --gain 1000: the colour CtC_t of (1) rather than its support, on the cells of Figure 19 (about 977 records by 133 block ids, gamma 1/2.21/2.2). The declared gain lifts every cell’s ink before the gamma, so shades order cells but do not measure them. Value concentrates along the frontier, because coins mostly move soon after they are minted, and the deep history that dominates the support carries almost none of it. Main binary: coloring-bt-transactions 1000001 --weighted --gain 1000 --fold history_weighted.png < finalBCUTXO_2022.scm.

The two pages read together. The 95.6% of Figure 19 counts the cells left of the running maximum of each row’s rightmost inked column, as figs_exact.py computes from the canvas. The weighted page is the exact, record-by-record form of the first reading of §12.2, “before 2012, what is spent was just minted”: the value sits in a dark rim along the frontier. Side by side, the pages are the contrast of §10.1 between JJ and JwJ_w: old supports are shared, while a colour’s weight sits on its recent blocks.

--rows draws a window and still colours everything in front of it: the 1,024 rows of Figure 21 and Figure 22 inherit from all 830,362 records before them, folded and not drawn. The row axis is the record ordinal, not the transaction id (the two BIP-30 duplicates of §5.2 put the ordinal two ahead of the id from record 142,842). The proof-of-reserves, transaction 830,874, is therefore record 830,876 here, row 514 of the window counting from 0, in block 132,749; on the canvas its row is inked across 1,014 of the 1,024 columns, and the two rows above it across one. No row is blank. In 882 of the 1,024 rows the newest block of the colour lies within ten columns of the right edge, about 1,300 blocks or nine days, but not in all: in the other 142 it lies further left, and in five of them before column 500 (these counts are read off the canvas by canvas_rows.py, a script kept with figs_exact.py). These pictures were first drawn for a companion article on the Mt.Gox cases, which draws their spend trees with tree-pdf, another binary of the crate; they are kept here because they are pictures of the colour and not of any one case.

1,024 records, one row each, from record 830,362 at the top to 831,385 at the bottom, against block ids 0 to 132,765. Most rows show only a speck at the right edge; about one in six is a black line across nearly the whole width. A blue wedge on the left marks record 830,876, one of the full-width rows.
Figure 21: One row a record: the support of the 1,024 records 830,362 to 831,385, under --sets --rows 830362..831386, every record before them coloured but not drawn. The 132,765×1,024132{,}765 \times 1{,}024 picture is folded onto cells of one record by about 130 block ids, gamma 1/2.21/2.2. The blue wedge marks the Mt.Gox proof-of-reserves: transaction 830,874, record 830,876, in block 132,749 of June 2011. Its row is inked across 1,014 of the 1,024 columns. Most rows are narrow, everyday payments with shallow provenance; the full-width bands are transactions whose coins descend from essentially every era of the chain. Main binary: coloring-bt-transactions --sets --rows 830362..831386 --fold window_sets.png < finalBCUTXO_2022.scm.
The same 1,024 records weighted by value: nearly white, faint dotted lines where the support page had full-width bands, a dark scatter in the last few columns on the right, and the blue wedge at record 830,876.
Figure 22: The same 1,024 records around the proof-of-reserves (blue wedge, record 830,876) under --weighted --gain 2000, on the cells of Figure 21: one record by about 130 block ids, gamma 1/2.21/2.2. The declared gain lifts ink before the gamma, so shades order cells but do not measure them. Even the full-width bands fade, except where real value rides old blocks. Main binary: coloring-bt-transactions --weighted --rows 830362..831386 --gain 2000 --fold window_weighted.png < finalBCUTXO_2022.scm.

13.3 A ramp that reads

The ramp of --palette is built in Oklab,Björn Ottosson. A perceptual color space for image processing. Blog post, December 2020. URL https://bottosson.github.io/posts/oklab/ not in HSL. HSL’s lightness is not luminance and its hue circle is far from uniform (yellow at 60∘60^\circ and blue at 240∘240^\circ have nominally the same lightness and are nothing of the sort), so a ramp built in it has bands where the eye sees a step that is not there. For a picture whose purpose is to compare magnitudes that is not cosmetic.

Lightness carries the magnitude, monotonically, which keeps the picture readable in grey, readable to a colour-deficient eye, and readable where it is folded so small that a cell is a sample rather than a shape. Hue and chroma only separate levels that lightness leaves adjacent. Most of the chroma one would like at the dark end is outside sRGB. Clamping the channels there shifts the hue and flattens the sweep, so the gamut mapping holds lightness and hue fixed and bisects the chroma down until the colour fits: 256 colours, computed once (src/oklch.rs).

Figure 23: The --palette ramp of src/oklch.rs, from paper on the left to the heaviest ink on the right (the PLTE chunk stores it in the reverse order, ink first), drawn from the write-up’s ramp.png, which matches ramp() entry for entry. Lightness falls monotonically. The hue sweeps an arc of about 250∘250^\circ rather than the full circle, so the ends stay apart.A horizontal strip shading from near-white on the left through pale blue, teal, green and ochre to a dark wine red on the right.

13.4 One pixel per transaction

The main binary’s examples/tint.rs (cargo run --release --example tint) reads a --moments file, colors.moments.zst of §5.2, and draws each transaction as one pixel: the mean block to hue over an arc of 250∘250^\circ, and the concentration 1/(1+spread/45,000)1/(1 + \text{spread}/45{,}000) to chroma. Over the whole chain that picture is nearly one colour, and the reason is the data, not the drawing. The median spread is about 164,850 blocks, so 80% of the records have a concentration between 0.18 and 0.33 and only 3.4% exceed 0.5; and 80% of the hues fall in a stretch of about 39∘39^\circ of the arc, because the mean climbs with the record index. (These figures are quoted from the main binary’s write-up. tint_stats.c, a program kept with the runs’ evidence outside the crate, recounts them over all 778,613,440 lines of colors.moments.zst and agrees: a median spread of 164,852 blocks, concentrations from 0.180 to 0.330 between the 10th and 90th percentiles, 3.39% above 0.5, and 38.8° between the 10th and 90th percentile hues.) A fixed scale on a quantity this skewed spends the channel on a few transactions, so the picture is not shown here. Its two questions, when the coins were minted and how mixed they are, are asked elsewhere on axes that read: the first by the colour surface of §12, on two time axes; the second by the spread of §5.1, whose sketched error section 8 measures.

One lesson of the attempt stands, and it is about a scalar. Averaging the tints of the transactions that fall in a cell makes the cell nearly a function of its own position, for the same reason, so a binned picture of tints should sample one transaction per cell. Section 12 does average, but whole distributions rather than one number a transaction: the average of colours is again a distribution over the minting bands, a column is the expected colour of a transaction drawn at random from its band, and the structure that a tint would flatten (the diagonal, the halving steps) survives in it. What that average gives up is how the transactions of one band differ from one another.

tint --index also writes the tint as one byte a record: 778,614,320 bytes for the chain, an 80-byte header, a 768-byte palette, the 778,613,440 bytes and 32 bytes for the four places where the transaction id breaks its sequence (examples/tint.rs).

14. What Is Left

  • Bias at k≥512k \ge 512. Pass B ran one seed; the 3-seed test covers k=64k = 64 and 256256 only, and its 95% bounds (11.4% and 16.7% of the mean absolute error) are loose. More seeds would tighten both.
  • k=1024k = 1024 in production. Its accuracy is measured; its emit size, time and memory are projected. A 100M-record emit would firm them up (compare the first 100M records at k=512k = 512: 34.3 GB with -12; a ratio above 2.3 would mean the 659–721 GB bracket is low).
  • Why varopt’s error does not grow with depth. Corollary 12 proves the 1/k1/k rate at every record, with a factor At\sqrt{A_t} that is allowed to grow with depth; that the error relative to the colours’ spread stays flat, as measured, is not proved (§6.3). The control for the stratification explanation, VarOpt with its lights chosen in random order, was run only with the design-phase prototype on a prefix of the chain (§6.4); repeating it with the final binary over the whole chain is open. So is a direct look at the bound. On the first 3M records, where the exact colours are known, AtA_t and ∑r⪯tαt,r2τr2\sum_{r \preceq t} \alpha_{t,r}^2 \tau_r^2 could be computed record by record. AtA_t is the squared norm of row tt of (𝐈−Γ)−1(\mathbf{I} - \Gamma)^{-1} (§6.3), a solve with the identity on the right. Its rows hold an entry for every ancestor record rather than every ancestor block, so it is a heavier solve than the exact colours, and whether it fits on that prefix has not been measured. That would show whether the error stays flat because these sums stay small under mixing, or because the errors of different reductions cancel.
  • Literal bottom-kk against VarOpt. The literal weighted bottom-kk sketch of sections 2–4 is prio, and here it loses by 6–21×; the exponential (PPSWOR) ranks of §2.2 were tried in the design phase and were no different from priority ranks. Whether some bottom-kk variant can recover the 1/k1/k rate (for instance by making the choice among the lights systematic, which is what VarOpt does) is open.
  • The band-based floors. The figure of TV1024 against its floor has to be redrawn with each row’s own τ\tau before it can be shown; the numbers in §8.8 are the corrected ones.
  • --long=27 sizes at k=64k = 64, 256256 and 10241024 are estimates: at k=64k = 64 from the 36.4% saving measured at k=128k = 128, at k=256k = 256 from its own 40.7% measured over 0–350M, and at k=1024k = 1024 from an assumed saving of about 42%, extrapolated from the rise with kk. At k=512k = 512 the production run measured 172.7 GB, just below its estimate of 175–190 GB.
  • The permutation is pseudo-random. The exact unbiasedness of §10.4–10.5 is a theorem about a uniform permutation; the code draws a Fisher–Yates shuffle from a hash. The seed tests of §10.9 and the uniformity test T-K1 are the evidence that the difference is harmless, and a change to the shuffle or the hash must rerun them.
  • One permutation per run. Every count and every cell of a matrix shares it, so errors are correlated across records and cells, and a single run can say nothing about bias. The production count file is one seed; R4 computed seeds 2 and 3 beside it but they are not shipped.
  • Other weighted similarities. The Euclidean distance and the cosine of two colours would need a store of Gaussian projections, and the Jensen–Shannon divergence one of entropy sketches (§10.7); both would fold as the l1 store does, and neither was built. The KS distance between two varopt sketches is written by pairs but not checked against the exact colours.
  • Weighted similarity near the floor. The L1 store’s floor is 0.0088 at m=1024m = 1024, so pairs with smaller JwJ_w cannot be told apart one by one; a larger mm lowers the floor only as 1/m1/\sqrt m. On the prefix that is most deep pairs across time (92% below 0.01); over the whole chain it is a fifth of the chain pairs and almost none inside a window. The f32 fold was checked against f64 on the first 3M records and, at full depth, only on the 1,280 records R5 selected (7.8×10−57.8 \times 10^{-5} relative at worst). L1 against the exact JwJ_w was checked on the prefix only: no record of the whole-chain selections has an unreduced varopt sketch to compare with. At full depth there is only the band lower bound of §10.10, which holds but is loose inside a window.
  • A weighted sample that keeps the subset lemma. Ranks ub/g(b)u_b / g(b) with a fixed function gg of the block keep Lemma 21, so they would fold exactly with exact weights, sampling blocks by a prior rather than by the colour. Which gg (recency, minted value) would serve JwJ_w or the functionals of §5.1 is open, and so is whether a weighted MinHash outside the class of Proposition 29 can compose under sums. The probability Jaccard index of Moulton and Jiang is not a function of L1, and no composing sketch for it is known here.
  • Containment is often undefined for a small support against a large one (27% of the ordered even pairs of the prefix one way, 14% the other; 0.78% of the cells of the whole-chain matrix), and its estimate is consistent but not unbiased: the inclusive threshold of the code biases it up by up to about c(1−c)/kc(1 - c)/k (the full amount when AA is smaller than BB). A strict threshold showed no bias in simulation; adopting it changes the output of pairs, so it waits for a new version. The fallback J^n^u/n^A\hat J \hat n_u / \hat n_A is a biased ratio and is flagged.
  • More of the sketch for Jaccard. Both sketches are complete below the smaller threshold, so up to 2k2k elements of the union are known; an estimator that uses them could lower the variance at small JJ.
  • KMV and L1 sketches of every record are not stored. At k=1024k = 1024 the KMV ones would take about 3.2 TB. The counts are stored, and so is the varopt:512 colour of every record (§9); KMV and L1 sketches exist only for selections, and a new selection needs a new fold (about 70 minutes, as R5 took).
  • A value-weighted surface. The surface of §12 counts every transaction once. Weighted by the amounts, it would be the colour of the bitcoin that moved, and its comparison with the supply in §12.5 would be like with like. The amounts are not in the sketch file or the count file, so it needs one more pass over the chain with them, or over the share matrix of §7.12, which holds them (10.6 GB, not kept). The time since coins last moved, which coin-age charts use, is a different recurrence and is not in the colours at all.
  • sketch does not read the share matrix. Its runs parse the 150 GB of text (§7.12); reading the matrix through the main binary’s reader would save the parse of every pass.
  • The universe. Blocks must stay below 220=1,048,5762^{20} = 1{,}048{,}576, which at 144 blocks a day the chain passes in about 2028; :bits=21 doubles the tables to 16 MiB.

15. Notes and References

15.1 Further reading

  • Sampling theory. Horvitz and Thompson (1952) introduced the estimator that weights each sampled item by the inverse of its inclusion probability; every weight and linear-functional estimate of the priority and VarOpt sketches in this post, from priority sampling’s max⁡(wi,1/τ)\max(w_i, 1/\tau) (§2.3, with rank threshold τ\tau) to the weight threshold τ\tau carried by a kept light in VarOpt (§6.1), is one of them (the KMV counts, the Jaccard and containment ratios, and the Cauchy-scale L1 estimates of §1 and §10 are not). Madow (1949) belongs to the classical theory of systematic sampling, the design that §6.1 runs along the block axis. Chao (1982) is a fixed-size plan with unequal probabilities in which units enter the sample one at a time; the stream VarOptk_k of Cohen et al.Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Stream sampling for variance-optimal estimation of subset sums. In Proceedings of the Twentieth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA '09, pages 1255–1264. Society for Industrial and Applied Mathematics, 2009a. doi: 10.1137/1.9781611973068.136. URL https://doi.org/10.1137/1.9781611973068.136 (one random eviction per arrival) draws exactly the same distribution of samples, while the systematic scheme of §6.1 keeps its inclusion probabilities but not its joint distribution.
  • Resampling in particle filters. Kitagawa (1996) and Carpenter et al. (1999) introduced stratified and systematic resampling. Fearnhead and Clifford (2003) keep the particles above a threshold and resample the rest at the threshold’s weight. That is the reduction of §6.1, which they prove optimal among unbiased resampling schemes. Moral (2004) analyses particle systems through the decomposition of their error into the noises of the resampling steps, the analogue of §6.3. Gerber and Chopin (2015) beat the Monte Carlo rate by ordering the particles and using quasi-random points, and Gerber et al. (2019) prove that ordering speeds up stratified resampling. That is the gain of the block order in §6.4.
  • Order sampling. Rosén (1997) studies the designs that give every unit an independent random ranking variable and keep the nn smallest: both rank families of §2.2 are of this kind. With the uniform ranks ui/wiu_i/w_i it is the sequential Poisson sampling of Ohlsson (1998), devised for the Swedish Consumer Price Index; with exponential ranks it is sampling without replacement with probability proportional to weight.
  • Priority sampling and VarOpt. Duffield et al. (2007) is the source of §2–3: priority sampling, its unbiasedness and its zero covariances. Szegedy (2006) proved the near-optimality they had conjectured. Cohen et al. (2009a), in its journal version Cohen et al. (2011b), define VarOptk_k, whose estimates minimise the average variance over the subsets of every size; §6.1 keeps two of their three requirements and trades the third for the block order.
  • Bottom-kk sketches. Cohen and Kaplan (2007) treat bottom-kk sketches as one family parametrised by the rank distribution, and Cohen and Kaplan (2008) derive their Horvitz–Thompson estimators by rank conditioning, the argument of §3. Thorup (2013) shows how little independence the hash function needs, for bottom-kk and for priority sampling alike. Cohen (1997) folds min-rank sketches through a graph to estimate the size of every node’s reachability set, the fold of §10.3.
  • Counting distinct elements. Bar-Yossef et al. (2002) keep the kk smallest hash values; Beyer et al. (2007) name the KMV synopsis, prove the (k−1)/v(k)(k - 1)/v_{(k)} estimator of §1.2 unbiased, and extend it to multiset unions, intersections and differences. Flajolet et al. (2007) is the right-hand column of the table of §1.3, with a standard error of about 1.04/m1.04/\sqrt{m} for mm registers, and Broder (1997) the origin of MinHash and of resemblance as the Jaccard index of shingle sets.
  • Structure and coordination. Cohen et al. (2011a) design VarOpt samples that respect an order or a hierarchy on the keys, so that range sums (here, the cuts of a colour’s CDF) are much more accurate; their appendix on ordered keys sets systematic sampling beside them, which is the choice §6.1 makes. Cohen et al. (2009b) coordinate samples of many weight assignments over the same keys through shared ranks, as coord does over the blocks in §6.6.
  • Weighted similarity of distributions. Manasse et al. (2010) define consistent weighted sampling, a MinHash for vectors whose collision probability is the weighted Jaccard similarity, and Ioffe (2010) makes it run in constant time per nonzero weight. Moulton and Jiang (2018) argue that for probability distributions, such as two colours, the natural generalisation of the Jaccard index is a different one, and give a MinHash for it, P-MinHash, whose ranks are those of Proposition 29. None of them composes through the sums of the colour recurrence; §10.6 uses instead that for distributions the weighted Jaccard similarity is a function of the L1 distance.
  • Stable projections. Indyk (2006) sketches the L1 distance of streamed vectors by projections with Cauchy entries, which are linear and therefore follow any sequence of updates, including the mixtures of §5.1; Li et al. (2007) study estimators of the scale from Cauchy projections, among them the maximum likelihood estimator of §10.6, and their tail bounds. Jowhari et al. (2011) give LpL_p samplers, linear sketches from which a coordinate can be drawn in proportion to its weight, the weighted sampling that does compose under sums (§10.6).
  • Sparse triangular solves. Gilbert and Peierls (1988) solve a sparse triangular system in time proportional to the arithmetic, by first finding the nonzeros of the solution as the nodes reachable in the graph of the matrix, the fill-in that §5.3–5.4 measure; Davis (2006) (chapter 3) gives the algorithm and its code.
  • Martingales. Williams (1991) covers what §6.2–6.3 use: conditional expectation, the tower property, and the orthogonality of martingale differences.
  • Bitcoin and taint. Nakamoto (2008) describes the chain whose transactions are coloured here. Möser et al. (2014) define the poison and haircut blacklisting policies, the second of which is the recurrence of §5.1 read for one set of blocks; Anderson et al. (2018) propose first-in-first-out tracing instead, which in their case studies taints far fewer addresses than haircut.
  • Randomness. Steele et al. (2014) is the SplitMix generator whose output function hashes every draw of §7.4. The permutation of §10.8 is the shuffle of Fisher and Yates in Durstenfeld’s in-place form, Algorithm P of Knuth’s §3.4.2.Donald E. Knuth. The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, Massachusetts, 3rd edition, 1997. ISBN 0201896842. URL https://www-cs-faculty.stanford.edu/~knuth/taocp.html

15.2 References

  1. Edith Cohen and Haim Kaplan. Summarizing data using bottom-k sketches. In Proceedings of the Twenty-Sixth Annual ACM Symposium on Principles of Distributed Computing, PODC '07, pages 225–234. Association for Computing Machinery, 2007. doi: 10.1145/1281100.1281133. URL https://doi.org/10.1145/1281100.1281133.
  2. Ziv Bar-Yossef, T. S. Jayram, Ravi Kumar, D. Sivakumar, and Luca Trevisan. Counting Distinct Elements in a Data Stream. In José D. P. Rolim and Salil Vadhan, editors, Randomization and Approximation Techniques in Computer Science: 6th International Workshop, RANDOM 2002, volume 2483 of Lecture Notes in Computer Science, pages 1–10. Springer, 2002. doi: 10.1007/3-540-45726-7_1. URL https://doi.org/10.1007/3-540-45726-7_1.
  3. Andrei Z. Broder. On the resemblance and containment of documents. In Proceedings. Compression and Complexity of SEQUENCES 1997, pages 21–29. IEEE Computer Society, 1997. doi: 10.1109/SEQUEN.1997.666900. URL https://doi.org/10.1109/SEQUEN.1997.666900.
  4. Kevin Beyer, Peter J. Haas, Berthold Reinwald, Yannis Sismanis, and Rainer Gemulla. On synopses for distinct-value estimation under multiset operations. In Proceedings of the 2007 ACM SIGMOD International Conference on Management of Data, SIGMOD '07, pages 199–210. Association for Computing Machinery, 2007. doi: 10.1145/1247480.1247504. URL https://doi.org/10.1145/1247480.1247504.
  5. Mikkel Thorup. Bottom-k and priority sampling, set similarity and subset sums with minimal independence. In Proceedings of the Forty-Fifth Annual ACM Symposium on Theory of Computing, STOC '13, pages 371–380. Association for Computing Machinery, 2013. doi: 10.1145/2488608.2488655. URL https://doi.org/10.1145/2488608.2488655.
  6. Philippe Flajolet, Éric Fusy, Olivier Gandouet, and Frédéric Meunier. HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm. In 2007 Conference on Analysis of Algorithms (AofA 07), volume AH of DMTCS Proceedings, pages 137–156, 2007. doi: 10.46298/dmtcs.3545. URL https://doi.org/10.46298/dmtcs.3545.
  7. D. G. Horvitz and D. J. Thompson. A Generalization of Sampling Without Replacement from a Finite Universe. Journal of the American Statistical Association, 47(260):663–685, 1952. doi: 10.1080/01621459.1952.10483446. URL https://doi.org/10.1080/01621459.1952.10483446.
  8. Edith Cohen and Haim Kaplan. Tighter estimation using bottom k sketches. Proceedings of the VLDB Endowment, 1(1):213–224, 2008. doi: 10.14778/1453856.1453884. URL https://doi.org/10.14778/1453856.1453884.
  9. Bengt Rosén. Asymptotic theory for order sampling. Journal of Statistical Planning and Inference, 62(2):135–158, 1997. doi: 10.1016/S0378-3758(96)00185-1. URL https://doi.org/10.1016/S0378-3758(96)00185-1.
  10. Nick Duffield, Carsten Lund, and Mikkel Thorup. Priority sampling for estimation of arbitrary subset sums. Journal of the ACM, 54(6), December 2007. doi: 10.1145/1314690.1314696. URL https://doi.org/10.1145/1314690.1314696. Article 32.
  11. Esbjörn Ohlsson. Sequential Poisson Sampling. Journal of Official Statistics, 14(2):149–162, 1998. URL https://www.scb.se/contentassets/ca21efb41fee47d293bbee5bf7be7fb3/sequential-poisson-sampling.pdf.
  12. Mario Szegedy. The DLT priority sampling is essentially optimal. In Proceedings of the Thirty-Eighth Annual ACM Symposium on Theory of Computing, STOC '06, pages 150–158. Association for Computing Machinery, 2006. doi: 10.1145/1132516.1132539. URL https://doi.org/10.1145/1132516.1132539.
  13. Satoshi Nakamoto. Bitcoin: A Peer-to-Peer Electronic Cash System, 2008. URL https://bitcoin.org/bitcoin.pdf.
  14. Malte Möser, Rainer Böhme, and Dominic Breuker. Towards Risk Scoring of Bitcoin Transactions. In Rainer Böhme, Michael Brenner, Tyler Moore, and Matthew Smith, editors, Financial Cryptography and Data Security: FC 2014 Workshops, BITCOIN and WAHC 2014, volume 8438 of Lecture Notes in Computer Science, pages 16–32. Springer, 2014. doi: 10.1007/978-3-662-44774-1_2. URL https://doi.org/10.1007/978-3-662-44774-1_2.
  15. Ross Anderson, Ilia Shumailov, Mansoor Ahmed, and Alessandro Rietmann. Bitcoin Redux. Workshop on the Economics of Information Security (WEIS 2018), Innsbruck, June 2018. URL https://www.cl.cam.ac.uk/~rja14/Papers/bitcoin-redux.pdf.
  16. Tin Tironsakkul, Manuel Maarek, Andrea Eross, and Mike Just. Probing the Mystery of Cryptocurrency Theft: An Investigation into Methods for Taint Analysis, 2019. URL https://arxiv.org/abs/1906.05754. arXiv:1906.05754.
  17. John R. Gilbert and Tim Peierls. Sparse partial pivoting in time proportional to arithmetic operations. SIAM Journal on Scientific and Statistical Computing, 9(5):862–874, 1988. doi: 10.1137/0909058. URL https://doi.org/10.1137/0909058.
  18. Timothy A. Davis. Direct Methods for Sparse Linear Systems. Fundamentals of Algorithms. Society for Industrial and Applied Mathematics, 2006. doi: 10.1137/1.9780898718881. URL https://doi.org/10.1137/1.9780898718881.
  19. Edith Cohen. Size-estimation framework with applications to transitive closure and reachability. Journal of Computer and System Sciences, 55(3):441–453, 1997. doi: 10.1006/jcss.1997.1534. URL https://doi.org/10.1006/jcss.1997.1534.
  20. William G. Madow. On the Theory of Systematic Sampling, II. The Annals of Mathematical Statistics, 20(3):333–354, 1949. doi: 10.1214/aoms/1177729988. URL https://doi.org/10.1214/aoms/1177729988.
  21. M. T. Chao. A general purpose unequal probability sampling plan. Biometrika, 69(3):653–656, 1982. doi: 10.1093/biomet/69.3.653. URL https://doi.org/10.1093/biomet/69.3.653.
  22. Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Efficient Stream Sampling for Variance-Optimal Estimation of Subset Sums. SIAM Journal on Computing, 40(5):1402–1431, 2011b. doi: 10.1137/10079817X. URL https://doi.org/10.1137/10079817X.
  23. Paul Fearnhead and Peter Clifford. On-line inference for hidden Markov models via particle filters. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 65(4):887–899, 2003. doi: 10.1111/1467-9868.00421. URL https://doi.org/10.1111/1467-9868.00421.
  24. Edith Cohen, Graham Cormode, and Nick Duffield. Structure-aware sampling: flexible and accurate summarization. Proceedings of the VLDB Endowment, 4(11):819–830, 2011a. doi: 10.14778/3402707.3402721. URL https://doi.org/10.14778/3402707.3402721.
  25. Lek-Heng Lim and Jonathan Weare. Fast Randomized Iteration: Diffusion Monte Carlo through the Lens of Numerical Linear Algebra. SIAM Review, 59(3):547–587, 2017. doi: 10.1137/15M1040827. URL https://doi.org/10.1137/15M1040827.
  26. Samuel M. Greene, Robert J. Webber, Jonathan Weare, and Timothy C. Berkelbach. Beyond Walkers in Stochastic Quantum Chemistry: Reducing Error Using Fast Randomized Iteration. Journal of Chemical Theory and Computation, 15(9):4834–4850, 2019. doi: 10.1021/acs.jctc.9b00422. URL https://doi.org/10.1021/acs.jctc.9b00422.
  27. Samuel M. Greene, Robert J. Webber, Timothy C. Berkelbach, and Jonathan Weare. Approximating Matrix Eigenvalues by Subspace Iteration with Repeated Random Sparsification. SIAM Journal on Scientific Computing, 44(5):A3067–A3097, 2022. doi: 10.1137/21M1422513. URL https://doi.org/10.1137/21M1422513.
  28. Jonathan Weare and Robert J. Webber. Randomly Sparsified Richardson Iteration: A Dimension-Independent Sparse Linear Solver, 2023. URL https://arxiv.org/abs/2309.17270. arXiv:2309.17270.
  29. Pierre Del Moral. Feynman-Kac Formulae: Genealogical and Interacting Particle Systems with Applications. Probability and Its Applications. Springer, 2004. doi: 10.1007/978-1-4684-9393-1. URL https://doi.org/10.1007/978-1-4684-9393-1.
  30. Mathieu Gerber and Nicolas Chopin. Sequential quasi Monte Carlo. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 77(3):509–579, 2015. doi: 10.1111/rssb.12104. URL https://doi.org/10.1111/rssb.12104.
  31. Mathieu Gerber, Nicolas Chopin, and Nick Whiteley. Negative association, ordering and convergence of resampling methods. The Annals of Statistics, 47(4):2236–2260, 2019. doi: 10.1214/18-AOS1746. URL https://doi.org/10.1214/18-AOS1746.
  32. Harald Niederreiter. Random Number Generation and Quasi-Monte Carlo Methods, volume 63 of CBMS-NSF Regional Conference Series in Applied Mathematics. Society for Industrial and Applied Mathematics, 1992. doi: 10.1137/1.9781611970081. URL https://doi.org/10.1137/1.9781611970081.
  33. Yichao Li, Wenshuo Wang, Ke Deng, and Jun S. Liu. Stratification and optimal resampling for sequential Monte Carlo. Biometrika, 109(1):181–194, 2022. doi: 10.1093/biomet/asab004. URL https://doi.org/10.1093/biomet/asab004.
  34. Beltran Borja Fiz Pontiveros, Mathis Steichen, and Radu State. Mint Centrality: A Centrality Measure for the Bitcoin Transaction Graph. In 2019 IEEE International Conference on Blockchain and Cryptocurrency (ICBC). IEEE, May 2019. doi: 10.1109/BLOC.2019.8751401. URL https://doi.org/10.1109/BLOC.2019.8751401.
  35. Edith Cohen, Nick Duffield, Haim Kaplan, Carsten Lund, and Mikkel Thorup. Stream sampling for variance-optimal estimation of subset sums. In Proceedings of the Twentieth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA '09, pages 1255–1264. Society for Industrial and Applied Mathematics, 2009a. doi: 10.1137/1.9781611973068.136. URL https://doi.org/10.1137/1.9781611973068.136.
  36. Genshiro Kitagawa. Monte Carlo filter and smoother for non-Gaussian nonlinear state space models. Journal of Computational and Graphical Statistics, 5(1):1–25, 1996. doi: 10.1080/10618600.1996.10474692. URL https://doi.org/10.1080/10618600.1996.10474692.
  37. James Carpenter, Peter Clifford, and Paul Fearnhead. Improved particle filter for nonlinear problems. IEE Proceedings – Radar, Sonar and Navigation, 146(1):2–7, 1999. doi: 10.1049/ip-rsn:19990255. URL https://doi.org/10.1049/ip-rsn:19990255.
  38. David Williams. Probability with Martingales. Cambridge University Press, 1991. doi: 10.1017/CBO9780511813658. URL https://doi.org/10.1017/CBO9780511813658.
  39. Edith Cohen, Haim Kaplan, and Subhabrata Sen. Coordinated weighted sampling for estimating aggregates over multiple weight assignments. Proceedings of the VLDB Endowment, 2(1):646–657, 2009b. doi: 10.14778/1687627.1687701. URL https://doi.org/10.14778/1687627.1687701.
  40. Guy L. Steele, Doug Lea, and Christine H. Flood. Fast splittable pseudorandom number generators. In Proceedings of the 2014 ACM International Conference on Object Oriented Programming Systems Languages & Applications, pages 453–472. Association for Computing Machinery, 2014. doi: 10.1145/2660193.2660195. URL https://doi.org/10.1145/2660193.2660195.
  41. Piotr Indyk. Stable distributions, pseudorandom generators, embeddings, and data stream computation. Journal of the ACM, 53(3):307–323, 2006. doi: 10.1145/1147954.1147955. URL https://doi.org/10.1145/1147954.1147955.
  42. Ping Li, Trevor J. Hastie, and Kenneth W. Church. Nonlinear Estimators and Tail Bounds for Dimension Reduction in l1l_1 Using Cauchy Random Projections. Journal of Machine Learning Research, 8(83):2497–2532, 2007. URL https://www.jmlr.org/papers/v8/li07b.html.
  43. Mark Manasse, Frank McSherry, and Kunal Talwar. Consistent Weighted Sampling. Technical Report MSR-TR-2010-73, Microsoft Research, June 2010. URL https://www.microsoft.com/en-us/research/publication/consistent-weighted-sampling/.
  44. Sergey Ioffe. Improved Consistent Sampling, Weighted Minhash and L1 Sketching. In 2010 IEEE International Conference on Data Mining, pages 246–255. IEEE, 2010. doi: 10.1109/ICDM.2010.80. URL https://doi.org/10.1109/ICDM.2010.80.
  45. Ryan Moulton and Yunjiang Jiang. Maximally Consistent Sampling and the Jaccard Index of Probability Distributions. In 2018 IEEE International Conference on Data Mining (ICDM), pages 347–356. IEEE, 2018. doi: 10.1109/ICDM.2018.00050. URL https://doi.org/10.1109/ICDM.2018.00050.
  46. Hossein Jowhari, Mert Sağlam, and Gábor Tardos. Tight bounds for Lp samplers, finding duplicates in streams, and related problems. In Proceedings of the 30th ACM SIGMOD-SIGACT-SIGART Symposium on Principles of Database Systems, PODS '11, pages 49–58. Association for Computing Machinery, 2011. doi: 10.1145/1989284.1989289. URL https://doi.org/10.1145/1989284.1989289.
  47. Peter Clifford and Ioana Cosma. A simple sketching algorithm for entropy estimation over streaming data. In Proceedings of the Sixteenth International Conference on Artificial Intelligence and Statistics, Proceedings of Machine Learning Research, volume 31, pages 196–206. PMLR, 2013. URL https://proceedings.mlr.press/v31/clifford13a.html.
  48. Donald E. Knuth. The Art of Computer Programming, Volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, Massachusetts, 3rd edition, 1997. ISBN 0201896842. URL https://www-cs-faculty.stanford.edu/~knuth/taocp.html.
  49. Björn Ottosson. A perceptual color space for image processing. Blog post, December 2020. URL https://bottosson.github.io/posts/oklab/.