Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

countminsketch.gno

// Package countminsketch estimates element frequencies in sublinear space, as
// a pure, reusable package.
//
// An exact frequency map costs one entry per distinct element, which on chain
// means unbounded storage driven by whatever users feed it. A Count-Min Sketch
// trades exactness for a FIXED footprint: d rows of w counters, sized once and
// never grown, regardless of how many distinct elements arrive.
//
// The error is one-sided and that is the whole contract: Estimate NEVER
// UNDERCOUNTS. Collisions can only add other elements' counts to a row, so the
// true frequency is always <= the estimate. Taking the minimum across d
// independent rows makes an overestimate require a collision in every row at
// once. Callers must treat the result as an upper bound — "at most this often",
// never "exactly this often".
//
// Sizing: width controls the error, depth controls the odds of hitting it.
// Roughly, the overestimate stays within total/width with probability
// 1 - (1/2)^depth.
//
// Hashing is FNV-1a with a per-row seed, computed in pure gno — deterministic
// across every node, which a map-address-derived hash would not be.
//
// A live demo of this package is at
// [r/moul/x/daily/countminsketchdemo](/r/nym-moultest123/x/daily/countminsketchdemo/v0).
package countminsketch

import "errors"

const (
	// MinWidth/MaxWidth bound each row.
	MinWidth = 4
	MaxWidth = 8192
	// MinDepth/MaxDepth bound the number of rows.
	MinDepth = 1
	MaxDepth = 16
)

var (
	ErrBadWidth = errors.New("countminsketch: width out of range")
	ErrBadDepth = errors.New("countminsketch: depth out of range")
	ErrBadCount = errors.New("countminsketch: count must be positive")
)

// Sketch is a Count-Min Sketch over string elements.
type Sketch struct {
	width  int
	depth  int
	rows   [][]int64 // depth rows of width counters
	total  int64     // sum of every increment applied
	adds   int64     // number of Add/AddN calls applied
}

// New returns a sketch with the given dimensions.
func New(width, depth int) (*Sketch, error) {
	if width < MinWidth || width > MaxWidth {
		return nil, ErrBadWidth
	}
	if depth < MinDepth || depth > MaxDepth {
		return nil, ErrBadDepth
	}
	rows := make([][]int64, depth)
	for i := range rows {
		rows[i] = make([]int64, width)
	}
	return &Sketch{width: width, depth: depth, rows: rows}, nil
}

// NewDefault returns a sketch sized for general use: 256 x 4.
func NewDefault() *Sketch {
	s, _ := New(256, 4)
	return s
}

// Width returns the number of counters per row.
func (s *Sketch) Width() int { return s.width }

// Depth returns the number of rows.
func (s *Sketch) Depth() int { return s.depth }

// Counters returns the total number of counters — the fixed storage cost.
func (s *Sketch) Counters() int { return s.width * s.depth }

// Total returns the sum of every increment applied.
func (s *Sketch) Total() int64 { return s.total }

// Distinct is deliberately absent: a Count-Min Sketch cannot answer it. Use a
// HyperLogLog for cardinality.

// Add records one occurrence of e.
func (s *Sketch) Add(e string) { s.AddN(e, 1) }

// AddN records n occurrences of e. A non-positive n is ignored.
func (s *Sketch) AddN(e string, n int64) error {
	if n <= 0 {
		return ErrBadCount
	}
	for r := 0; r < s.depth; r++ {
		s.rows[r][s.index(e, r)] += n
	}
	s.total += n
	s.adds++
	return nil
}

// Estimate returns an UPPER BOUND on how often e was added. It never
// undercounts; it may overcount when every row collided.
func (s *Sketch) Estimate(e string) int64 {
	var min int64 = -1
	for r := 0; r < s.depth; r++ {
		v := s.rows[r][s.index(e, r)]
		if min < 0 || v < min {
			min = v
		}
	}
	if min < 0 {
		return 0
	}
	return min
}

// MightHave reports whether e may have been added. A false result is
// definitive: it was never added.
func (s *Sketch) MightHave(e string) bool { return s.Estimate(e) > 0 }

// Merge adds another sketch into this one. Both must have identical dimensions;
// merging is what makes sketches useful across shards or time windows.
func (s *Sketch) Merge(other *Sketch) error {
	if s.width != other.width {
		return ErrBadWidth
	}
	if s.depth != other.depth {
		return ErrBadDepth
	}
	for r := 0; r < s.depth; r++ {
		for c := 0; c < s.width; c++ {
			s.rows[r][c] += other.rows[r][c]
		}
	}
	s.total += other.total
	s.adds += other.adds
	return nil
}

// Reset zeroes every counter, keeping the dimensions.
func (s *Sketch) Reset() {
	for r := range s.rows {
		for c := range s.rows[r] {
			s.rows[r][c] = 0
		}
	}
	s.total = 0
	s.adds = 0
}

// Clone returns an independent copy.
func (s *Sketch) Clone() *Sketch {
	cp, _ := New(s.width, s.depth)
	for r := range s.rows {
		copy(cp.rows[r], s.rows[r])
	}
	cp.total = s.total
	cp.adds = s.adds
	return cp
}

// Row returns a copy of row r, for rendering and inspection.
func (s *Sketch) Row(r int) []int64 {
	if r < 0 || r >= s.depth {
		return nil
	}
	out := make([]int64, s.width)
	copy(out, s.rows[r])
	return out
}

// Index returns the column e maps to in row r — exported so a demo can show
// where collisions happen.
func (s *Sketch) Index(e string, r int) int {
	if r < 0 || r >= s.depth {
		return -1
	}
	return s.index(e, r)
}

// index hashes e for row r with FNV-1a, seeded per row.
func (s *Sketch) index(e string, row int) int {
	const (
		offset64 = uint64(14695981039346656037)
		prime64  = uint64(1099511628211)
	)
	h := offset64
	// Seed the row so each row hashes independently.
	h ^= uint64(row + 1)
	h *= prime64
	for i := 0; i < len(e); i++ {
		h ^= uint64(e[i])
		h *= prime64
	}
	return int(h % uint64(s.width))
}

countminsketch_test.gno

package countminsketch

import (
	"strconv"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func TestNewValidation(t *testing.T) {
	_, err := New(MinWidth-1, 4)
	uassert.ErrorIs(t, err, ErrBadWidth)
	_, err = New(MaxWidth+1, 4)
	uassert.ErrorIs(t, err, ErrBadWidth)
	_, err = New(256, MinDepth-1)
	uassert.ErrorIs(t, err, ErrBadDepth)
	_, err = New(256, MaxDepth+1)
	uassert.ErrorIs(t, err, ErrBadDepth)

	_, err = New(MinWidth, MinDepth)
	uassert.NoError(t, err, "the minimum dimensions are valid")
	_, err = New(MaxWidth, MaxDepth)
	uassert.NoError(t, err, "the maximum dimensions are valid")
}

func TestDimensions(t *testing.T) {
	s, _ := New(64, 3)
	uassert.Equal(t, 64, s.Width())
	uassert.Equal(t, 3, s.Depth())
	uassert.Equal(t, 192, s.Counters(), "storage is width*depth, fixed")

	d := NewDefault()
	uassert.Equal(t, 256, d.Width())
	uassert.Equal(t, 4, d.Depth())
}

func TestEmptyEstimatesZero(t *testing.T) {
	s := NewDefault()
	uassert.Equal(t, int64(0), s.Estimate("anything"))
	uassert.False(t, s.MightHave("anything"))
	uassert.Equal(t, int64(0), s.Total())
}

func TestAddAndEstimate(t *testing.T) {
	s := NewDefault()
	for i := 0; i < 5; i++ {
		s.Add("apple")
	}
	s.Add("pear")

	uassert.Equal(t, int64(5), s.Estimate("apple"))
	uassert.Equal(t, int64(1), s.Estimate("pear"))
	uassert.Equal(t, int64(6), s.Total())
	uassert.True(t, s.MightHave("apple"))
}

func TestAddNRejectsNonPositive(t *testing.T) {
	s := NewDefault()
	uassert.ErrorIs(t, s.AddN("x", 0), ErrBadCount)
	uassert.ErrorIs(t, s.AddN("x", -3), ErrBadCount)
	uassert.Equal(t, int64(0), s.Total(), "a rejected add changes nothing")
}

func TestAddNAccumulates(t *testing.T) {
	s := NewDefault()
	uassert.NoError(t, s.AddN("x", 100))
	uassert.NoError(t, s.AddN("x", 50))
	uassert.Equal(t, int64(150), s.Estimate("x"))
	uassert.Equal(t, int64(150), s.Total())
}

// TestNeverUndercounts is THE contract. A tiny sketch guarantees collisions;
// the estimate must still never fall below the truth.
func TestNeverUndercounts(t *testing.T) {
	s, _ := New(MinWidth, 2) // deliberately tiny: 4 columns, collisions certain

	truth := map[string]int64{}
	for i := 0; i < 300; i++ {
		e := "e" + strconv.Itoa(i%40)
		s.Add(e)
		truth[e]++
	}

	for e, want := range truth {
		got := s.Estimate(e)
		uassert.True(t, got >= want,
			"estimate must never undercount "+e+": got "+strconv.FormatInt(got, 10)+
				" want >= "+strconv.FormatInt(want, 10))
	}
}

// TestExactWhenNoCollisions checks a generously sized sketch is exact for a
// handful of elements — the common case.
func TestExactWhenNoCollisions(t *testing.T) {
	s, _ := New(MaxWidth, 4)
	s.AddN("alpha", 7)
	s.AddN("bravo", 3)
	s.AddN("charlie", 11)

	uassert.Equal(t, int64(7), s.Estimate("alpha"))
	uassert.Equal(t, int64(3), s.Estimate("bravo"))
	uassert.Equal(t, int64(11), s.Estimate("charlie"))
}

// TestAbsentIsDefinitiveWhenZero pins the useful direction of the one-sided
// error: zero means definitely never added.
func TestAbsentIsDefinitiveWhenZero(t *testing.T) {
	s, _ := New(MaxWidth, 4)
	s.Add("present")
	uassert.False(t, s.MightHave("definitely-absent"), "a zero estimate is definitive")
}

// TestEstimateBoundedByTotal pins the other side: an estimate can never exceed
// everything that was ever added.
func TestEstimateBoundedByTotal(t *testing.T) {
	s, _ := New(MinWidth, 1)
	for i := 0; i < 100; i++ {
		s.Add("e" + strconv.Itoa(i))
	}
	for i := 0; i < 100; i++ {
		uassert.True(t, s.Estimate("e"+strconv.Itoa(i)) <= s.Total(),
			"no estimate may exceed the total")
	}
}

// TestDeterministicAcrossInstances is what makes this safe on chain: the same
// input yields the same counters everywhere, with no map-order dependence.
func TestDeterministicAcrossInstances(t *testing.T) {
	build := func() *Sketch {
		s, _ := New(32, 3)
		for i := 0; i < 200; i++ {
			s.Add("elem" + strconv.Itoa(i%25))
		}
		return s
	}
	a, b := build(), build()

	for r := 0; r < a.Depth(); r++ {
		ra, rb := a.Row(r), b.Row(r)
		for c := range ra {
			uassert.Equal(t, ra[c], rb[c], "counters must match across instances")
		}
	}
	uassert.Equal(t, a.Estimate("elem7"), b.Estimate("elem7"))
}

func TestIndexIsStableAndInRange(t *testing.T) {
	s, _ := New(64, 3)
	for r := 0; r < 3; r++ {
		i := s.Index("hello", r)
		uassert.True(t, i >= 0 && i < 64, "index must be within the row")
		uassert.Equal(t, i, s.Index("hello", r), "index must be stable")
	}
	uassert.Equal(t, -1, s.Index("hello", -1), "out-of-range row")
	uassert.Equal(t, -1, s.Index("hello", 3))
}

// TestRowsHashIndependently checks the per-row seed actually changes the column,
// which is what makes taking the minimum meaningful.
func TestRowsHashIndependently(t *testing.T) {
	s, _ := New(MaxWidth, MaxDepth)
	first := s.Index("some-element", 0)
	differs := false
	for r := 1; r < s.Depth(); r++ {
		if s.Index("some-element", r) != first {
			differs = true
		}
	}
	uassert.True(t, differs, "rows must not all map to the same column")
}

func TestMerge(t *testing.T) {
	a, _ := New(128, 3)
	b, _ := New(128, 3)
	a.AddN("x", 5)
	b.AddN("x", 7)
	b.AddN("y", 2)

	uassert.NoError(t, a.Merge(b))
	uassert.Equal(t, int64(12), a.Estimate("x"), "merged counts add")
	uassert.Equal(t, int64(2), a.Estimate("y"))
	uassert.Equal(t, int64(14), a.Total())
}

func TestMergeRejectsMismatchedShape(t *testing.T) {
	a, _ := New(128, 3)
	uassert.ErrorIs(t, a.Merge(mustNew(t, 64, 3)), ErrBadWidth)
	uassert.ErrorIs(t, a.Merge(mustNew(t, 128, 2)), ErrBadDepth)
	uassert.Equal(t, int64(0), a.Total(), "a rejected merge changes nothing")
}

func TestReset(t *testing.T) {
	s := NewDefault()
	s.AddN("x", 10)
	s.Reset()

	uassert.Equal(t, int64(0), s.Estimate("x"))
	uassert.Equal(t, int64(0), s.Total())
	uassert.Equal(t, 256, s.Width(), "dimensions survive a reset")
}

func TestClone(t *testing.T) {
	s := NewDefault()
	s.AddN("x", 4)

	cp := s.Clone()
	cp.AddN("x", 6)

	uassert.Equal(t, int64(4), s.Estimate("x"), "clone must not share storage")
	uassert.Equal(t, int64(10), cp.Estimate("x"))
	uassert.Equal(t, s.Width(), cp.Width())
}

func TestRowCopy(t *testing.T) {
	s, _ := New(8, 2)
	s.Add("x")

	row := s.Row(0)
	uassert.Equal(t, 8, len(row))
	row[0] = 999
	uassert.False(t, s.Row(0)[0] == 999, "Row returns a copy")

	uassert.True(t, s.Row(-1) == nil)
	uassert.True(t, s.Row(2) == nil)
}

func mustNew(t *testing.T, w, d int) *Sketch {
	s, err := New(w, d)
	uassert.NoError(t, err)
	return s
}

gnomod.toml

module = "gno.land/p/nym-moultest123/x/daily/countminsketch/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186405
  max_deposit = "6000000ugnot"