Back to Streaming Sketching

Linear Sketches, l0-Sampling & Sparse Recovery

September 26, 2026 Wasil Zafar 23 min read

Treat sketches as linear measurements of dynamic vectors.

Table of Contents

  1. Measurements Instead of the Full Vector
  2. Linearity, Null Spaces and Sparse Signals
  3. Recovery Conditions and Failure Certificates
  4. Inventory Changes and Network Anomalies
  5. Reason About What Can Be Recovered

Measurements Instead of the Full Vector

Imagine trying to identify which few shelves changed in a warehouse without recounting every shelf. One option is to record several weighted totals: total change on all shelves, an alternating-sign total, and totals for selected groups. Each update changes those measurements immediately. If only a few shelves have nonzero changes, the combined measurements may reveal them even though the full inventory vector was never stored.

A linear sketch formalizes that idea. A high-dimensional vector $x\in\mathbb R^n$ is mapped to a shorter measurement vector $y=Ax\in\mathbb R^m$, usually with $m\ll n$. A stream update $(i,\Delta)$ means $x_i\leftarrow x_i+\Delta$ and changes the sketch by $y\leftarrow y+\Delta A e_i$, where $e_i$ is the $i$th standard basis vector. Insertions and deletions use the same update rule.

For a tiny example, let

$$ A=\begin{bmatrix}1&1&1&1\\1&-1&1&-1\end{bmatrix},\qquad x=(0,3,0,0)^\mathsf T. $$

Then $Ax=(3,-3)^\mathsf T$. These two measurements happen to identify this one-sparse signal: a positive value in coordinate two produces that pattern. But they cannot identify every vector. Because $A$ has fewer rows than columns, distinct vectors share measurements; recovery requires a restricted signal class such as sparsity and a matrix whose null space does not confuse members of that class.

This viewpoint connects several tasks. Mergeability follows because $A(x+z)=Ax+Az$. An $\ell_0$-sampler tries to return a uniformly random index from the support $\{i:x_i\ne0\}$. Sparse recovery tries to reconstruct all or the most important nonzero coordinates from few measurements. The questions are therefore not “Does compression lose information?”—it must—but “Which information does it preserve, under which model, with what probability, and against which update sequence?”

From warehouse changes to linear measurements and sparse recovery A sparse shelf-change vector passes through a measurement matrix to a small sketch, then a decoder identifies changed shelves under a recovery condition. Shelf changes x few nonzero coordinates Matrix A hashed weighted totals Sketch y=Ax m measurements Decode support + values Success requires sparsity and a matrix that does not hide sparse differences.
ConceptIntuitive meaningExact exampleNon-example or boundaryMain assumptionQuestion answered
Linear sketchShort vector of linear measurements$y=Ax$A nonlinear compressed file with no additive lawArithmetic domain and matrix are fixedWhat additive information is retained?
Turnstile updateCoordinate may increase or decrease$(i,-3)$ subtracts $3A e_i$ from $y$Insertion-only counts that can never fallUpdates define a frequency vector, often with bounded precisionCan deletions be processed without the full vector?
MergeabilitySketches of vectors add$Ax+Az=A(x+z)$Combining states built with different matrices or seedsIdentical linear map and compatible domainsCan distributed partial streams be combined?
Null spaceDirections invisible to measurements$Ah=0$ means $x$ and $x+h$ look identicalSmall measurement noise, which is visible but perturbativeExact arithmetic for the stated equalityWhat ambiguity can the sketch never resolve?
$\ell_0$ supportIndices with nonzero coordinates$(0,4,0,-2)$ has support $\{2,4\}$Number of updates; cancellations may remove supportFinal vector defines membershipWhich coordinates remain nonzero?
Sparse recoveryReconstruct a vector with few important coordinatesRecover a $k$-sparse $x$ from $Ax$Recover every dense $x$ from $m\ll n$ measurementsSparsity or compressibility plus matrix conditionsWhat signal can be decoded?
Warm-up

Measurements Instead of the Full Vector

Let

$$ A=\begin{bmatrix}1&1&1&1\\1&-1&1&-1\end{bmatrix} $$

and begin with $x=(0,0,0,0)^\mathsf T$, $y=(0,0)^\mathsf T$.

  1. Apply update $(2,+3)$. Column two is $(1,-1)^\mathsf T$, so $y=(3,-3)^\mathsf T$.
  2. Apply $(4,+2)$. Column four is also $(1,-1)^\mathsf T$, so $y=(5,-5)^\mathsf T$.
  3. Apply $(2,-1)$. The final vector is $x=(0,2,0,2)^\mathsf T$ and $y=(4,-4)^\mathsf T$.
  4. Compare $z=(0,4,0,0)^\mathsf T$. It has the same sketch $(4,-4)^\mathsf T$. Thus the measurements cannot distinguish these two sparse vectors.

Reflection: linearity made every update and deletion easy, yet recovery failed. Which property of columns two and four caused the ambiguity, and what matrix-design requirement would forbid it for one-sparse signals?

Linearity, Null Spaces and Sparse Signals

Fix a field or numerical domain and an $m\times n$ matrix $A$. The sketch of $x$ is $S(x)=Ax$. Linearity means $S(\alpha x+\beta z)=\alpha S(x)+\beta S(z)$. In a turnstile stream, update $(i,\Delta)$ adds $\Delta e_i$ to $x$ and therefore adds $\Delta A e_i$ to the sketch. Two shards using the same $A$ can merge by addition; subtracting sketches yields a sketch of the difference.

The null space $\ker(A)=\{h:Ah=0\}$ describes exact indistinguishability. If $Ax=Az$, then $A(x-z)=0$, so $x-z\in\ker(A)$. Conversely, any nonzero $h\in\ker(A)$ makes $x$ and $x+h$ collide. Full recovery for all of $\mathbb R^n$ is impossible when $m\lt n$ because a nontrivial null space must exist.

Sparsity restricts the candidates. Write $\lVert x\rVert_0$ for the number of nonzero coordinates. Exact recovery of every $k$-sparse vector is information-theoretically possible under a fixed matrix precisely when no nonzero null-space vector has at most $2k$ nonzeros. The reason is that the difference of two $k$-sparse vectors is at most $2k$-sparse. If such a difference lies in the null space, the pair collides; if no such vector exists, measurements are injective on the $k$-sparse set. This establishes uniqueness, not an efficient or noise-stable decoder.

Compressed sensing strengthens uniqueness with geometric conditions. The null-space property of order $k$ supports exact $\ell_1$ recovery: for every nonzero $h\in\ker(A)$ and every index set $T$ of size at most $k$, $\lVert h_T\rVert_1\lt\lVert h_{T^c}\rVert_1$. The restricted isometry property approximately preserves the $\ell_2$ norm of sparse vectors and can yield stable recovery under noise and approximate sparsity. Exact constants depend on the theorem and decoder; “RIP” alone is not a complete guarantee.

An $\ell_0$-sampler returns an index $i$ with $x_i\ne0$, ideally uniformly over the final support, and usually reports or estimates $x_i$. It must respect cancellations: an index inserted and later fully deleted is not eligible. Practical constructions use randomized subsampling levels and hashed one-sparse recovery tests. Their guarantee includes a failure probability and assumptions about update adaptivity, arithmetic range, and random seeds.

Linear Sketches, l0-Sampling & Sparse Recovery: Linearity, Null Spaces and Sparse Signals
flowchart TD
    A[Turnstile updates define vector x] --> B[Fixed linear map A]
    B --> C[Sketch y equals Ax]
    C --> D[Update by adding Delta times column i]
    C --> E[Merge compatible shards by addition]
    C --> F[Ask whether two candidates collide]
    F --> G[Difference lies in null space]
    G --> H{Signal restriction}
    H -->|k-sparse| I[No nonzero 2k-sparse null vector]
    H -->|compressible and noisy| J[Null-space or restricted-isometry conditions]
    H -->|support sample| K[Hashed subsampling plus one-sparse tests]
    I --> L[Unique exact sparse solution]
    J --> M[Stable approximate recovery]
    K --> N[l0 sample with stated failure probability]
    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 navy;
    class D,E teal;
    class F,G,H purple;
    class I,J,K teal;
    class L,M,N crimson;
Linear measurement model with an invisible null-space direction Two candidate vectors differ by h. If h lies in the null space, both map to the same measurement y; restricting candidates to sparse vectors can remove the ambiguity. Candidate space x z h=z−x Linear map A AxAz = Ax + Ah Ah = 0? Measurement space y if Ah=0, x and z collide Sparse uniqueness: no invisible nonzero h with at most 2k nonzeros.
Definition or claimExact scopeRequired assumptionsWhat it does not implyCounterexample or consequence
Linearity$S(\alpha x+\beta z)=\alpha S(x)+\beta S(z)$Same matrix, field, dimensions, and arithmetic conventionSame decoded answer after arbitrary nonlinear postprocessingDifferent random seeds make shard sketches incompatible
Sparse uniquenessEvery $k$-sparse vector is uniquely determined iff the null space has no nonzero vector with support at most $2k$Exact measurements and candidate class of all $k$-sparse vectorsEfficient decoding or robustness to noiseNearly colliding sparse vectors can make recovery unstable
Spark condition$\operatorname{spark}(A)\gt2k$ gives uniquenessSpark is the smallest dependent column countEasy verification for large matricesComputing spark is generally difficult
$\ell_1$ null-space propertyStrict mass inequality on every size-$k$ set characterizes uniform exact basis-pursuit recoveryExact arithmetic and the stated orderRecovery by every decoder or under arbitrary noiseA null vector concentrated on $T$ defeats $\ell_1$ separation
Restricted isometrySparse norms are approximately preservedDeclared sparsity order and constantA guarantee without specifying order, constant, decoder, and noise modelA matrix can be injective yet severely ill-conditioned
$\ell_0$ samplingOutput distribution is near-uniform over nonzero final coordinates, conditional on successTurnstile model, randomness, bounded failure, support nonemptySampling updates uniformlyMany updates to one canceled coordinate should not increase eligibility

The central recoverability test is injectivity on differences: two allowed signals collide exactly when their difference lies in $\ker(A)$. For all $k$-sparse signals, exact uniqueness therefore requires $\ker(A)$ to contain no nonzero $2k$-sparse vector; stronger geometric conditions are needed for efficient, stable recovery.

Recovery Conditions and Failure Certificates

Suppose a decoder receives $y=Ax$ and knows that $x$ is $k$-sparse. If two $k$-sparse candidates $x$ and $z$ satisfy the measurements, then $h=x-z$ is at most $2k$-sparse and satisfies $Ah=0$. Thus the absence of nonzero $2k$-sparse null vectors proves uniqueness. Conversely, if such an $h$ exists, split its support into two sets of size at most $k$, write $h=u-v$, and obtain $Au=Av$. That collision is a failure certificate for uniform exact recovery.

Uniqueness can still be numerically fragile. If a unit-norm sparse vector $h$ has $\lVert Ah\rVert_2$ extremely small, measurement noise can make $x$ and $x+h$ nearly indistinguishable. Stable recovery needs a lower bound on measurements of sparse differences, not merely nonzero measurements. Restricted singular values, RIP, robust null-space properties, or expander-based conditions provide different ways to express this separation.

Hashed sparse recovery uses many smaller measurement groups. A coordinate isolated in a bucket can be recognized using checks such as a count, an index-weighted sum, and a verification fingerprint. Peeling decodes isolated coordinates, subtracts their contributions from neighboring buckets, and repeats. The proof must show enough coordinates become isolated, verification rejects mixed buckets with high probability, and accumulated failures remain within the global error budget.

An $\ell_0$-sampler similarly searches for a level at which random subsampling leaves about one surviving support element in some bucket. A one-sparse test identifies it; repetitions reduce failure. If randomness is public and an adaptive adversary sees outcomes or seeds, it may craft updates aligned with collisions. Guarantees proved for an oblivious stream do not automatically survive adaptive interaction.

A sparse null vector certifies impossible recovery A two-k-sparse null vector is split into two k-sparse vectors u and v. Both produce the same measurement, proving ambiguity. Find h in ker(A) support at most 2k Split h = u − v u: at most kv: at most k Same measurements Au = Av decoder cannot know which uniform recovery is impossible Failure certificate: a concrete nonzero sparse h satisfying Ah=0.
Linear Sketches, l0-Sampling & Sparse Recovery: Recovery Conditions and Failure Certificates
flowchart TD
    A[Assume two allowed candidates x and z] --> B[Both satisfy Ax equals Az]
    B --> C[Set h equal to x minus z]
    C --> D[Then Ah equals zero]
    D --> E{Is h nonzero and at most 2k-sparse?}
    E -->|Yes| F[Collision certificate: exact uniform recovery impossible]
    E -->|No such h exists| G[Measurements are injective on k-sparse signals]
    G --> H{Need stability under noise?}
    H -->|Yes| I[Require quantitative lower bound on sparse differences]
    H -->|No| J[Uniqueness established]
    I --> K[Choose decoder with matching robust theorem]
    D -. very small Ah rather than zero .-> L[Near-collision: unstable recovery risk]
    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 navy;
    class D,E purple;
    class G,H,I,J,K teal;
    class F,L crimson;
Worked Derivation

Recovery Conditions and Failure Certificates

Let

$$ A=\begin{bmatrix}1&0&1\\0&1&1\end{bmatrix}. $$

  1. Solve $Ah=0$: the equations are $h_1+h_3=0$ and $h_2+h_3=0$. Taking $h_3=1$ gives $h=(-1,-1,1)^\mathsf T$.
  2. This null vector has three nonzero coordinates. Therefore it does not by itself refute uniqueness for one-sparse vectors, because a difference of two one-sparse vectors has support at most two.
  3. Check the columns: $(1,0)^\mathsf T$, $(0,1)^\mathsf T$, and $(1,1)^\mathsf T$ are all nonzero and no pair is proportional. Hence distinct one-sparse vectors, including their amplitudes, do not collide.
  4. For $k=2$, the same $h$ is a valid at-most-four-sparse certificate. Split it as $u=(0,0,1)^\mathsf T$ and $v=(1,1,0)^\mathsf T$. Both are at most two-sparse and $Au=Av=(1,1)^\mathsf T$.

Assumption-breaking variation: add measurement noise $\eta$. Even if no exact sparse null vector exists, a sparse $h$ with tiny $\lVert Ah\rVert_2$ can be hidden by noise of comparable size. Explain why a uniqueness proof must be replaced by a robust separation bound.

Analytical viewpointWhat it establishesAssumptionsTightness or limitationRepresentative failure case
Null-space collisionExact information-theoretic impossibilityExact $Ah=0$ and both colliding signals allowedSays nothing about near-collisions or algorithmsA nonzero $2k$-sparse null vector
SparkUniform uniqueness for $k$-sparse signals when spark exceeds $2k$Exact arithmeticHard to compute for large matricesTwo proportional columns make one-sparse identity ambiguous
Null-space propertyExact recovery by $\ell_1$ minimizationProperty holds uniformly at order $k$Verification is difficult; noise needs robust versionNull mass concentrated on a small index set
RIP or restricted singular valuesQuantitative sparse separation and stabilityCorrect order and sufficiently strong constantSufficient constants vary and may not be necessaryPoorly conditioned sparse column subset amplifies noise
Hash isolationMany heavy coordinates appear alone in at least one bucketSuitable independent hashing and enough buckets/repetitionsCollisions remain probabilisticAdversarial keys concentrate under exposed deterministic hashes
One-sparse verificationRejects buckets containing multiple active coordinatesFingerprints, bounded arithmetic, and randomness as specifiedHas a collision/failure probabilityModular checksum collision accepts a mixed bucket
Peeling invariantRepeatedly removes verified isolated coordinatesCorrect subtraction and a favorable measurement graphError propagation can poison later stepsOne false decode creates several false singletons

Inventory Changes and Network Anomalies

For inventory reconciliation, let coordinate $i$ be the net change of product $i$ between two snapshots. Sales and receipts create positive or negative turnstile updates. If only a small number of products disagree, sketch subtraction gives $A(x-z)$ and sparse recovery can identify them without transferring full inventories. This model fails when differences are dense or identifiers are inconsistently mapped.

For network monitoring, coordinates can represent flows and values can represent byte-count changes from a baseline. Heavy or sparse anomalies may be recoverable from hashed linear measurements collected across routers. Linearity supports aggregation only when matrices, seeds, epochs, units, and sign conventions match. Packet loss and counter wraparound are measurement-model errors, not decoder noise unless modeled accordingly.

For distributed set or graph differences, coordinates represent possible edges or items and signed updates encode insertions and deletions. $\ell_0$ sampling can return a surviving edge for graph-stream algorithms or a random differing key for diagnostics. The sampler selects from the final nonzero support, not uniformly from update events.

Misleading cases matter. A “sparse anomaly” may be dense after a feature transformation. Two organizations may hash different canonical identifiers to the same coordinate. Floating-point accumulation may violate exact cancellation. An adaptive attacker who learns the sketch can search for a harmful null-space direction. Secret or rotated randomness, overflow-safe arithmetic, validation measurements, and explicit adversary models are part of the guarantee boundary.

Distributed linear-sketch recovery pipeline with trust boundaries Signed updates at multiple sources use the same measurement map, merge into one sketch, decode sparse candidates, and verify them against source records. Warnings mark incompatible seeds, dense residuals, and adversarial inputs. Signed updatessales / flows / edgesacross shards Local Axsame matrix + epochbounded arithmetic Mergesum measurementsor subtract snapshots Decodesupport + valuesor l0 sample Verifysourcerecords Compatibility riskseed, ID, unit mismatch Model riskresidual is not sparse Adversarial risknull-space probing Linearity preserves algebra; validation protects the meaning of the recovered coordinates.
Case Study

Inventory Changes and Network Anomalies: Linear Sketches, l0-Sampling & Sparse Recovery

A shop tracks net changes for four products. Use

$$ A=\begin{bmatrix}1&1&1&1\\1&2&3&4\end{bmatrix}. $$

The day’s updates are $(3,+5)$, $(1,+2)$, $(3,-5)$, and $(1,-1)$.

  1. The final vector is $x=(1,0,0,0)^\mathsf T$ because product three cancels completely.
  2. Apply updates directly to the sketch: $5(1,3)+2(1,1)-5(1,3)-(1,1)=(1,1)^\mathsf T$.
  3. Under the promise that the final vector is one-sparse, the measurements $s=x_i$ and $t=i x_i$ reveal $i=t/s=1$ and value $s=1$.
  4. An $\ell_0$-sampler must return product one with probability one; product three is not in the final support despite receiving two updates.
  5. If the final vector were $(1,1,0,0)^\mathsf T$, then $(s,t)=(2,3)$ and $t/s=1.5$ is not a valid one-sparse index, providing a failure certificate for this decoder.

Success criteria: reproduce the vector and sketch, explain cancellation, state the one-sparsity assumption, and reject the mixed case rather than rounding $1.5$ to an index.

Production

Inventory Changes and Network Anomalies: Linear Sketches, l0-Sampling & Sparse Recovery

A network operator has $10^8$ possible flow IDs across 500 edge nodes. Each five-minute epoch receives $3\times10^9$ signed byte-counter updates. The goal is to identify at most $k=2{,}000$ anomalous residual flows relative to a baseline, with support recall at least $99\%$, value error within a declared tail norm, and end-to-end results within 20 seconds.

Proposed design: canonicalize flow IDs; version a common measurement matrix and epoch; compute integer linear sketches locally; merge by addition; recover candidates with a hashed multi-level sparse-recovery scheme; and verify candidate counters against sampled raw or authoritative aggregates. Keep an independent residual-norm sketch to test whether the assumed sparsity/tail bound is plausible.

Evidence to collect: synthetic exact $k$-sparse signals, compressible heavy-tail signals, dense residuals, counter wraparound, packet loss, shard retries, seed mismatch, arithmetic overflow, adversarial keys, and adaptive-query simulations. Report recall by magnitude, false discoveries, value error, decoder failure rate, residual check, sketch bytes, merge throughput, and p95/p99 decode time.

Risks and controls: incompatible seeds silently corrupt merges; false one-sparse tests poison peeling; dense change violates the model; public fixed hashes invite collision attacks; and modular arithmetic can alias large values. Use metadata validation, checked arithmetic, independent fingerprints, seed rotation or secrecy where appropriate, and a “model rejected” outcome rather than forcing a sparse answer.

Decision: adopt sparse recovery only if exact replay demonstrates the target guarantees across the declared tail and adversary models and the residual certificate catches dense cases. Otherwise use the sketch for anomaly scoring or candidate generation, with authoritative verification before mitigation.

Reason About What Can Be Recovered

The disciplined workflow begins with a vector definition and ends with a failure policy. State the update domain, final signal class, randomness model, noise and precision model, and desired output. Then ask what the null space hides, which quantitative property supports the decoder, and how the system detects violated assumptions.

Practice

Practice: Reason About What Can Be Recovered

Work with

$$ A=\begin{bmatrix}1&0&1\\0&1&1\end{bmatrix} $$

and turnstile updates over three coordinates.

Tier 1 — Definitions. Define linear sketch, turnstile update, support, $k$-sparsity, null space, $\ell_0$-sampler, and stable sparse recovery. Checkpoint: distinguish the number of nonzero final coordinates from the number of updates.

Tier 2 — Update algebra. Starting from zero, process $(1,+4),(3,+2),(1,-1),(3,-2)$. Compute final $x=(3,0,0)^\mathsf T$ and sketch $y=(3,0)^\mathsf T$ both from $Ax$ and by column updates. Then show how two shard sketches add.

Tier 3 — Collision proof. Derive $h=(-1,-1,1)^\mathsf T\in\ker(A)$. Split it into two at-most-two-sparse candidates with the same measurements. Explain why this disproves uniform two-sparse recovery but not uniform one-sparse recovery.

Tier 4 — Stability counterexample. Construct or search for a matrix whose relevant columns are distinct but nearly proportional. Add small measurement noise and show that one-sparse amplitude/location decisions become ill-conditioned. Hint: uniqueness requires nonzero separation; robustness requires separation bounded away from zero.

Tier 5 — Sampling semantics. For updates $(2,+5),(2,-5),(1,+1),(3,-4)$, the final support is $\{1,3\}$. State the ideal $\ell_0$ sampling probabilities and explain why coordinate two gets probability zero despite receiving most updates.

Tier 6 — Professional artifact. Write a recovery contract specifying $n$, expected $k$, tail/noise norm, update range, arithmetic domain, matrix/seed version, oblivious or adaptive adversary, success probability, decoder output, verification test, residual certificate, merge metadata, and fallback when the signal is dense.

Debugging prompts: if merged results are nonsense, compare matrix and epoch IDs; if canceled keys reappear, inspect overflow and update signs; if peeling explodes, audit singleton verification; if recovery always returns exactly $k$ entries, confirm it can report model failure; if empirical recall collapses only after repeated queries, examine adaptivity.

Stretch goal: compare Gaussian compressed-sensing measurements, sparse hashing/peeling, and expander-style measurements for update cost, decoding time, numerical stability, randomness, and adversarial exposure. Do not claim one is universally best.

Rubric (10 points): definitions and domains 2; update/merge derivation 2; null-space certificate 2; stability and sampling counterexamples 2; reviewable recovery contract 2. Full credit requires separating uniqueness, efficient decoding, and robustness.

Decision checklist: define the final vector and signal class; fix compatible measurement metadata; inspect null-space ambiguity; require quantitative stability for noise; budget randomized failure; verify decoded coordinates and residuals; and provide a dense-signal fallback. Linearity guarantees update and merge algebra—not sparse truth, uniform sampling, or recovery. This chapter extends frequency-moment sketches toward compressed sensing and prepares the ground for sparse embeddings, randomized linear algebra, and graph-stream recovery.

Next in the Series

In Dimensionality Reduction, we'll explore Preserve geometry while reducing dimension..