From Theorem to Production State
A theorem may say that a sketch uses $O(\varepsilon^{-2}\log(1/\delta))$ counters and returns an estimate within a stated error. Production must decide what each counter stores, how bytes are laid out, which hash and seed define the state, what concurrent updates mean, and whether a snapshot created today can merge with one stored last year.
Think of a sketch as a measuring instrument. The mathematics is its measurement principle; the implementation is the calibrated device, connector, label, and maintenance log. A correct estimator inside an ambiguous, overflowing, or incompatible state is not dependable.
For a tiny example, an unsigned $8$-bit counter represents $0$ through $255$. Starting at $250$, ten increments should produce $260$. Wrapping produces $4$; saturation produces $255$. Neither silently preserves the unbounded-integer model. The component must choose a width and overflow policy, expose saturation, or prove the boundary cannot be reached.
A stable interface commonly offers update, query, merge, reset, and snapshot. Its real contract also specifies item encoding, weights, replay behavior, consistency, serialization, version compatibility, concurrency, failures, and observability.
A production sketch is a versioned state machine whose bytes, arithmetic, metadata, and operations must preserve the theorem’s assumptions. Big-O bounds do not specify overflow, serialization, replay, concurrency, or safe merge behavior.
| Concept | Intuitive meaning | Exact example | Non-example or boundary | Required assumption | Question answered |
|---|---|---|---|---|---|
| API contract | Observable meaning of operations | Merge rejects a seed mismatch | Method names without semantics | Inputs, errors, consistency defined | What may callers rely on? |
| Counter width | Numeric range allotted to a cell | Unsigned 16-bit range $0$ to $65{,}535$ | Platform-dependent integer | Overflow policy matches model | Can arithmetic preserve meaning? |
| Packed registers | Small fields share machine words | Ten 6-bit registers use 60 payload bits | Struct with hidden padding | Bit order and alignment fixed | How is memory reduced predictably? |
| SIMD | One instruction handles several lanes | Vector maximum on aligned registers | Assuming source code auto-vectorizes | Lane semantics match scalar path | Can throughput improve safely? |
| Serialization | Canonical state bytes | Header, parameters, payload, checksum | Dumping in-memory structs | Endianness and lengths explicit | Can state survive processes and years? |
| Merge compatibility | Predicate for lawful combination | Same family, seed, precision, window | Equal byte length | The theorem’s domain is encoded | Which states may combine? |
| Observability | Evidence about health | saturation and reject metrics | Logging only estimates | Metrics avoid leakage/cardinality blowup | How is silent corruption detected? |
| Concurrency contract | Meaning of overlapping calls | Linearizable update and snapshot | “Thread-safe” without a model | Atomicity and ownership stated | What state does a query see? |
From Theorem to Production State
Four unsigned 8-bit counters hold $[250,2,0,255]$. Apply $[+10,+3,+1,+1]$.
- Mathematical integers give $[260,5,1,256]$.
- Modulo-$256$ wraparound gives $[4,5,1,0]$.
- Saturation gives $[255,5,1,255]$ and should increment two saturation metrics.
- Checked arithmetic may reject atomically before committing.
Reflection: which policy best preserves the estimator, and what explicit signal is required for every alternative?
Schemas, Seeds, Versions and Numeric Widths
Model serialized state as $(h,p,b)$: header, semantic parameters, and payload. The header identifies magic, family, schema version, length, canonical byte order, flags, and checksum. Parameters record every field that changes interpretation: dimension, precision, register width, hash algorithm and seed identifier, item encoding, weights, estimator generation, and window.
Compatibility is not “deserialization succeeded.” It is a relation $C(S_1,S_2)$ derived from the merge theorem. Exact equality may be required for seeds and dimensions. Some formats permit a proved one-way conversion such as precision downsampling; the information loss must be explicit.
For a $w$-bit unsigned counter, maximum value is $2^w-1$. If cell mass is bounded by $U$, exact storage requires
$$ w\ge\lceil\log_2(U+1)\rceil. $$
Intermediate sums and products can require more width than stored cells. Floating-point paths must address rounding, NaNs, infinities, and reduction order. Packed layouts define bit numbering, boundaries, padding, alignment, and atomic updates. SIMD kernels must match a scalar reference for boundary values and supported architectures.
Versioning separates wire readability, merge compatibility, and query comparability. A reader may parse an old format yet be forbidden to merge it.
flowchart TD
A[Mathematical state and merge law] --> B[Identify semantic parameters]
B --> C[Choose widths and overflow policy]
B --> D[Choose hash seed and encoding]
C --> E[Define canonical payload]
D --> E
E --> F[Add header version length checksum]
F --> G[Specify compatibility predicate]
G --> H[Define explicit migrations]
H --> I[Scalar reference]
I --> J[Packed and SIMD optimization]
J --> K[Differential cross-platform tests]
G --> X[Reject incompatible state]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
class A,B,C,D navy;
class E,F,G,H purple;
class I,J,K teal;
class X crimson;
| Definition or claim | Exact scope | Required assumptions | What it does not imply | Counterexample or consequence |
|---|---|---|---|---|
| Wire compatibility | Reader safely parses a version | Lengths, flags, endianness bounded | Parsed state may merge | Old seed semantics differ |
| Merge compatibility | Combination preserves objective | All theorem parameters match | Same size suffices | Same registers, different seed |
| Precision downsampling | High precision maps to lower precision | Construction proves mapping | Upsampling restores information | New zero registers fabricate confidence |
| Width sufficiency | $2^w-1$ covers stored value | Contribution bound is valid | Intermediates also fit | Product overflows before division |
| Saturating arithmetic | Value remains at maximum | Saturation surfaced and acceptable | Estimator stays unbiased | Hot cell sticks at maximum |
| Packed layout | Fields occupy documented positions | Canonical bit/byte order | Compiler struct is portable | Padding differs |
| SIMD equivalence | Optimized output matches scalar | Same overflow/rounding rules | Faster on every CPU | Narrow lane wraps |
The central invariant is semantic identity: operations must interpret bytes under the same family, parameters, encoding, arithmetic, and randomness contract. Parsing is weaker than merge compatibility, and conversion is safe only when information loss is explicit and proved.
Merge Safety, Replay and Operational Invariants
Associativity permits regrouping compatible states; commutativity permits reordering when order is irrelevant. Neither provides idempotence. Replaying an additive summary counts its population twice even though merge code is mathematically correct.
Exactly-once effects require stable batch identity, provenance, and an atomic deduplication boundary. Registerwise maximum may be idempotent, but audit counters or privacy budgets may not be. Snapshots also need a consistency model: barriers, copy-on-write, double buffering, or version validation. Copying packed words during mutation can create a state that never existed.
Concurrency must preserve both cell arithmetic and global invariants. Atomic increments may work for independent cells; packed fields may need compare-and-swap loops. Merge during update needs exclusive ownership or synchronization.
flowchart TD
A[Receive state and provenance] --> B[Validate framing checksum bounds]
B --> C[Validate semantic compatibility]
C --> D[Check batch identity and population]
D --> E{Already committed}
E -->|Yes| F[Return prior result]
E -->|No| G[Acquire consistent ownership]
G --> H[Merge with declared arithmetic]
H --> I[Persist state and commit atomically]
I --> J[Emit metrics and lineage]
B --> X[Quarantine malformed bytes]
C --> Y[Reject incompatible state]
G --> Z[Retry concurrent conflict]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
class A,B,C,D,E navy;
class G,H purple;
class F,I,J teal;
class X,Y,Z crimson;
Merge Safety, Replay and Operational Invariants
Base additive state is $S=[5,4]$; batch B42 is $B=[3,2]$.
- One merge gives $[8,6]$.
- Retrying without deduplication gives $[11,8]$.
- Store a durable destination/batch commit record atomically with state. A retry returns prior success.
- Registerwise maximum is idempotent: $\max([5,1],[3,2])=[5,2]$, and replay remains $[5,2]$.
- Two threads that read the same base then overwrite can lose an update; use ownership or compare-and-commit.
Assumption-breaking variation: different seeds share dimensions. Deduplication works, but merge semantics remain invalid.
| Invariant or tool | What it establishes | Assumptions | Limitation | Representative failure |
|---|---|---|---|---|
| Associativity test | Grouping preserves semantics | Compatible inputs, fixed arithmetic | Floating bits may vary | Tree shapes drift numerically |
| Idempotence test | Reapplication leaves payload unchanged | $a\oplus a=a$ | Side effects may differ | Audit count doubles |
| Provenance ledger | Detects duplicate batches | Stable IDs, atomic commit | Retention cost | ID reused for new population |
| Snapshot barrier | Captures a consistent cut | Writers honor epochs | Adds latency | Torn packed words |
| Scalar oracle | Reference for SIMD paths | Oracle correct | Slow and finite | Vector lane overflow |
| Property tests | Exercise algebra and boundaries | Strong generators | Not a proof | Maximum counter never generated |
| Fault injection | Tests crash/retry behavior | Realistic failure points | Environment gaps | Crash between write and ledger |
Rollouts, Monitoring and Sketch Incidents
Start with shadow exact answers for bounded populations. Compare accuracy, serialized round trips, replay, state size, and merge permutations. At scale, dual-write old and new versions, canary by region, treat seed/schema changes as epochs, reject unsafe cross-epoch merges, and preserve rollback readers.
Observe causes as well as estimates: state bytes, latency, saturation, overflow, NaNs, rejected merges, schema/seed distribution, snapshot age, replay rate, checksum failures, contention, audit divergence, and population lineage.
Incidents often masquerade as algorithmic error: retry doubles cardinality, mixed versions shift quantiles, SIMD diverges at boundaries, a snapshot misses concurrent writes, or a corrupt length allocates memory before validation.
Rollouts, Monitoring and Sketch Incidents: Practical Sketch Engineering
Exact daily distinct counts are $[1000,2000,5000]$; sketch estimates are $[1012,1970,5075]$.
- Relative errors are $1.2\%$, $-1.5\%$, and $1.5\%$.
- All meet a $2\%$ audit threshold.
- Round-trip each state and require identical query and metadata.
- Replay one batch and verify payload or provenance-level idempotence.
- Try another seed and confirm rejection.
Success criteria: calculate errors, document population/window, pass round-trip/replay tests, and expose rejection metrics.
Rollouts, Monitoring and Sketch Incidents: Practical Sketch Engineering
A telemetry platform processes $20$ million updates per second across $200$ regions. States live $18$ months, merge hourly, require p99 update latency below $5$ microseconds, total memory below $500$ GB, and audit error below $2\%$.
Design: bounded canonical wire format; immutable metadata; safe accumulation widths; scalar oracle and SIMD; batch ledger; epoch snapshots; compatibility matrix; dual-write canaries; stratified exact audits; and fail-closed merges.
Risks: mixed seeds, hot-cell saturation, retry replay, corrupt allocation, SIMD drift, torn snapshots, and high-cardinality metrics.
Evidence: golden cross-language vectors, property/fuzz tests, merge permutations, boundary arithmetic, crash injection, cross-CPU comparisons, benchmarks, shadow accuracy, memory forecasts, and recovery drills.
Decision: promote only after canaries meet accuracy, performance, and compatibility over a full merge/window cycle. Keep rollback readers and quarantine unknown required flags.
Write a Production Readiness Checklist
Connect each theorem assumption to a type rule, validation gate, test, metric, and incident response. Separate correctness from speed: establish scalar semantics and wire invariants first, then optimize cache layout, batching, allocation, and SIMD without changing behavior.
Practice: Write a Production Readiness Checklist
Design a mergeable service with update, query, merge, snapshot, and reset operations.
Tier 1 — Contract. Define item/weight domains, error semantics, consistency, replay, and ownership.
Tier 2 — Widths. For $U=10^9$, compute $\lceil\log_2(10^9+1)\rceil=30$ bits. Choose 32- or 64-bit storage and justify intermediates.
Tier 3 — Schema. Specify magic, family, version, flags, lengths, byte order, seed, precision, width, estimator generation, window, payload, checksum, and maximum allocation.
Tier 4 — Compatibility. Classify pairs as exact-compatible, explicitly convertible, query-comparable only, or incompatible.
Tier 5 — Failures. Trace wraparound, duplicate batch, torn snapshot, lost update, corrupt length, unsupported flag, and SIMD mismatch.
Tier 6 — Readiness. Produce SLOs, benchmarks, golden vectors, property/fuzz tests, rollout, dashboards, alerts, runbook, rollback, and owners.
Debugging prompts: doubled estimates suggest replay; one-CPU divergence suggests SIMD/endianness; hot-key error suggests saturation; memory spikes suggest unchecked lengths.
Stretch goal: define loss-accounted precision downsampling and prove when merge order remains equivalent.
Rubric (10 points): API 2; numeric/layout safety 2; schema/versioning 2; concurrency/replay 2; rollout/evidence 2.
Bridge: mergeable theory supplies algebra; robust/private streaming supplies adversary and leakage models. Engineering preserves both across bytes, threads, machines, upgrades, and failures.
Readiness checklist: freeze semantics before optimization; bound every width and allocation; canonicalize bytes; version meaning-changing parameters; reject unsafe merges; define replay and concurrency; compare scalar and SIMD; audit accuracy and lineage; canary full merge cycles; and rehearse rollback. Compact state is not ready until its assumptions are enforceable and observable.
Next in the Series
In Evaluation, Testing & Algorithm Selection, we'll explore Select algorithms with evidence rather than headline complexity..