Skip to content
quarry Artifact [326ecd2bb2]
Login

Artifact [326ecd2bb2]

Artifact 326ecd2bb290c8a7b65aeb5578e70b832e69dbe47a0cb4ba84f8b0835233267e:


//go:build !js && !wasip1

package obsduck

import (
	"context"
	"database/sql"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/obs"
)

func residentMB() string {
	out, err := exec.Command("ps", "-o", "rss=", "-p", strconv.Itoa(os.Getpid())).Output()
	if err != nil {
		return "?"
	}
	kb, _ := strconv.Atoi(strings.TrimSpace(string(out)))
	return fmt.Sprintf("%d MB", kb/1024)
}

// TestMemExperiment is an experiment, not a check: it documents the
// measurement behind ReopenEvery. DuckDB's native memory grows under
// repeated appends and wide reads and is given back only by closing the
// database. It is skipped unless MEMEXP is set, and only a Linux run
// counts, because macOS keeps the memory after a close.
//
//	MEMEXP=keep   go test ./internal/obsduck -run TestMemExperiment -count=1 -v -timeout 9m
//	MEMEXP=reopen go test ./internal/obsduck -run TestMemExperiment -count=1 -v -timeout 9m
//
// It loads 1.3M hits, then 400 times records 256 hits, flushes, and runs
// Traffic over 24h and History, printing resident memory every 50
// iterations; with reopen it also calls Reopen every 100 iterations.
func TestMemExperiment(t *testing.T) {
	mode := os.Getenv("MEMEXP")
	if mode == "" {
		t.Skip("set MEMEXP=keep or MEMEXP=reopen")
	}
	s, err := Open(filepath.Join(t.TempDir(), "ops.duckdb"), 256)
	if err != nil {
		t.Fatal(err)
	}
	defer s.Close()
	// One bulk insert stands in for the day's traffic: varied paths,
	// agents, networks and visitors, so the aggregates have real work.
	if _, err := s.db.Exec(`INSERT INTO hit
		(ts, door, method, url, repo, status, bytes, elapsed_ms, stream, addr, country, ua, referrer,
		 account, claimed, verb, client, version, asn, network, visitor)
		SELECT now() - INTERVAL (i % 86000) SECOND, CASE WHEN i % 5 = 0 THEN 'sync' ELSE 'web' END,
			'GET', '/r/repo' || (i % 300) || '/file/' || (i % 5000), 'repo' || (i % 300),
			200, i % 100000, i % 900, false, '203.0.113.' || (i % 250), 'US',
			'Mozilla/5.0 (X11; Linux x86_64) agent/' || (i % 400), '', '', '', '', '', '',
			CAST(i % 600 AS UINTEGER), 'net' || (i % 600), CAST(i % 90000 AS UBIGINT)
		FROM range(1300000) t(i)`); err != nil {
		t.Fatal(err)
	}
	fmt.Println("loaded 1.3M hits, resident", residentMB())
	now := time.Now()
	for i := 1; i <= 400; i++ {
		for j := 0; j < 256; j++ {
			s.Hit(obs.Hit{At: now, Door: obs.DoorWeb, URL: fmt.Sprintf("/r/repo%d/x", j), Repo: "repo", Status: 200,
				UA: fmt.Sprintf("Mozilla/5.0 agent/%d", j), Visitor: uint64(j), Addr: "203.0.113.7", ASN: uint32(j), Network: "n"})
		}
		s.Flush()
		if _, err := s.Traffic(obs.TrafficQuery{Now: time.Now(), Range: obs.RangeNamed("24h")}); err != nil {
			t.Fatal(err)
		}
		if _, err := s.History(obs.HistoryQuery{}); err != nil {
			t.Fatal(err)
		}
		if i%50 == 0 {
			fmt.Printf("iteration %d resident %s\n", i, residentMB())
		}
		if mode == "reopen" && i%100 == 0 {
			if err := s.Reopen(); err != nil {
				t.Fatal(err)
			}
			fmt.Printf("iteration %d after reopen resident %s\n", i, residentMB())
		}
	}
}

// peakWhile samples resident memory every 100 ms while f runs and
// returns the highest reading in MB.
func peakWhile(f func()) int {
	var peak int
	stop, done := make(chan struct{}), make(chan struct{})
	go func() {
		defer close(done)
		for {
			if kb, err := exec.Command("ps", "-o", "rss=", "-p", strconv.Itoa(os.Getpid())).Output(); err == nil {
				if n, _ := strconv.Atoi(strings.TrimSpace(string(kb))); n/1024 > peak {
					peak = n / 1024
				}
			}
			select {
			case <-stop:
				return
			case <-time.After(100 * time.Millisecond):
			}
		}
	}()
	f()
	close(stop)
	<-done
	return peak
}

// duckMB is what DuckDB says it holds: memory in use and spilled temp
// files, in MB.
func dirMB(dir string) int64 {
	var n int64
	filepath.WalkDir(dir, func(_ string, d os.DirEntry, err error) error {
		if err == nil && !d.IsDir() {
			if fi, err := d.Info(); err == nil {
				n += fi.Size()
			}
		}
		return nil
	})
	return n >> 20
}

func duckMB(s *Sink) string {
	var mem, tmp float64
	if err := s.db.QueryRow(`SELECT coalesce(sum(memory_usage_bytes),0), coalesce(sum(temporary_storage_bytes),0) FROM duckdb_memory()`).Scan(&mem, &tmp); err != nil {
		return "?"
	}
	return fmt.Sprintf("memory %.0f MB, temp storage %.0f MB", mem/1e6, tmp/1e6)
}

// TestMemExperimentTraffic measures the 30-day Traffic read against a
// store of ~4M hit rows over 14 days (the forge keeps 14 days of ~330k a
// day), with and without the bounds in openDSN. Each mode is its own
// process, so one run's retained memory does not count against the next:
//
//	MEMEXP=traffic-gen MEMEXP_DB=/path/ops.duckdb go test ./internal/obsduck -run TestMemExperimentTraffic -count=1 -v -timeout 20m
//	MEMEXP=traffic-old MEMEXP_DB=/path/ops.duckdb go test ... (no limit, all cores)
//	MEMEXP=traffic-new MEMEXP_DB=/path/ops.duckdb go test ... (as shipped)
func TestMemExperimentTraffic(t *testing.T) {
	mode := os.Getenv("MEMEXP")
	path := os.Getenv("MEMEXP_DB")
	if !strings.HasPrefix(mode, "traffic-") || path == "" {
		t.Skip("set MEMEXP=traffic-gen|traffic-old|traffic-new and MEMEXP_DB")
	}
	if v := os.Getenv("MEMEXP_LIMIT"); v != "" {
		defer func(old string) { memoryLimit = old }(memoryLimit)
		memoryLimit = v
	}
	s, err := Open(path, 256)
	if err != nil {
		t.Fatal(err)
	}
	defer s.Close()
	if mode == "traffic-gen" {
		for c := 0; c < 8; c++ {
			if _, err := s.db.Exec(fmt.Sprintf(`INSERT INTO hit
			(ts, door, method, url, repo, status, bytes, elapsed_ms, stream, addr, country, ua, referrer,
			 account, claimed, verb, client, version, asn, network, visitor)
			SELECT now() - INTERVAL ((i * 7919) %% 1209600) SECOND, CASE WHEN i %% 5 = 0 THEN 'sync' ELSE 'web' END,
				'GET', '/r/repo' || (i %% 300) || '/blob/main/internal/pkg' || (i %% 50) || '/file' || (i %% 5000) || '.go',
				'repo' || (i %% 300), 200, i %% 100000, i %% 900, false, '203.0.113.' || (i %% 250), 'US',
				'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/' || (i %% 90) || '.0.' || (i %% 400) || '.0 Safari/537.36',
				CASE WHEN i %% 3 = 0 THEN 'https://example.org/search?q=' || (i %% 700) ELSE '' END,
				'', '', '', '', '',
				CAST(i %% 600 AS UINTEGER), 'net' || (i %% 600), CAST(i %% 90000 AS UBIGINT)
			FROM range(%d, %d) t(i)`, c*500000, (c+1)*500000)); err != nil {
				t.Fatal(err)
			}
		}
		var n int
		s.db.QueryRow(`SELECT count(*) FROM hit`).Scan(&n)
		fmt.Println("generated", n, "hit rows")
		return
	}
	if mode == "traffic-old" {
		s.open = func(ctx context.Context, p string) (*sql.DB, error) { return openAt(ctx, p, p) }
		if err := s.Reopen(); err != nil {
			t.Fatal(err)
		}
	}
	var limit, threads string
	s.db.QueryRow(`SELECT current_setting('memory_limit')`).Scan(&limit)
	s.db.QueryRow(`SELECT CAST(current_setting('threads') AS VARCHAR)`).Scan(&threads)
	fmt.Printf("%s: memory_limit %s, threads %s, resident before %s\n", mode, limit, threads, residentMB())
	for i := 1; i <= 4; i++ {
		var took time.Duration
		peak := peakWhile(func() {
			start := time.Now()
			if _, err := s.Traffic(obs.TrafficQuery{Range: obs.RangeNamed("30d")}); err != nil {
				t.Error(err)
			}
			took = time.Since(start)
		})
		fmt.Printf("%s: run %d took %s, peak resident %d MB, resident after %s, %s, spill files on disk %d MB\n", mode, i, took.Round(time.Millisecond), peak, residentMB(), duckMB(s), dirMB(path+".tmp"))
	}
}