Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/load.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: load

on:
workflow_dispatch:
schedule:
- cron: '23 8 * * 1'

permissions:
contents: read

jobs:
load:
runs-on: ubuntu-latest
timeout-minutes: 60
env:
CGO_ENABLED: 1
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
- uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Verify load verdict calculations
run: python3 -m unittest discover -s e2e -p test_load_verdict.py
- name: Check tap and proxy load budgets
run: bash e2e/load.sh
- name: Upload load evidence
if: always()
uses: actions/upload-artifact@v6
with:
name: load-results
path: e2e/results/
7 changes: 3 additions & 4 deletions e2e/load_verdict.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""Evaluate a completed Step 31 synthetic load run."""
import json, glob, os, re, sys
import json, glob, math, os, re, sys

def summary(phase, resdir):
with open(os.path.join(resdir, phase + ".summary")) as f:
Expand Down Expand Up @@ -34,7 +34,7 @@ def pctl(path, p):
r = json.loads(line)
xs.append(r["lat_ms"])
xs.sort()
return xs[min(int(p * len(xs)), len(xs) - 1)] if xs else -1
return xs[math.ceil(p * len(xs)) - 1] if xs else -1

def paired_proxy_delta_p99(proxy_path, direct_path):
# Both phases offer the same fixture and reference at each index with
Expand All @@ -58,7 +58,6 @@ def read(path):
if not proxy or proxy.keys() != direct.keys():
return None
deltas = sorted(proxy[index] - direct[index] for index in proxy)
import math
return deltas[math.ceil(0.99 * len(deltas)) - 1]

def main():
Expand All @@ -75,7 +74,7 @@ def main():
overhead = paired_proxy_delta_p99(f"{resdir}/proxy-{workload}-{rep}.jsonl",
f"{resdir}/direct-{workload}-{rep}.jsonl")
if overhead is None:
pending.append(f"{workload} rep{rep}: proxy/direct successful event indexes did not match")
breaches.append(f"{workload} rep{rep}: cannot verify proxy budget without matching successful proxy/direct samples")
tap_stored = stored(f"tap-{rep}.db", f"tap-{workload}-{rep}", datadir)
proxy_stored = stored(f"proxy-{rep}.db", f"proxy-{workload}-{rep}", datadir)
checks = {
Expand Down
4 changes: 4 additions & 0 deletions e2e/test_load_verdict.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ def test_paired_delta_uses_event_distribution(self):
direct = self.records("direct", [2, 3, 4, 5])
self.assertEqual(load_verdict.paired_proxy_delta_p99(proxy, direct), 9)

def test_p99_excludes_maximum_for_100_samples(self):
tap = self.records("tap", range(1, 101))
self.assertEqual(load_verdict.pctl(tap, 0.99), 99)

def test_missing_pair_cannot_pass(self):
proxy = self.records("proxy", [10, 12])
direct = self.records("direct", [2])
Expand Down
218 changes: 50 additions & 168 deletions internal/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package server

import (
"bytes"
"cmp"
"context"
"crypto/hmac"
"crypto/sha256"
Expand All @@ -18,8 +17,6 @@ import (
"os"
"path/filepath"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"sync"
Expand All @@ -30,6 +27,7 @@ import (
"github.com/ostefani/watcherbridge/internal/briefing"
"github.com/ostefani/watcherbridge/internal/config"
"github.com/ostefani/watcherbridge/internal/forwarder"
"github.com/ostefani/watcherbridge/internal/provider"
"github.com/ostefani/watcherbridge/internal/store"
)

Expand Down Expand Up @@ -736,26 +734,17 @@ func TestWALBoundedUnderLoad(t *testing.T) {
}
}

func TestLatencyAndHeapBudgets(t *testing.T) {
func TestTapHeapBudget(t *testing.T) {
if testing.Short() {
t.Skip("latency budgets need a full run")
t.Skip("heap budget needs a full run")
}
h := newHarness(t, func(c *config.Config) { c.Mode = config.ModeTap })
now := time.Now()
const n = 200
durs := make([]time.Duration, 0, n)
for i := 0; i < n; i++ {
start := time.Now()
if rec := h.signedPost(t, uniqueID(), "host-l", "host.appeared", now); rec.Code != http.StatusAccepted {
t.Fatalf("tap request %d: got %d", i, rec.Code)
}
durs = append(durs, time.Since(start))
}
sort.Slice(durs, func(a, b int) bool { return durs[a] < durs[b] })
p99 := durs[int(float64(n)*0.99)]
t.Logf("tap p99 over %d requests: %v (budget 50ms)", n, p99)
if p99 > 50*time.Millisecond {
t.Fatalf("tap p99 %v exceeds 50ms", p99)
}
var mem runtime.MemStats
runtime.GC()
Expand All @@ -764,22 +753,6 @@ func TestLatencyAndHeapBudgets(t *testing.T) {
if mem.HeapInuse > 64<<20 {
t.Fatalf("heap %d bytes exceeds 64MiB budget", mem.HeapInuse)
}

proxy := newHarness(t, nil)
var over []time.Duration
for i := 0; i < n; i++ {
start := time.Now()
if rec := proxy.signedPost(t, uniqueID(), "host-p", "host.appeared", now); rec.Code != http.StatusAccepted {
t.Fatalf("proxy request %d: got %d", i, rec.Code)
}
over = append(over, time.Since(start))
}
sort.Slice(over, func(a, b int) bool { return over[a] < over[b] })
p99over := over[int(float64(n)*0.99)]
t.Logf("proxy overhead p99 over %d requests: %v (budget 25ms)", n, p99over)
if p99over > 25*time.Millisecond {
t.Fatalf("proxy overhead p99 %v exceeds 25ms", p99over)
}
}

func TestShutdownDuringSweepForward(t *testing.T) {
Expand Down Expand Up @@ -959,63 +932,50 @@ func briefingDeps(t *testing.T, h *harness) briefing.Deps {
}
}

type relayTimingTransport struct {
base http.RoundTripper
mu sync.Mutex
byEvent map[string]time.Duration
}

func (t *relayTimingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
start := time.Now()
res, err := t.base.RoundTrip(req)
elapsed := time.Since(start)
t.mu.Lock()
t.byEvent[req.Header.Get("X-SubnetLens-Event-ID")] += elapsed
t.mu.Unlock()
return res, err
}

func (t *relayTimingTransport) take(eventID string) (time.Duration, bool) {
t.mu.Lock()
defer t.mu.Unlock()
elapsed, ok := t.byEvent[eventID]
delete(t.byEvent, eventID)
return elapsed, ok
}

func TestClosureDrainBudgets(t *testing.T) {
func TestProxyIngestProgressWithBriefingBacklog(t *testing.T) {
h := newHarness(t, func(c *config.Config) { c.Mode = config.ModeProxy })
now := time.Now()
seeded := seedClosedGroups(t, h, 256)
ctx := t.Context()
deps := briefingDeps(t, h)

// Install before starting either goroutine. The test uses 100 distinct
// event IDs and consumes each timing after the request returns.
base := h.srv.proxy.Transport
if base == nil {
base = http.DefaultTransport
// Pause the first provider call after the group claim commits and
// before any briefing is written. Provider calls run outside the writer.
providerEntered := make(chan struct{})
releaseProvider := make(chan struct{})
fake := provider.NewFake()
var entered bool
fake.Handle = func(bool, []byte, map[string]struct{}) (provider.RawBriefing, error) {
if !entered {
entered = true
close(providerEntered)
select {
case <-releaseProvider:
case <-ctx.Done():
return provider.RawBriefing{}, ctx.Err()
}
}
return provider.RawBriefing{}, errors.New("test provider unavailable")
}
relay := &relayTimingTransport{base: base, byEvent: make(map[string]time.Duration)}
h.srv.proxy.Transport = relay
deps.Provider = fake

// The test cancels this context before cleanup waits for the worker.
ctx := t.Context()
deps := briefingDeps(t, h)
pending := make(map[string]struct{}, len(seeded))
for _, id := range seeded {
pending[id] = struct{}{}
}
drainDone := make(chan time.Time, 1)
drainDone := make(chan struct{})
// OnBriefing runs on the worker goroutine, which owns pending.
deps.OnBriefing = func(b store.Briefing) {
if _, ok := pending[b.GroupID]; ok {
delete(pending, b.GroupID)
if len(pending) == 0 {
drainDone <- time.Now()
close(drainDone)
}
}
}

runDone := make(chan error, 1)
// The test context is canceled before cleanup waits for the worker.
t.Cleanup(func() {
select {
case err := <-runDone:
Expand All @@ -1026,114 +986,36 @@ func TestClosureDrainBudgets(t *testing.T) {
t.Error("briefing worker did not stop after cancellation")
}
})

const drainBudget = 5 * time.Second
start := time.Now()
go func() { runDone <- briefing.Run(ctx, deps) }()

// Pace requests at up to 50/s and keep sampling after the drain,
// which can finish well before the 100-request workload ends.
type sample struct {
started time.Time
total time.Duration
relay time.Duration
}
type ingestResult struct {
samples []sample
lost int
saturated int
missingRelay int
firstMissingRelay string
}
ingestDone := make(chan ingestResult, 1)
go func() {
tick := time.NewTicker(20 * time.Millisecond)
defer tick.Stop()
var res ingestResult
for i := 0; i < 100; i++ {
<-tick.C
reqStart := time.Now()
id := uniqueID()
rec := h.signedPost(t, id, "host-bg", "host.appeared", now)
elapsed := time.Since(reqStart)
relayElapsed, forwarded := relay.take(id)
res.samples = append(res.samples, sample{started: reqStart, total: elapsed, relay: relayElapsed})
switch rec.Code {
case http.StatusAccepted:
if !forwarded {
if res.missingRelay == 0 {
res.firstMissingRelay = id
}
res.missingRelay++
}
case http.StatusServiceUnavailable:
res.saturated++
default:
res.lost++
}
}
ingestDone <- res
}()

var drainCommitted time.Time
timer := time.NewTimer(time.Until(start.Add(drainBudget)))
defer timer.Stop()
select {
case drainCommitted = <-drainDone:
case <-timer.C:
// The observer may have published before the deadline even if
// both channels became ready before this goroutine was scheduled.
select {
case drainCommitted = <-drainDone:
default:
}
}
res := <-ingestDone
if res.missingRelay > 0 {
t.Errorf("%d accepted proxy requests missing relay timing (first event ID: %s)", res.missingRelay, res.firstMissingRelay)
case <-providerEntered:
case <-time.After(5 * time.Second):
t.Fatal("briefing worker did not enter the provider with the seeded backlog")
}
if drainCommitted.IsZero() || drainCommitted.Sub(start) > drainBudget {
t.Fatalf("%d seeded groups did not finish within %v", len(seeded), drainBudget)
}
t.Logf("%d-group drain completed in %v (budget %v)", len(seeded), drainCommitted.Sub(start), drainBudget)
var during, after []sample
for _, req := range res.samples {
if req.started.Before(drainCommitted) {
during = append(during, req)
} else {
after = append(after, req)

const progressBudget = 2 * time.Second
const requests = 5
for i := 0; i < requests; i++ {
start := time.Now()
rec := h.signedPost(t, uniqueID(), "host-bg", "host.appeared", now)
if rec.Code != http.StatusAccepted {
t.Fatalf("proxy ingest %d while briefing is pending: got %d, want 202", i+1, rec.Code)
}
}
report := func(label string, samples []sample) time.Duration {
if len(samples) == 0 {
t.Logf("%s: 0 requests", label)
return 0
if elapsed := time.Since(start); elapsed > progressBudget {
t.Errorf("proxy ingest %d took %v while briefing was pending (progress ceiling %v)", i+1, elapsed, progressBudget)
}
slices.SortFunc(samples, func(a, b sample) int { return cmp.Compare(a.total, b.total) })
// Nearest rank, converted from a one-based rank to a slice index.
p99 := samples[(99*len(samples)+99)/100-1]
slowest := samples[len(samples)-1]
t.Logf("%s: %d requests, p99 %v (relay to headers %v), max %v (relay to headers %v)",
label, len(samples), p99.total, p99.relay, slowest.total, slowest.relay)
return p99.total
}
// The drain can finish in a few ticker intervals. Keep the gate
// over the full workload and report the small drain cohort separately.
p99 := report("all proxy ingest", res.samples)
report("started before the final seeded briefing committed", during)
report("started after the final seeded briefing committed", after)
if p99 > 50*time.Millisecond {
t.Errorf("proxy ingest p99 across all %d requests was %v (budget 50ms)", len(res.samples), p99)
}
if res.saturated != 0 || res.lost != 0 {
t.Errorf("ingest loss: saturated=%d lost=%d", res.saturated, res.lost)
}
var mem runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&mem)
t.Logf("heap after drain: %d bytes (budget 64MiB)", mem.HeapInuse)
if mem.HeapInuse > 64<<20 {
t.Fatalf("heap %d exceeds 64MiB", mem.HeapInuse)
if got := h.relay.hits.Load(); got != requests {
t.Errorf("relay received %d requests while briefing was pending, want %d", got, requests)
}

close(releaseProvider)
const drainBudget = 5 * time.Second
select {
case <-drainDone:
case <-time.After(drainBudget):
t.Fatalf("%d seeded groups did not finish within %v after releasing the provider", len(seeded), drainBudget)
}
}

Expand Down
4 changes: 2 additions & 2 deletions ui/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading