vis

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 43 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

vis

A live dashboard, SLOs and runtime knobs for Go services, for people and agents. No collector, no cloud.

vis showcase

Ollama adopts vis: two lines, a few comments, tuned while it runs, kept in its objective by an agent on call.

Install

go get github.com/tfcace/vis

See

func hello(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) }

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /hello", hello)

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	if err := vis.Start(ctx, vis.Service("myservice")); err != nil {
		log.Fatal(err)
	}
	defer vis.Stop()
	srv := &http.Server{Addr: ":8080", Handler: vis.HTTP(mux)}
	go srv.ListenAndServe()
	<-ctx.Done()
	srv.Shutdown(context.Background())
}
go run .
open http://localhost:7071
router wrap it with
net/http ServeMux vis.HTTP(mux)
gin r.Use(visgin.Middleware()), from github.com/tfcace/vis/integrations/visgin
echo e.Use(visecho.Middleware()), from github.com/tfcace/vis/integrations/visecho
any other vis.HTTP(h, vis.RouteName(func(r *http.Request) string { ... }))
on the dashboard
latency p99 of every route, the last hour
runtime CPU and throttling, scheduler wait, GC, goroutines
memory use and the live heap; against the limit and when it gets there, with one: a cgroup's (a container, a Kubernetes pod, systemd MemoryMax), Lambda's memory size, or GOMEMLIMIT
restarts why the last process died, and what it took with it
today every change, with what it did

Judge

//go:generate go tool vis gen

// vis:slo p99=500ms
func hello(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) }
go get -tool github.com/tfcace/vis/cmd/vis
go generate ./...
p99=500ms on GET /hello
headline "All good.", or "Latency is over the SLO."
latency chart the objective as a red dashed line, the time over it shaded
impact reports each change judged by what it did to the objective's route
rules when="slo.p99 > 400ms" acts before the objective is missed
agents describe and fleet say whether it is met
vis vet an objective whose route never serves

Tune

// vis:knob range=1..16384 default=100 unit=MB uses=memory pull=agent
var CacheSize vis.Int // Memory for cached images.

// vis:knob range=1..100 default=95 uses=cpu pull=agent,rule
// vis:rule name=quality_backoff when="slo.p99 > 400ms" for=30s do=step(-5) cooldown=30s lease=10m
var JPEGQuality vis.Int // JPEG quality of resized images.

// vis:signal unit=images/s
var OriginFetches vis.Gauge // Images fetched from origin servers per second.
q := JPEGQuality.From(r.Context())
CacheSize.Bind(func(mb int) { cache.Resize(mb * 1_000_000) })
every change
bounded within the declared range
leased ends on its own; a person may pin it with no end
audited who, why, when
measured what it did to latency, CPU and memory

Agents

agent give it
adopting vis in your code "Read go doc github.com/tfcace/vis, then adopt vis." The guide is the package doc: four adoption steps, every directive, and how to check the result with vis vet
on call the MCP server below; its instructions, its tools' descriptions and describe show how to look before acting
VIS_TOKENS=s3cret=agent:oncall:act go run .
{"mcpServers": {"vis": {"type": "http", "url": "http://127.0.0.1:7070",
  "headers": {"Authorization": "Bearer s3cret"}}}}

Check

command run it it catches
go tool vis vet ./... before a commit, in CI directives vis gen can't read; vis_gen.go out of date; a knob read before it is declared; a rule in the wrong unit or outside its knob's range; an SLO on a route that never serves
go tool vis diff [ref] reviewing a change knobs, signals, SLOs and rules added, removed or changed since ref (default HEAD)
go tool vis diff -check in CI on a pull request exit 1 when automation gets more room: a new writer, a wider range, a new rule, a longer lease, a slower p99, a removed SLO

Surfaces

surface default address access
dashboard 127.0.0.1:7071 no login; acts as VIS_UI_USER; keep it on localhost
MCP 127.0.0.1:7070 read-only without VIS_TOKENS
fleet gossip :7946 only with VIS_CLUSTER_KEY

Configuration

variable option default
VIS_LISTEN MCPAt(addr) 127.0.0.1:7070; "" off
VIS_UI_LISTEN UIAt(addr) 127.0.0.1:7071; "" off
VIS_TOKENS Tokens(...) none: read-only
VIS_UI_USER UIUser(id) the OS user
VIS_UI_HOSTS UIHosts(...) localhost only
VIS_STATE_DIR StateDir(dir) the temp dir; an emptyDir on Kubernetes
VIS_CLUSTER_KEY ClusterKey(key) none: no fleet
VIS_SEEDS Seeds(addrs...) none
VIS_PEER_LISTEN PeerAt(addr) :7946
VIS_PEER_ADVERTISE PeerAdvertise(addr) the listen address
VIS_INSTANCE_NAME InstanceName(name) the hostname
VIS_FLEET_WAIT FleetWait(d) 2s

Status

area v0.1
dashboard, SLOs, knobs, layers, leases, audit, vis gen, vis vet, vis diff stable
rules, impact reports, memory forecast, restart stories, MCP tools stable, still growing
fleet, rollouts experimental

Example

examples/cacheproxy: a caching proxy with knobs, signals, rules and an SLO.

Reference

go doc github.com/tfcace/vis

License

MIT

Documentation

Overview

Package vis gives a Go service runtime knobs: typed, bounded settings that people, AI agents and the service's own rules can change while it runs. Each change carries a reason, lasts for an agreed duration, and is audited. vis also measures the service: each route's latency against its objective, the Go runtime, and what every change did. People see it all in a live control UI; agents reach it over MCP.

Declaring with directives

The easiest way to declare is to annotate: put // vis: comments above your own declarations, and go generate writes the vis calls into vis_gen.go, an ordinary Go file you check in and can read.

//go:generate go tool vis gen

// vis:knob range=1..16384 default=100 unit=MB uses=memory pull=agent
var CacheSize vis.Int // Memory for cached images.

// vis:knob range=1..100 default=95 uses=cpu pull=agent,rule
// vis:rule name=quality_backoff when="slo.p99 > 400ms" for=30s do=step(-5) cooldown=30s lease=10m
var JPEGQuality vis.Int // JPEG quality of resized images.

// vis:knob range=100ms..30s default=5s
var FetchTimeout vis.Duration // How long to wait for an origin.

// vis:knob pull=agent
var Logging vis.LogLevel // What the service logs.

// vis:signal unit=images/s
var OriginFetches vis.Gauge // Images fetched from origin servers per second.

// vis:slo p99=500ms
func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) { ... }

Add the tool to your module once with go get -tool github.com/tfcace/vis/cmd/vis, then run go generate. A knob's name comes from its variable (CacheSize is cache_size; name= overrides it) and its description from its comment; env=MAX_LOADED lets that environment variable set its default, as configuration read from the environment did before (a bad value keeps the default, with a warning). An slo takes its route from where the package registers the handler, with HandleFunc or Handle, or as a gin or echo route; give route="GET /path" when vis gen can't tell, and it says so. A service that routes on its own, with no ServeMux, gives route= on every slo and names its routes with RouteName (see Routes); writing those calls by hand is as easy there. A vis.LogLevel knob needs neither range= nor default= (it runs DEBUG..ERROR from INFO), takes levels by name (range=trace..error default=warn, do=set(debug); TRACE is DEBUG-4, which slog leaves unnamed), and is a slog.Leveler: give it to your handler, slog.HandlerOptions{Level: Logging}, and changing the knob changes what the service logs, with no LevelVar in between. Build that handler in main, not in a package-level variable, which vis gen's init hasn't declared yet. Mistakes are reported at their line, with how to fix them. The keys:

knob    (above a vis.Int, vis.Duration or vis.LogLevel var)
        range=lo..hi default= special=v:"meaning" unit= pull=agent,rule uses= saves= env= name= about=
signal  (above a vis.Gauge or vis.Latency var) unit= name= about=
slo     (above a handler func) p99= route=
rule    (below a knob's directive) when="<measure> > <threshold>" do=step(N)|step(P%)|set(V)|reset
        for= cooldown= lease= deadband= max_drift= stall= mode=shadow every= name=

A rule watches sched.p99, gc.cpu, cpu.throttled, cpu.used, goroutines, slo.p99 (the package's one objective), a route by name, as in slo(POST /api/generate).p99, which may be served by another package, or one of the package's signals; its threshold is a duration, a number, or one of the package's knobs. Its action steps the knob (by a duration, for a Duration knob: step(-1ms)), sets it to one value, or resets it, ending what rules set on it so it falls back to the value below them: one rule can undo another's. Each value must fit the knob's range. Costs (uses, saves) are cpu, memory, or a signal. vis gen registers everything in an init function, so don't copy a knob into another package-level variable: read it where you use it.

Check it, in CI or before a commit, with go tool vis vet ./...: it reports the mistakes that compile and run but are wrong, each with how to fix it. A directive vis gen can't read; a vis_gen.go out of date with the directives; a knob read during package initialization, or copied before vis gen's init declares it; a rule whose knob doesn't let rules change it, whose threshold is in the wrong unit for what it watches, or whose action doesn't fit its knob's range; and an SLO naming a route no handler in its package is registered under.

To review a change to what the service declares, run go tool vis diff [ref]: it lists the knobs, signals, objectives and rules added, removed or changed since a git revision (HEAD by default), marking with ! each change that gives automation more room or loosens an objective: a new writer, a wider range, a new rule, a longer lease, a slower p99, a removed objective. It reads hand-written calls and directives alike. With -check it exits 1 when there is such a change, so CI can ask for a review.

The steps below show the calls the directives generate, which you can also write by hand where you can't generate.

Adopting vis in four steps

1. Declare knobs as package-level variables, next to the code they tune. A declaration is reviewed code: its range, default and unit can't change at runtime, only its value.

var (
	CacheSize = vis.NewInt("cache_size", vis.Range(1, 16384), vis.Default(100), vis.Unit("MB"),
		vis.Uses(vis.Memory), vis.Pull(vis.Agent),
		vis.About("Memory for cached images."))
	JPEGQuality = vis.NewInt("jpeg_quality", vis.Range(1, 100), vis.Default(95),
		vis.Uses(vis.CPU), vis.Pull(vis.Agent, vis.Rule),
		vis.About("JPEG quality of resized images."))
	FetchTimeout = vis.NewDuration("fetch_timeout",
		vis.Range(100*time.Millisecond, 30*time.Second), vis.Default(5*time.Second))
)

About is what people and agents read about the knob. Pull says which automated writers may change it, agents and rules; people always may (pull=people,agent in a directive says so, for whoever reads it). Uses and Saves are optional: they say what turning the knob up costs and what it saves, each either CPU or Memory, which vis measures itself, or one of your own gauges (step 4): bytes sent, say, as a bytes_out_per_s gauge. When the service runs short of CPU or memory, the UI and agents are told which knobs use it and how far up each one is, so whoever is on call knows what to turn down without reading your code.

2. Read them where the work happens. In a request, read the knob from the request's context: every knob a request reads comes from one snapshot, taken when the request arrived, so a request never sees half of a change.

q := JPEGQuality.From(r.Context())

For something you build from a knob, such as a cache whose size is a knob, use Bind. It calls your function once right away with the knob's current value, then again each time someone changes the knob, so the cache is created at today's size and resized the moment anyone changes it:

CacheSize.Bind(func(mb int) { cache.Resize(mb * 1_000_000) }) // your cache's own resize

Anywhere else, such as a background worker, FetchTimeout.Now() is the value right now.

3. Declare objectives beside your handlers, then start vis. An objective (SLO) says how fast a route must be: here, 99% of requests to it finish within 50 ms, measured inside the service. The route is named as http.ServeMux registered it, so share one constant:

const keyRoute = "GET /k/{key}"

var KeySLO = vis.NewSLO(keyRoute, vis.P99(50*time.Millisecond))

mux.HandleFunc(keyRoute, serveKey)

The UI's headline, agents, impact reports and rules judge the service by its first declared objective. (The SLO option gives a single instance an objective of its own, as tests do; a service declares its objectives with NewSLO.) Then, in main:

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := vis.Start(ctx, vis.Service("imageproxy")); err != nil {
	log.Fatal(err)
}
defer vis.Stop()
srv := &http.Server{Addr: *addr, Handler: vis.HTTP(mux)}
go func() {
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		log.Fatal(err)
	}
}()
<-ctx.Done()                       // Ctrl-C, or SIGTERM from docker stop or Kubernetes
srv.Shutdown(context.Background()) // the requests in flight finish, then Stop runs

Keep the last two lines. Catching a signal turns off Go's own exit on it, so a main that serves until it is killed would ignore Ctrl-C and SIGTERM, and a deploy would wait on it until it is killed. Ending on ctx is also what lets vis tell a fleet this instance is leaving (see Fleets).

Start serves the control UI on localhost:7071 and MCP on localhost:7070, and runs the rules you declared. Bind, Now and SetDefault may run before Start: they use the same default instance, and Start's options still apply. HTTP times every request under its route. Open http://localhost:7071 to see and turn the knobs. That is a working adoption; the rest is optional.

4. Publish what only your service knows, and teach it a reflex. A gauge is a number your service computes that people, agents and rules should see. Declare it like a knob and Set it wherever your code already computes it:

var HitShare = vis.NewGauge("cache_hit_share",
	vis.About("Share of images served from the cache over the last 10 s, 0 to 1."))

for range time.Tick(10 * time.Second) { // the stats loop that already counts hits
	served, hits := p.takeCounts()
	HitShare.Set(float64(hits) / float64(max(served, 1)))
}

NewLatency is a gauge of a time.Duration, which a rule watches with a latency threshold; NewGaugeFunc computes its value each time it is read.

A rule is a reflex compiled into the service: when what it watches stays over its threshold, it steps a knob, each step lasting an agreed duration.

var QualityBackoff = vis.NewRule(vis.RuleSpec{
	Name:  "quality_backoff",
	Knob:  JPEGQuality, Step: -5, // in the knob's own unit
	Watch: vis.RouteP99("GET /{options}/{remote}"),
	Over:  vis.Fixed(400 * time.Millisecond), // or a Duration knob, so people can tune it
	For:   30 * time.Second, Cooldown: 30 * time.Second, Lease: 10 * time.Minute,
})

It lowers the quality by 5 every 30 s while the route's p99 is over 400 ms, each step lasting 10 minutes. A rule moves its knob at most MaxDrift from the value below it, by default four steps, so this one never takes the quality below 75; it says so when it starts, in the UI and over MCP. It stops by itself if its steps don't move what it watches. If they do but the objective gets worse, or stays broken without coming closer (by a quarter of the way to its target, from where the step before left it) for Stall steps in a row, vis undoes its change and stops it, saying which. A step after which 10% more of the objective's requests fail (5xx) is stopped the same way, however much p99 improved: a request that fails fast is no win. A refused request (429) is counted apart and reported beside p99, in impact reports too, but doesn't stop a rule, since shedding load can be the point. NewRule checks the rule when it is declared and panics saying what to fix: a knob without Pull(Rule), a threshold in the wrong unit for what it watches, no step.

A quality steps by a fixed amount. A size, a count or a concurrency limit responds to ratios, so step it by a share of its value instead: Do: vis.StepPercent(-25) (do=step(-25%)) takes a batch of 64 to 48, 36, 27 and 20, where a fixed step of -16 would take 16 to 1 in one step. vis vet points out a fixed step that cuts its knob by more than half.

A Duration knob's Step and MaxDrift count nanoseconds, so write them as durations: Step: int64(-time.Millisecond). Instead of a Step, Do takes vis.StepPercent(p), vis.SetTo(v) or vis.Reset().

To time part of a request, wrap it in a probe: defer vis.Probe(ctx, "origin")().

The words vis uses

  • Knob: a declared setting with a range, a default and a unit.
  • Writer: who changes a knob: a person, an agent, a rule, or a fleet rollout.
  • Layer: each kind of writer has its own slot on every knob, and the highest one that is set wins: a person's pin over a rule, over an agent, over a fleet rollout, over the default. When a value ends, the knob falls back to the next one down. Instance.Stack lists them.
  • Lease: the agreed duration an automated writer's value lasts. Agents and rules must give one, so nothing they set outlives its reason.
  • Change: one or more knobs set together, with a reason. Every change is audited and measured: 30 s later vis reports what moved.
  • Snapshot: every knob's value at one moment. A request reads one snapshot from start to end.
  • SLO: a route's objective, such as p99 under 50 ms.
  • Gauge (signal): a number only your service knows, published to people, agents and rules.
  • Rule: a compiled-in reflex that steps a knob while what it watches is too high.
  • Cost (Uses, Saves): what turning a knob up spends or saves: CPU, Memory, or one of your gauges.

Routes

vis times every request under its route: the http.ServeMux pattern that served it, such as "GET /k/{key}". A handler that routes on its own leaves the pattern empty, and vis counts its requests as "unmatched". Name the routes yourself with RouteName, and give the SLO the same name:

vis.HTTP(proxy, vis.RouteName(func(r *http.Request) string {
	if r.URL.Path == "/health-check" {
		return "GET /health-check"
	}
	return imageRoute
}))

With directives, put the slo above the func that does that route's work, even though nothing registers it, and give the route as RouteName returns it (route= is a string, so it repeats the constant):

// vis:slo p99=500ms route="GET /{options}/{remote}"
func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) { ... }

A rule in the same package reads it as slo.p99; from another package, such as main, name the route: when="slo(GET /{options}/{remote}).p99 > 500ms". What vis times is what RouteName returns, so a route= that doesn't match it is an objective no request counts toward: vis warns about it once requests come in.

With gin or echo, use their middleware instead of vis.HTTP: it names each route as the router does, "POST /api/generate" or "GET /k/:key", and a // vis:slo above a handler the router registers finds that route itself. Each is its own module, so vis doesn't depend on either:

r.Use(visgin.Middleware())       // github.com/tfcace/vis/integrations/visgin
e.Use(visecho.Middleware())      // github.com/tfcace/vis/integrations/visecho

If an SLO's route never serves while others do, vis warns in the UI and over MCP, naming the routes that do.

Reading knobs below a cache, or outside a request

From reads the snapshot HTTP puts in the request's context. Without one, in code vis.HTTP didn't serve, it reads the knob's value now in the default instance, so nothing panics; but that request loses its consistent snapshot, and probably its timing, so vis reports the reads, per knob, with how to fix them: in the UI, over MCP's describe, and once in the log. A test that calls a handler directly works the same way; to read a test's own instance, wrap the handler with in.HTTP.

Code the request context doesn't reach (a RoundTripper, a worker, a cache) should get the value from the request that started the work: read it once in the handler and pass it down. If the value changes what you cache, as an image's quality does, make it part of the cache key, or a change will keep serving what was cached before it.

Keep vis in your service, not in libraries it imports: declare knobs, objectives, gauges and rules in the service, and pass values to a library through its own options or hooks, as you would any setting.

Declaring knobs from flags

Declare knobs at package level. To keep an existing flag as a knob's default, call SetDefault after flag.Parse and before Start, Bind or Now:

flag.Parse()
if err := CacheSize.SetDefault(*cacheMB); err != nil {
	log.Fatal(err) // outside the knob's range, which the error names
}

Range returns a knob's declared range, so a flag's own check needn't repeat it.

The knob's env= variable (vis.Env) beats SetDefault: what the operator set for this process wins over the code's default. A bad value in it falls back to the default SetDefault gave, and vis says so.

When a setting's 0 means "work it out", as "three per GPU" does, don't make 0 a knob value: people, agents and rules would read 0 and a rule would step from it, while the service runs with three. Work the value out at startup, start the range at 1, and pass the value to SetDefault; default= in the directive is the fallback for when it can't be worked out:

// vis:knob range=1..64 default=3 env=MAX_LOADED pull=agent,rule
var MaxLoaded vis.Int // Models kept loaded at once. Starts at three per GPU.

gpus := discoverGPUs()
if err := MaxLoaded.SetDefault(3 * max(len(gpus), 1)); err != nil {
	log.Fatal(err)
}
vis.Start(ctx) // after the code that knows the value

Every value is then what the service runs with: the UI and agents see 3, and a rule's step(1) goes to 4.

When a setting's 0 means none instead, as imageproxy's -timeout 0 means no limit, keep it: declare 0 as the knob's special value, a value outside the range that the service gives its own meaning, and start the range past it:

// vis:knob range=1s..5m default=0s special=0s:"no limit" pull=agent,rule
// vis:rule name=fail_fast when="slo.p99 > 500ms" do=step(-1s) lease=10m mode=shadow
var RequestTimeout vis.Duration // Time limit for a request.

if err := RequestTimeout.SetDefault(*timeout); err != nil { // -timeout 0 is still no limit
	log.Fatal(err)
}

The code reads it as before (From returns 0, so if timeout > 0 still works), and people and agents see it, and set it, by name: "no limit". vis never calculates with it, so it needn't know which side of the range "no limit" is on. A rule never moves the knob into it or out of it: from 3s, fail_fast steps down to 1s and stops there; at no limit it stands aside and says why. (Special(time.Duration(0), "no limit") without directives.) Don't put the 0 inside the range instead: a rule stepping down from 1s would land on it and turn the limit off.

Units

An Int knob's unit is a label (Unit("MB")); its range, default and a rule's steps count in it. A Duration knob's range and default are time.Durations, so a bare 10 can't mean 10 ns. A LogLevel knob's are slog.Levels, which people and agents see by name: TRACE, DEBUG, INFO, WARN, ERROR. A rule's threshold and dead band are Levels: vis.Fixed(400*time.Millisecond) or a Duration knob against a latency, vis.Fixed(0.9) against a gauge. NewRule checks they match.

The control UI and its JSON API

The UI is a page at / and a JSON API under /api/, which scripts can use too. It acts as one person (VIS_UI_USER, by default the OS user), so keep it on localhost.

curl localhost:7071/api/state   # what the UI shows: knobs, SLOs, gauges, rules, stories
curl -X POST localhost:7071/api/apply \
  -d '{"set": {"jpeg_quality": 40}, "for": "10m", "reason": "testing quality"}'
curl -X POST localhost:7071/api/clear -d '{"knob": "jpeg_quality", "reason": "done"}'

"for" is a Go duration; without it, a person's value has no end. A person's value is on the pin layer either way. In /api/state, "slo" is the main objective, the one the headline judges, and "slos" lists them all.

MCP for agents

MCP is served at / on localhost:7070. Without VIS_TOKENS, anyone who can reach it may read, and no one may act. With it, every request needs one of its tokens, and only tokens granted act may act: VIS_TOKENS=token=agent:oncall:act. Responses are MCP's event streams, so use an MCP client rather than plain curl. An agent's client config:

{"mcpServers": {"vis": {"type": "http", "url": "http://127.0.0.1:7070",
  "headers": {"Authorization": "Bearer <token>"}}}}

Fleets

Instances of one service that share a cluster key form a fleet: give each the same VIS_CLUSTER_KEY and a seed to join through, VIS_SEEDS=cp-1:7946 (a host:port, several, or a DNS name that resolves to them; an instance may list itself). They find each other by gossip on a port of their own, VIS_PEER_LISTEN (:7946), which the other instances must reach; every message is signed with the key, and instances of other services or keys are refused, with the reason in Warnings. Nothing else is configured: members, their builds and whether they're alive come from the fleet itself.

Any instance then answers for all of them. MCP's fleet tool compares the members (each objective's p99 across the fleet from merged histograms, CPU and throttling, the members that stand out and what's different about them: a CPU limit, a build, a knob), and every other tool takes instance, a member's name, and runs there under the caller's own token, which that member checks. A change for every member is a rollout: one member first, then, if it got no worse than the rest over the same windows, the others; a first stage that hurt is undone, and one it can't judge is kept and the rollout stops. It answers within the minute an MCP client waits: with its result and how to take it back (undo), or that it is still running, with a member's full patience, when members are slow. Fleet, asked of any member, shows the fleet's last rollout (last_rollout: how it ended, its undo, then each member from its own change and the fleet before and after). A rollout is refused while another runs, and while frozen. A freeze on one member holds them all. The UI judges the fleet: its headline names a member over the objective the rest meet, wherever the page is open, and any member can be opened and changed from it. Its API takes ?instance=cp-2 the same way: inside a fleet, members trust each other's UI to say which person is acting, so keep every member's UI on localhost, as one member's already is.

A member that stops cleanly says so and leaves at once. The main in step 3 of the adoption makes a stop clean: Start's context ends on SIGTERM as well as Ctrl-C, which is what docker stop and Kubernetes send; the server shuts down when it does; and the deferred Stop tells the fleet and returns once it has. Without SIGTERM in NotifyContext, Go ends the process on it before vis can say anything, and the fleet can't tell the stop from a crash. A member that goes silent may still be taking traffic, so it stays listed, dead, for 10 minutes or until an instance restarts under its name, and the fleet's objective can't read as met while it is unaccounted for. Where names don't come back (a Kubernetes Deployment gives a new pod a new name), a person forgets it: POST /api/forget on any member's UI. The fleet also shows what each member holds above its defaults and when each value ends, and how often a member restarted, with what the restart dropped: runtime values live in the process, so a restart, a deploy included, undoes them. And it says what every member shares, which a comparison can't: a pressure, a change in their environment such as a CPU limit cut on all of them, a value they all hold and when it ends. A member too busy to answer within VIS_FLEET_WAIT (2 s) is shown from what its gossip last carried; raise it where members answer slowly by design. However high it is, a call forwarded to a member waits at most 20 s for it to start answering, and 55 s in all, so that it answers within the minute an MCP client waits.

Configuration

Each setting comes from the environment or from an option given to Start; the option wins:

VIS_LISTEN     MCPAt(addr)                  MCP's address: 127.0.0.1:7070; "" turns it off
VIS_UI_LISTEN  UIAt(addr)                   the UI's address: 127.0.0.1:7071; "" turns it off
VIS_TOKENS     MCPAt(addr, Tokens(...))     who may use MCP, and who may act: no one, so read-only
VIS_UI_USER    UIAt(addr, UIUser(id))       the person the UI acts as: the OS user
VIS_UI_HOSTS   UIAt(addr, UIHosts(...))     host names the UI answers to beyond localhost
VIS_STATE_DIR  StateDir(dir)                where it keeps its last word: the temp dir

A process that dies without stopping cleanly (an OOM kill, a crash) can't say why, so the one that replaces it does: "most likely killed for memory" when its container was at its memory limit, with what the death dropped (values people, agents and rules had set) and how to set each back. vis doesn't set them back itself, since one may be what killed it, unless its writer asked: a change with Tx.Keep (set_knob's keep) is set back after a restart, clean or not, as its writer, for what is left of its lease, and the death story says so and which lease to revert. If the fresh process it was set back on dies within a minute, it may be what kills it: vis stops setting it back, and the story says so and how to set it back anyway. In a crash loop each death also names what earlier ones dropped, until someone sets the knob again or its lease ends. The restarted process numbers its changes and leases on from the former one's, and set_knob warns of a change on a process seconds from its memory limit, which a kill would take with it. describe and impact reports say when the container reaches its memory limit at the rate since the last change, however far ahead: how long a fix buys. The former process's last word comes from its peers in a fleet (its last digest if it died, what it said as it left if it stopped), and alone from a note in VIS_STATE_DIR, one per process (by PID), written every couple of seconds and on each change. A note whose process still runs isn't a former one's: two processes under one name on a host is a warning. Docker keeps the temp dir across a restart; on Kubernetes, mount an emptyDir volume there. The note is optional: where it can't be written, vis says so in its warnings and goes on. The guide's main stops through Stop, which marks the note clean: no death to tell.

and for a fleet (see Fleets):

VIS_CLUSTER_KEY     ClusterKey(key)         the secret every member shares; without it, no fleet
VIS_SEEDS           Seeds(addrs...)         members to join through, comma-separated
VIS_PEER_LISTEN     PeerAt(addr)            where peers reach this one: :7946
VIS_PEER_ADVERTISE  PeerAdvertise(addr)     the address peers should use, when the one it listens on isn't
VIS_INSTANCE_NAME   InstanceName(name)      its name in the fleet, stable across restarts: the hostname
VIS_FLEET_WAIT      FleetWait(d)            how long a fleet question waits for each member: 2s

The default instance

The package-level functions (Start, HTTP, and a knob's Bind and Now) work on one instance per process, the default instance, the way slog.Default and http.DefaultServeMux do. That is global state, with consequences you should know:

  • Everything declared (knobs, SLOs, gauges, rules) belongs to the process, and Start runs once; a second call returns ErrStarted.
  • Tests that use the default instance share it, so they can't run in parallel. A test that needs its own state takes its own instance.

Tests and several instances

Tests, and programs that need more than one instance, create instances with NewInstance and use its methods: in.HTTP, in.Serve, in.Apply, in.RunRules, and a knob's BindIn and Get(in.Snapshot()). vistest.Start(t) gives a test its own instance, so tests can run in parallel, and vistest.Ring(t, n) a joined fleet of n, over an in-memory network that testing/synctest runs in no time.

Index

Constants

View Source
const MaxFreezeReason = 140

MaxFreezeReason caps a freeze reason so the record stays one gossip message.

View Source
const MaxHistory = 1000

MaxHistory is how many audit events an instance keeps in memory. The full trail goes to the logger; this is the recent part, for agents and the UI.

View Source
const MaxRoutes = 256

MaxRoutes caps how many routes an instance tracks. Route names can come from request paths, which are user input, so requests beyond the cap count under "other".

Variables

View Source
var (
	ErrUnknownKnob   = errors.New("vis: unknown knob")
	ErrOutOfRange    = errors.New("vis: value out of range")
	ErrDefaultLayer  = errors.New("vis: the default layer is set in code")
	ErrLeaseRequired = errors.New("vis: fleet, agent and rule values need a lease")
	ErrActorRequired = errors.New("vis: a change needs an actor")
	ErrFrozen        = errors.New("vis: automated changes are frozen")
	ErrNotAllowed    = errors.New("vis: writer not allowed")
	ErrConflict      = errors.New("vis: conflicting change")
	ErrEmptyChange   = errors.New("vis: a change needs at least one knob")
	ErrUnknownLease  = errors.New("vis: unknown or ended lease")
	ErrUnknownRule   = errors.New("vis: unknown rule")
)
View Source
var (
	// SchedP99 is the Go runtime's scheduler latency p99 over the last second, in ms:
	// how long runnable goroutines wait for a CPU.
	SchedP99 = Measure{Name: "sched.p99", Unit: "ms", Resource: CPU, Read: func(in *Instance) float64 { return msf(in.Runtime(time.Second).SchedP99) }, /* contains filtered or unexported fields */}
	// GCCPU is the share of CPU spent on garbage collection over the last 10 seconds, 0 to 1.
	GCCPU = Measure{Name: "gc.cpu", Resource: CPU, Read: func(in *Instance) float64 { return in.Runtime(10 * time.Second).GCCPU }, /* contains filtered or unexported fields */}
	// CPUThrottled is the share of scheduling periods in which the container hit its CPU limit, over the last 10 seconds.
	CPUThrottled = Measure{Name: "cpu.throttled", Resource: CPU, Read: func(in *Instance) float64 { return in.Runtime(10 * time.Second).Throttled }, /* contains filtered or unexported fields */}
	// CPUUsed is the CPU the process used over the last 10 seconds, in cores.
	CPUUsed = Measure{Name: "cpu.used", Unit: "cores", Resource: CPU, Read: func(in *Instance) float64 { return in.Runtime(10 * time.Second).CPUUsed }, /* contains filtered or unexported fields */}
	// Goroutines is how many goroutines are alive now.
	Goroutines = Measure{Name: "goroutines", Read: func(in *Instance) float64 { return float64(in.Runtime(time.Second).Goroutines) }, /* contains filtered or unexported fields */}
)

Ready-made measures from vis's own signals.

View Source
var ErrStarted = errors.New("vis: Start already ran: the default instance starts once per process")

ErrStarted is returned by a second call to Start.

View Source
var ProfileKinds = []string{"cpu", "goroutine", "goroutineleak", "heap", "mutex", "block"}

ProfileKinds are what Profile can take.

Functions

func DeclareDuration

func DeclareDuration(k *Duration, name string, opts ...Option)

DeclareDuration declares *k, a Duration knob variable. See DeclareInt.

func DeclareGauge

func DeclareGauge(g *Gauge, name string, opts ...Option)

DeclareGauge declares *g, a gauge variable the app declared without a value. It is what vis gen writes for a // vis:signal directive; by hand, NewGauge reads better.

func DeclareInt

func DeclareInt(k *Int, name string, opts ...Option)

DeclareInt declares *k, a knob variable the app declared without a value. It is what vis gen writes for a // vis:knob directive; by hand, NewInt reads better.

func DeclareLatency

func DeclareLatency(l *Latency, name string, opts ...Option)

DeclareLatency declares *l, a latency gauge variable. See DeclareGauge.

func DeclareLogLevel

func DeclareLogLevel(k *LogLevel, name string, opts ...Option)

DeclareLogLevel declares *k, a LogLevel knob variable. See DeclareInt.

func HTTP

func HTTP(h http.Handler, opts ...HTTPOption) http.Handler

HTTP wraps h with the default instance. See Instance.HTTP.

func ParseTokens

func ParseTokens(s string) (map[string]Grant, error)

ParseTokens reads grants from configuration such as an environment variable: "token=kind:id[:act],…", for example "s3cret=agent:oncall:act,view=agent:dash".

func Probe

func Probe(ctx context.Context, name string) (done func())

Probe times part of a request, from the call until done:

defer vis.Probe(ctx, "origin")()

For each route vis then reports how long each probe takes, and groups the requests by the probes they ran, so a cache hit and a miss (requests that ran "lookup", and those that ran "lookup" then "origin") show as two latencies with no other declaration. A probe run more than once in a request counts its total time. Name probes with constants: each route keeps 15 and counts the rest as "other". With defer the probe runs until the function returns; for part of a function, call done where that part ends. Outside a request served by Instance.HTTP (or a framework adapter) a probe does nothing, so library code can always call it.

func Start

func Start(ctx context.Context, opts ...StartOption) error

Start sets up the default instance with opts and serves it until ctx ends: the control UI on localhost:7071 and MCP on localhost:7070, unless options or the environment say otherwise (see Instance.Serve), and runs the rules declared with NewRule. It returns once both are listening, so a bad address fails here. Call it once, in main, before serving requests; a second call returns ErrStarted.

func Stop

func Stop()

Stop ends what Start started and tells the fleet this instance is leaving, returning once it has. Defer it in main after Start. See Instance.Stop.

func UnwrappedReads

func UnwrappedReads() map[string]uint64

UnwrappedReads counts, per knob, the reads From made outside a request vis served, since the process started.

func WithSnapshot

func WithSnapshot(ctx context.Context, c *Config) context.Context

WithSnapshot puts a snapshot in ctx, for code that starts work outside a request, such as a background worker that wants one consistent view.

Types

type Action

type Action interface {
	// contains filtered or unexported methods
}

Action is what a rule does instead of a fixed Step: StepPercent moves its knob by a share of its value, SetTo puts it at one value, Reset ends what rules set on it.

func Reset

func Reset() Action

Reset is a rule's action that ends the value rules hold on its knob, so it falls back to the value below them: one rule can undo another's.

func SetTo

func SetTo[T ~int | ~int64](v T) Action

SetTo is a rule's action that puts its knob at v: an integer for an Int knob, a time.Duration for a Duration knob, inside its range.

func StepPercent

func StepPercent(p float64) Action

StepPercent is a rule's action that moves its knob by p percent of its current value each time: StepPercent(-25) takes a batch of 64 to 48, then 36, 27 and 20. Sizes, counts and concurrency respond to ratios, so a percent step is as gentle near the bottom of the range as at the top, where a fixed step of -16 takes 16 to 1. An Int knob moves by at least one.

type Breakdown

type Breakdown struct {
	Route  string
	Probes []ProbeStats // in the order they first ran
	Paths  []PathStats  // the most requests first
}

Breakdown is where a route's requests spend their time, over a window.

type Bucket

type Bucket struct {
	Start         time.Time
	Requests      int64
	Errors        int64
	Refused       int64
	P50, P95, P99 time.Duration
}

Bucket is one 10-second slice of a route's history.

type Change

type Change struct {
	Knob   string
	Value  int64
	For    time.Duration // the lease; required for automated writers, optional for people
	By     Writer        // decides the layer: people pin, agents write the agent layer, and so on
	Reason string
}

Change writes one value into one knob. Set applies it as a one-entry Tx.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config is one immutable snapshot of every knob's effective value. Taking a snapshot is one atomic load, and reading a knob is a slice index, so a handler that takes one at request start sees consistent values throughout.

func SnapshotFrom

func SnapshotFrom(ctx context.Context) (*Config, bool)

SnapshotFrom returns the snapshot a request carries.

type Confounder

type Confounder struct {
	What  string `json:"what"`
	Kind  string `json:"kind"`            // change, environment, freeze
	Layer string `json:"layer,omitempty"` // a change's layer: rule for what a rule did, its lease ending included
}

Confounder is something else that changed around a change.

type Cost

type Cost interface {
	// contains filtered or unexported methods
}

Cost is what Uses and Saves take: CPU, Memory, or a gauge.

type DeclaredRule

type DeclaredRule struct {
	// contains filtered or unexported fields
}

DeclaredRule is a rule declared with NewRule.

func NewRule

func NewRule(r RuleSpec) *DeclaredRule

NewRule declares a rule at package level, next to the knob it moves. It is checked now, and panics saying what to fix: a knob that doesn't let rules change it, a threshold in the wrong unit for what it watches, no step or lease. vis.Start runs it on the default instance; RunRules runs every declared rule on another one.

func (*DeclaredRule) Name

func (r *DeclaredRule) Name() string

Name is the rule's name.

type Difference

type Difference struct {
	What   string            // cpu_limit, build, or a knob's name
	Values map[string]string // by member name, as people read them
	SetBy  map[string]string // a knob's: who set it, where it isn't at its default
}

Difference is something not the same on every member that answered: its CPU limit, its build, or a knob's value.

type Duration

type Duration struct {
	// contains filtered or unexported fields
}

Duration is a bounded time.Duration knob.

func NewDuration

func NewDuration(name string, opts ...Option) Duration

NewDuration declares a duration knob. It panics on an invalid declaration.

func (Duration) Bind

func (k Duration) Bind(fn func(d time.Duration))

Bind keeps state built from the knob in step with it. See Int.Bind.

func (Duration) BindIn

func (k Duration) BindIn(in *Instance, fn func(d time.Duration))

BindIn is Bind on a given instance.

func (Duration) From

func (k Duration) From(ctx context.Context) time.Duration

From reads the knob from the snapshot the request carries. See Int.From.

func (Duration) Get

func (k Duration) Get(c *Config) time.Duration

Get reads the knob from a snapshot.

func (Duration) Name

func (k Duration) Name() string

Name is the knob's name, as agents and the manifest see it.

func (Duration) Now

func (k Duration) Now() time.Duration

Now is the knob's value in the default instance right now. See Int.Now.

func (Duration) Range

func (k Duration) Range() (lo, hi time.Duration)

Range is the knob's declared range.

func (Duration) SetDefault

func (k Duration) SetDefault(v time.Duration) error

SetDefault replaces the knob's declared default. See Int.SetDefault.

type Effect

type Effect struct {
	Knob   string
	Value  int64
	Layer  Layer
	Change uint64
	Lease  uint64
}

Effect is what is in effect for one knob after a change. It may differ from what was asked for, for example when a higher layer still holds the knob.

type Entry

type Entry struct {
	Layer  Layer
	Value  int64
	By     Writer
	Change uint64        // the change that wrote it
	Lease  uint64        // the lease group it belongs to; 0 means no expiry
	Left   time.Duration // time until the lease ends; 0 means no expiry
	Then   int64         // what the knob falls back to when this layer ends
	Kept   bool          // its lease is kept across a restart (Tx.Keep)
}

Entry is one layer of a knob's stack.

type Event

type Event struct {
	At     time.Time
	Kind   string         // change, rule, freeze, unfreeze, environment, onchange_panic
	Fields map[string]any // the record's attributes: knob, actor, old, new, reason, …
}

Event is one audit record: a knob change, a rule's state change, a freeze, or a change vis noticed in its environment, such as the container's CPU limit.

type FleetMember

type FleetMember struct {
	Member
	Frozen    bool
	CPUUsed   float64 // cores, over the last 20 s
	CPULimit  float64
	Throttled float64
	SLOs      []MemberSLO
	// Gossiped is how old its numbers are when it didn't answer and they come
	// from its last gossip; zero when it answered.
	Gossiped time.Duration
	// Silent is a member with no numbers to show: not heard from, refusing
	// connections, or alive with no gossip yet. It is unaccounted for, never
	// taken as healthy; SilentWhy says which.
	Silent    bool
	SilentWhy string
	Held      []Held        // values above its defaults, with who set them and when they end
	Restarts  int           // under its name, in the last 10 minutes
	Restarted time.Duration // since the last of them
	Lost      []Held        // what the last restart dropped and it doesn't hold again
	Died      string        // what most likely killed it the last time it restarted; "" if it stopped cleanly
	// Its container's memory, when it says: bytes used and the limit (0 when
	// unlimited), and how soon its forecast reaches the limit (0: it isn't heading there).
	MemUsed, MemLimit uint64
	MemKill           time.Duration
	Pressures         []Pressure // what it is short of, with the knobs that spend it
	// LastChange is its newest knob change by a person or an agent, LastAgo
	// how long ago: where a lapsed fix or a harmful change starts.
	LastChange string
	LastAgo    time.Duration
}

FleetMember is one member's side of the comparison.

type FleetReport

type FleetReport struct {
	Members  []FleetMember
	SLOs     []FleetSLO   // each objective across the fleet, from merged histograms
	StandOut []StandOut   // members that differ from the rest in a way that matters
	Differ   []Difference // what isn't the same on every member: its CPU limit, its build, its knobs
	Covers   string       // "3 of 3 members": a partial answer says so
	Missing  []string     // members that didn't answer, and why
	Common   []string     // what every member shares: a pressure, an environment change, a value held
	At       time.Time    // when it was asked
}

FleetReport compares the members of the fleet, as one instance sees them.

type FleetSLO

type FleetSLO struct {
	Route     string
	Objective time.Duration
	P99       time.Duration
	Requests  int64
	Met       bool
	Partial   string // members whose requests aren't in P99, and what their gossip says
}

FleetSLO is one objective across every member that answered.

type FreezeState

type FreezeState struct {
	Frozen bool
	By     Writer
	Reason string
	Since  time.Time
	Epoch  uint64 // rises with every freeze and unfreeze; across a fleet the highest wins
	On     string // the member it was set on, by name; a freeze reaches the whole fleet
	// contains filtered or unexported fields
}

FreezeState says whether automated changes are frozen, and who changed that, when and why.

type Gauge

type Gauge struct {
	// contains filtered or unexported fields
}

A gauge is a number only the service knows, such as the share of requests served from its cache, published to people, agents and rules next to vis's own measurements. Declare it like a knob, at package level, and Set it wherever the app computes the value. Its value belongs to the process, so every instance publishes it.

func NewGauge

func NewGauge(name string, opts ...Option) *Gauge

NewGauge declares a gauge. Unit and About describe it; options that bound a knob panic. It panics on a duplicate name, like a knob.

func (*Gauge) Measure

func (g *Gauge) Measure() Measure

Measure lets a rule watch the gauge.

func (*Gauge) Name

func (g *Gauge) Name() string

Name is the gauge's name, as people, agents and rules see it.

func (*Gauge) Set

func (g *Gauge) Set(v float64)

Set publishes v as the gauge's value, until the next Set.

type GaugeFunc

type GaugeFunc struct {
	// contains filtered or unexported fields
}

GaugeFunc is a gauge computed each time it is read.

func NewGaugeFunc

func NewGaugeFunc(name string, read func() float64, opts ...Option) *GaugeFunc

NewGaugeFunc declares a gauge whose value is computed each time someone reads it, for values that are cheap to compute and always current. Keep read cheap: the UI, agents and rules call it.

func (*GaugeFunc) Measure

func (g *GaugeFunc) Measure() Measure

Measure lets a rule watch the gauge.

func (*GaugeFunc) Name

func (g *GaugeFunc) Name() string

Name is the gauge's name.

type Grant

type Grant struct {
	Writer Writer
	Act    bool
}

Grant is what a bearer token gives its holder: who they write as, and whether they may act or only read. The writer comes from the token, never from a tool's input, so an agent can't claim to be a person.

type HTTPOption

type HTTPOption func(*httpOptions)

HTTPOption configures Instance.HTTP.

func RouteName

func RouteName(fn func(*http.Request) string) HTTPOption

RouteName names a request's route for routers that don't fill in http.Request.Pattern, for example chi's RouteContext(r.Context()).RoutePattern(). It runs after the handler, when routing is done.

type Held

type Held struct {
	Knob   string        `json:"knob"`
	Value  string        `json:"value"`
	By     string        `json:"by"`
	EndsIn time.Duration `json:"ends_in"`
	// For a kept value: whether a restart set it back, and how long it has
	// been in effect since it was written: what the breaker reads (keepHolds).
	Back bool          `json:"back,omitempty"`
	Age  time.Duration `json:"age,omitempty"`
	// Unkept is a dropped kept value that vis stopped setting back: the
	// process it was set back on died within keepHolds, so it may be what kills it.
	Unkept bool `json:"unkept,omitempty"`
}

Held is a value a member holds above its default: who set it, and when it ends (0: it doesn't). A restart drops it: values set at runtime live in the process.

type Impact

type Impact struct {
	Change     uint64             `json:"change"`
	At         time.Time          `json:"at"`
	Settle     time.Duration      `json:"-"`
	MeasuredAt time.Time          `json:"measured_at"` // At plus the settle time
	Done       bool               `json:"done"`
	Changes    []string           `json:"changes"` // "compress_level 9 → 6"
	Before     map[string]float64 `json:"before"`
	After      map[string]float64 `json:"after,omitempty"`
	Confounded []string           `json:"confounded,omitempty"`
	Effects    []Moved            `json:"effects,omitempty"` // what moved, as numbers; Summary says it in a sentence
	Summary    string             `json:"summary"`
	Rest       *Rest              `json:"rest,omitempty"` // in a fleet: the other members over the same windows
	// ConfoundedBy is Confounded with who and where: a member's own rules
	// reacting in the window read differently from a person changing something.
	ConfoundedBy []Confounder `json:"confounded_by,omitempty"`
	// Warming is a change made in the instance's first minute, while its
	// caches and connections still fill: its before window says little.
	Warming bool `json:"warming,omitempty"`
	// Memory is the memory outlook after the change: when the container
	// reaches its limit at the rate since, or that it doesn't within the hour.
	Memory string `json:"memory,omitempty"`
	// contains filtered or unexported fields
}

Impact is what a change did, measured by vis with nothing declared beyond the SLOs: the SLO routes' p99 (the busiest routes' without an SLO), CPU, throttling and every published signal, over the 20 seconds before the change and the 20 seconds ending once it settled. No significance is claimed: one instance, one window. Other changes or environment events inside the window are named in Confounded.

type Info

type Info struct {
	Name    string
	Type    string // "int", "duration" or "level"
	Unit    string
	About   string     // what it does and what turning it costs
	Uses    []Resource // what turning it up uses more of
	Saves   []Resource // what turning it up saves
	Min     int64
	Max     int64
	Default int64
	Pull    []Kind // automated writers that may change it; people always may
	Env     string // the environment variable that may set Default (vis.Env)
	FromEnv bool   // it did
	// The value outside the range the service gives its own meaning, when it
	// declares one (vis.Special): Special is the value, SpecialName what it means.
	HasSpecial  bool
	Special     int64
	SpecialName string
	// contains filtered or unexported fields
}

Info describes a declared knob: what the manifest, the admin UI and MCP show.

func Knobs

func Knobs() []Info

Knobs lists every declared knob, in declaration order.

func Lookup

func Lookup(name string) (Info, bool)

Lookup describes one knob by name.

func (Info) Format

func (i Info) Format(v int64) string

Format writes a value in the knob's own terms: "1m30s" for a duration, "WARN" for a level, "2000" for an int.

func (Info) Parse

func (i Info) Parse(s string) (int64, error)

Parse reads a value in the knob's own terms. A duration needs its unit, so "1500" is an error rather than 1.5 microseconds. The special value is read by its name ("no limit"). Parse doesn't check the range; Apply does.

type Instance

type Instance struct {
	// contains filtered or unexported fields
}

Instance holds knob values. Declarations are shared by the whole process; values are per instance, so tests that each start their own can run in parallel.

func DefaultInstance

func DefaultInstance() *Instance

DefaultInstance returns the process's default instance, creating it on first use.

func NewInstance

func NewInstance(opts ...InstanceOption) *Instance

NewInstance starts an instance with every declared knob at its default.

func (*Instance) Apply

func (in *Instance) Apply(tx Tx) (Record, error)

Apply validates every part of tx before touching anything, then applies it in one step: one published snapshot, one change ID, one lease.

func (*Instance) Breakdown

func (in *Instance) Breakdown(route string, window time.Duration) Breakdown

Breakdown says where a route's requests spent their time over the last window, up to 5 minutes, from the probes they ran.

func (*Instance) Clear

func (in *Instance) Clear(knob string, l Layer, by Writer, reason string) (Effect, error)

Clear removes one layer from a knob and returns what is in effect afterwards.

func (*Instance) Fleet

func (in *Instance) Fleet(ctx context.Context) FleetReport

Fleet asks every member for its side and compares them. A member that doesn't answer within the fleet wait is shown, and merged, from what its gossip last carried; a member not heard from at all is listed as such, and the fleet's objective can't read as met while one is unaccounted for: silence is a finding, never absence.

func (*Instance) Forget

func (in *Instance) Forget(by Writer, name, reason string) error

Forget drops a member that is gone for good (scaled down, or replaced under a new name, as a Kubernetes pod is) from the whole fleet, so it stops reading as unaccounted for. Only a person may, and only a member that is dead (not heard from for 15 s). If it was only cut off, its own gossip brings it back once it is heard from again.

func (*Instance) Freeze

func (in *Instance) Freeze(by Writer, reason string) error

Freeze stops automated changes (fleet, agent and rule layers) and holds every knob where it is: no layer is masked, and every lease clock stops, a pin's expiry included. A person can still pin or clear any knob. Any writer may freeze. Freezing an already frozen instance keeps the first freeze but raises its epoch: in a fleet, an unfreeze set elsewhere a moment earlier, not yet heard here, mustn't lift a freeze made after it.

func (*Instance) FreezeState

func (in *Instance) FreezeState() FreezeState

FreezeState reports whether automated changes are frozen, and who changed that, when and why.

func (*Instance) HTTP

func (in *Instance) HTTP(h http.Handler, opts ...HTTPOption) http.Handler

HTTP wraps h so every request carries one snapshot of the knobs in its context, read with Int.From and Duration.From, and is timed per route. Routes are named by http.ServeMux patterns by default ("GET /k/{key}"), so it works with the standard library and any router built on net/http.

func (*Instance) History

func (in *Instance) History(n int) []Event

History returns the newest n events, oldest first.

func (*Instance) Impact

func (in *Instance) Impact(change uint64) (Impact, bool)

Impact returns the report for a change: pending until it has settled.

func (*Instance) Levers

func (in *Instance) Levers(r Resource) []Lever

Levers lists the knobs whose setting costs r, the most expensive setting first.

func (*Instance) MCP

func (in *Instance) MCP(opts ...MCPOption) http.Handler

MCP serves the instance's tools over MCP's streamable HTTP transport, stateless, so any instance can answer and no load balancer needs sticky sessions.

func (*Instance) Members

func (in *Instance) Members() []Member

Members lists the instances of the service this one knows, itself first, then by name. Without peers it is the only one.

func (*Instance) Pressures

func (in *Instance) Pressures() []Pressure

Pressures lists the resources running short over the last 10 seconds: CPU when the container is throttled or goroutines wait long for a CPU, memory when the container nears its memory limit or the heap nears GOMEMLIMIT. Each comes with the knobs that spend it.

func (*Instance) Preview

func (in *Instance) Preview(tx Tx) (Record, error)

Preview runs every check Apply would and reports what would be in effect afterwards, without changing anything: the plan a person or an agent reads before deciding. The record has no change or lease ID.

func (*Instance) Profile

func (in *Instance) Profile(ctx context.Context, kind string, d time.Duration) (ProfileReport, error)

Profile takes one profile and reads it. cpu, mutex and block sample for d (10 s when zero, 30 s at most); goroutine, goroutineleak and heap are taken at once. Mutex and block profiling are switched on only while sampling, so block counts the waits that started in the window; the mutex fraction is restored afterwards, and the block rate (which can't be read back) is left at 0. One profile runs at a time in the process.

func (*Instance) Revert

func (in *Instance) Revert(leaseID uint64, by Writer, reason string) (Record, error)

Revert ends a lease group early, as if it had expired: every value it still holds drops to the layer below. It is gated like any change to those knobs.

func (*Instance) Route

func (in *Instance) Route(route string, window time.Duration) RouteStats

Route summarizes one route over the last window, up to 5 minutes.

func (*Instance) RouteHistory

func (in *Instance) RouteHistory(route string) []Bucket

RouteHistory is a route's last hour in 10-second buckets, oldest first.

func (*Instance) Routes

func (in *Instance) Routes(window time.Duration) []RouteStats

Routes summarizes every route seen in the last window.

func (*Instance) Rules

func (in *Instance) Rules() []RuleState

Rules reports every running rule's state.

func (*Instance) RunRule

func (in *Instance) RunRule(ctx context.Context, r RuleSpec)

RunRule runs one rule on this instance, checking it every r.Every until ctx is done. A rule declared with NewRule needs none of this: vis.Start, or RunRules on another instance, runs it. RunRule is for a rule built at run time, as tests do; it doesn't check the spec the way NewRule does.

func (*Instance) RunRules

func (in *Instance) RunRules(ctx context.Context)

RunRules runs every declared rule on in until ctx ends, each on its own goroutine. It starts them once per instance, however often it's called.

func (*Instance) Runtime

func (in *Instance) Runtime(window time.Duration) RuntimeStats

Runtime reads the runtime's counters now and summarizes the last window.

func (*Instance) SLOs

func (in *Instance) SLOs() []SLOStatus

SLOs reports each declared objective, in declaration order, against the last 20 seconds, so it reads as met soon after a recovery, with the last minute alongside.

func (*Instance) Serve

func (in *Instance) Serve(ctx context.Context, opts ...ServeOption) (Served, error)

func (*Instance) Service

func (in *Instance) Service() string

Service is the service's name.

func (*Instance) Set

func (in *Instance) Set(c Change) (Effect, error)

Set writes one value and returns what is in effect afterwards.

func (*Instance) SetRule

func (in *Instance) SetRule(name string, enabled bool, by Writer, reason string) error

SetRule switches a running rule off or on. Disabling it also ends its lease, so its knob falls back now instead of keeping the rule's last value. People and agents may do this, with a reason; during a freeze only a person may, since ending the lease is a change.

func (*Instance) Signal

func (in *Instance) Signal(name, unit, about string, read func() float64) Measure

Signal publishes a value this instance computes when asked, for signals that appear while the service runs, such as one per tenant as tenants show up. A signal known when the code is written is a gauge: declare it at package level with NewGauge, NewLatency or NewGaugeFunc instead. read is called whenever someone asks, so keep it cheap. It returns the signal as a Measure, so a rule can watch it.

func (*Instance) Signals

func (in *Instance) Signals() []SignalValue

Signals reads every published signal: the declared gauges, then those this instance publishes with Signal, each in the order they were declared.

func (*Instance) Snapshot

func (in *Instance) Snapshot() *Config

Snapshot returns the current values. It never blocks.

func (*Instance) Stack

func (in *Instance) Stack(knob string) ([]Entry, error)

Stack returns a knob's layers, top first, so a caller can see why it has its value.

func (*Instance) StartRequest

func (in *Instance) StartRequest(ctx context.Context) (context.Context, func(route string, status int))

StartRequest is what framework adapters build on: it puts a snapshot in ctx and returns a function to call when the request is done, with the route and the status. Instance.HTTP is StartRequest plus a ResponseWriter that records the status.

func (*Instance) Stop

func (in *Instance) Stop()

Stop ends what Serve started, if its context hasn't ended already: it tells the fleet this member is leaving, closes MCP and the UI, and returns once the fleet has been told (or after a few seconds if it can't be). Defer it in main after Start: a process that exits as its context ends would otherwise be gone before vis could say so, and the fleet would take a clean stop for a crash. Calling it again does nothing.

func (*Instance) Stories

func (in *Instance) Stories(n int, viewer Writer) []Story

Stories tells the recent history, newest first, as viewer reads it: their own actions are "you". Times are relative to now, so a story is as true when read as when it was written.

func (*Instance) UI

func (in *Instance) UI(opts ...UIOption) http.Handler

UI serves the control UI and its JSON API. Keep it on localhost (reach it through a port-forward): it acts as one person, without other auth.

The API, version 1, snake_case throughout:

GET  /api/state      everything the page shows: service, started, slos, routes (with 10-second history), runtime,
                     signals, knobs (with stacks), rules, freeze, stories, and the raw history
GET  /api/events     the same as a stream (text/event-stream): a whole "state" event on connect, then
                     one as soon as the history records something and every 2 s, each carrying only
                     the newest two buckets of a route's history (replace buckets by their start)
POST /api/preview    {set, for, keep, reason}: what a change would do, changing nothing
POST /api/apply      {set, for, keep, reason}: the change, as UIUser's pin; returns change, lease and effects
POST /api/clear      {knob, reason}: remove UIUser's pin
POST /api/revert     {lease, reason}: end a lease early
POST /api/rule       {rule, enabled, reason}: switch a rule off or on
POST /api/freeze     {reason}, POST /api/unfreeze {reason}
POST /api/forget     {member, reason}: drop a member gone for good from the fleet

Scripts may read it too, from localhost: it's the same contract the page uses.

func (*Instance) Unfreeze

func (in *Instance) Unfreeze(by Writer, reason string) error

Unfreeze resumes automated changes. Each lease picks up with the time it had left. Only a person may unfreeze; an agent that could would make the freeze meaningless.

func (*Instance) WaitImpact

func (in *Instance) WaitImpact(ctx context.Context, change uint64) (Impact, error)

WaitImpact returns a change's report once it has been measured, which is the settle time after the change. If ctx ends first it returns the pending report with ctx's error.

func (*Instance) Warnings

func (in *Instance) Warnings() []string

Warnings are reasons to doubt the service is set up right, each saying how to fix it: knobs read outside requests vis served, and objectives whose routes never serve.

type InstanceOption

type InstanceOption func(*Instance)

InstanceOption configures an Instance.

func InstanceName

func InstanceName(name string) InstanceOption

InstanceName names the instance in its fleet: stable across restarts, unlike its ID. It defaults to VIS_INSTANCE_NAME, then the hostname.

func SLO

func SLO(route string, p99 time.Duration) InstanceOption

SLO gives one instance a route's latency objective, p99 at or under the target. To declare an objective for the service, use NewSLO beside the handler instead.

func Service

func Service(name string) InstanceOption

Service names the service this instance belongs to, as the UI's header, MCP's describe and every story show it.

func WithLogger

func WithLogger(l *slog.Logger) InstanceOption

WithLogger sends audit records to l instead of slog.Default.

type Int

type Int struct {
	// contains filtered or unexported fields
}

Int is a bounded integer knob.

func NewInt

func NewInt(name string, opts ...Option) Int

NewInt declares an integer knob. It panics on an invalid declaration, since declarations are reviewed code, not runtime input.

func (Int) Bind

func (k Int) Bind(fn func(n int))

Bind keeps state built from the knob in step with it, in the default instance, such as a cache sized by it: fn runs with the current value before Bind returns, then with every new value, in the order changes were published, possibly on another goroutine. No change can slip in between. fn may change knobs itself. A panic in fn is recovered and audited. Bind while setting up, not from inside another knob's callback: there it would wait on itself.

func (Int) BindIn

func (k Int) BindIn(in *Instance, fn func(n int))

BindIn is Bind on a given instance.

func (Int) From

func (k Int) From(ctx context.Context) int

From reads the knob from the snapshot the request carries, so a request sees one consistent set of values. Outside a request vis served, it reads the value now in the default instance, and vis reports the reads with how to fix them (Instance.Warnings, the UI, MCP, and once in the log).

func (Int) Get

func (k Int) Get(c *Config) int

Get reads the knob from a snapshot.

func (Int) Name

func (k Int) Name() string

Name is the knob's name, as agents and the manifest see it.

func (Int) Now

func (k Int) Now() int

Now is the knob's value in the default instance right now. In a request, read From instead, so the whole request sees one snapshot.

func (Int) Range

func (k Int) Range() (lo, hi int)

Range is the knob's declared range.

func (Int) SetDefault

func (k Int) SetDefault(v int) error

SetDefault replaces the knob's declared default, for a default that comes from a flag: call it after flag.Parse and before Start. A value outside the range is an error, saying the range, since a flag is user input. The default instance follows, and anything bound to the knob sees the new value; other instances created earlier keep theirs. It panics after Start. A value the knob's env= variable set wins: SetDefault then only checks v's range. Use it too for a default worked out at startup, such as one per CPU.

type Kind

type Kind int

Kind is the kind of writer behind a change. The core derives the layer from it, so no caller can claim a layer it doesn't own.

const (
	Human Kind = iota + 1 // a person, in the UI or over MCP; writes the pin layer
	Agent                 // an agent through vis.set_knob or an approved proposal
	Rule                  // a compiled-in rule
	Fleet                 // a staged rollout
)

func (Kind) String

func (k Kind) String() string

type Knob

type Knob interface {
	// contains filtered or unexported methods
}

Knob is any declared knob: Int, Duration. A rule takes the knob itself, not its name, so a typo is a compile error.

type Latency

type Latency struct {
	// contains filtered or unexported fields
}

Latency is a gauge of a duration, published in milliseconds.

func NewLatency

func NewLatency(name string, opts ...Option) *Latency

NewLatency declares a latency gauge. See NewGauge.

func (*Latency) Measure

func (l *Latency) Measure() Measure

Measure lets a rule watch the latency, in milliseconds.

func (*Latency) Name

func (l *Latency) Name() string

Name is the latency's name.

func (*Latency) Set

func (l *Latency) Set(d time.Duration)

Set publishes d as the latency's value, until the next Set.

type Layer

type Layer int

Layer is one writer's slot in a knob's stack. The effective value is the highest layer that hasn't expired: Default < Fleet < Agent < Rule < Pin.

const (
	DefaultLayer Layer = iota // the reviewed baseline, set in code
	FleetLayer                // a staged rollout
	AgentLayer                // vis.set_knob or an approved proposal
	RuleLayer                 // a compiled-in rule
	PinLayer                  // a person; overrides everything until it expires or is removed

)

func (Layer) String

func (l Layer) String() string

type Level

type Level interface {
	// contains filtered or unexported methods
}

Level is a rule's threshold or dead band: a fixed amount (Fixed), or a knob people can tune, read on every check. A latency, a time.Duration or a Duration knob, goes with a measure in milliseconds, such as SchedP99 or a route's p99; a plain number goes with a gauge or a ratio.

func Fixed

func Fixed[T time.Duration | float64 | int](v T) Level

Fixed is a level that never changes: vis.Fixed(400*time.Millisecond) for a latency, vis.Fixed(0.9) for a ratio.

type Lever

type Lever struct {
	Knob     string  `json:"knob"`
	Value    string  `json:"value"`    // as people read it, with its unit
	Position float64 `json:"position"` // 0 the cheapest setting, 1 the most expensive
	About    string  `json:"about,omitempty"`
	Observed string  `json:"observed,omitempty"`    // what turning it did before, measured: "last time 9 → 6: GET /k p99 -97%"
	People   bool    `json:"people_only,omitempty"` // agents may not pull it (Pull doesn't list them): an agent can only ask a person to
}

Lever is a knob that spends a resource, and how expensive its current setting is.

type LogLevel

type LogLevel struct {
	// contains filtered or unexported fields
}

LogLevel is a log level knob, so a service can log more while someone looks into it and less again after. It is a slog.Leveler, reading the default instance, so a handler takes it as its level directly:

slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: LogLevel}))

People and agents see and set it by name: DEBUG, INFO, WARN, ERROR.

func NewLogLevel

func NewLogLevel(name string, opts ...Option) LogLevel

NewLogLevel declares a log level knob. Without Range it runs from slog.LevelDebug to slog.LevelError, and without Default it starts at slog.LevelInfo; both take slog.Level values. It panics on an invalid declaration.

func (LogLevel) Bind

func (k LogLevel) Bind(fn func(l slog.Level))

Bind keeps state built from the knob in step with it. See Int.Bind. A handler needs no Bind: give it the knob as its Level.

func (LogLevel) BindIn

func (k LogLevel) BindIn(in *Instance, fn func(l slog.Level))

BindIn is Bind on a given instance.

func (LogLevel) Get

func (k LogLevel) Get(c *Config) slog.Level

Get reads the knob from a snapshot.

func (LogLevel) Level

func (k LogLevel) Level() slog.Level

Level is the knob's value in the default instance, which makes the knob a slog.Leveler. It costs one atomic load, so a handler can ask on every record.

func (LogLevel) Name

func (k LogLevel) Name() string

Name is the knob's name, as agents and the manifest see it.

func (LogLevel) Now

func (k LogLevel) Now() slog.Level

Now is the knob's value in the default instance right now. See Int.Now.

func (LogLevel) Range

func (k LogLevel) Range() (lo, hi slog.Level)

Range is the knob's declared range.

func (LogLevel) SetDefault

func (k LogLevel) SetDefault(v slog.Level) error

SetDefault replaces the knob's declared default. See Int.SetDefault.

type MCPOption

type MCPOption func(*mcpOptions)

MCPOption configures Instance.MCP.

func Tokens

func Tokens(t map[string]Grant) MCPOption

Tokens configures static bearer tokens. Without tokens an instance serves the read tools only; with them, every request needs a valid token. (OAuth, as the MCP authorization spec describes, comes later.)

type Measure

type Measure struct {
	Name     string   // as people and agents read it: "sched.p99"
	Unit     string   // "ms"
	Resource Resource // what it measures the shortage of, if anything: CPU for scheduler latency
	Read     func(*Instance) float64
	// contains filtered or unexported fields
}

Measure is a value a rule can watch: what it is, its unit, and how to read it.

func RouteP99

func RouteP99(route string) Measure

RouteP99 is a route's request p99 over the last minute, in ms, measured inside the service. A rule judging its step counts only the requests served since the step.

type Member

type Member struct {
	ID      string // this process's, new at every start
	Name    string // stable across restarts: VIS_INSTANCE_NAME, or the hostname
	Addr    string // where its peers reach it
	Service string
	Build   string
	State   string        // alive, suspect (quiet for 5 s) or dead (15 s), listed for 10 minutes unless it left cleanly
	Quiet   time.Duration // since its heartbeat last rose
	Self    bool
	// contains filtered or unexported fields
}

Member is one instance of the service, as this instance sees it.

type MemberSLO

type MemberSLO struct {
	Route    string        `json:"route"`
	P99      time.Duration `json:"p99"`
	Requests int64         `json:"requests"`
	Met      bool          `json:"met"`
}

MemberSLO is one objective on one member, over the last 20 s.

type Moved

type Moved struct {
	Name  string  `json:"name"` // "GET /k p99", "CPU", "throttled", "sched.p99"
	From  float64 `json:"from"`
	To    float64 `json:"to"`
	Unit  string  `json:"unit"` // "ms", "cores", "%"
	Worse bool    `json:"worse"`
}

Moved is one thing a change moved, measured before and after. Every effect vis reports is better lower (latency, CPU, throttling), so Worse is whether it went up.

func (Moved) String

func (e Moved) String() string

String says it as the summaries do: "GET /k p99 243 → 61 ms", "throttled 10% → 40%".

type Objective

type Objective struct {
	// contains filtered or unexported fields
}

Objective is a route's declared SLO.

func NewSLO

func NewSLO(route string, t Target) Objective

NewSLO declares a route's objective, at package level beside the handler that serves it: vis.NewSLO("GET /k/{key}", vis.P99(50*time.Millisecond)). The route is named as http.ServeMux registered it (or as RouteName names it). The UI's headline, agents, impact reports and rules judge the service by it; the first one declared is the service's main objective. Every instance has it.

func (Objective) P99

func (o Objective) P99() time.Duration

P99 is the objective's p99 target.

func (Objective) Route

func (o Objective) Route() string

Route is the route the objective judges.

type Option

type Option func(*decl)

Option configures a knob declaration.

func About

func About(s string) Option

About says what the knob does and what turning it costs, for the people and agents deciding whether to: "Compression level. 9 costs about 7x the CPU of 6."

func Default

func Default[T ~int | ~int64](v T) Option

Default is the knob's reviewed baseline value. Its type must match the knob's.

func Env

func Env(key string) Option

Env takes the knob's default from the environment variable key when it is set: a whole number for an Int knob, a duration such as 300ms for a Duration knob, a level such as debug for a LogLevel knob. A value that doesn't parse or is outside the range keeps the code's Default, and the instance's Warnings say why. A service configured by environment variables keeps them working this way, with vis's range around them.

func Pull

func Pull(kinds ...Kind) Option

Pull lists the automated writers that may change the knob directly. People may always change any knob; a knob without Pull is theirs alone.

func Range

func Range[T ~int | ~int64](min, max T) Option

Range bounds a numeric knob. Every runtime value must fall inside it. Its type must match the knob's: durations for a Duration knob, so a bare 10 can't silently mean 10 nanoseconds.

func Saves

func Saves(cs ...Cost) Option

Saves says that turning the knob up saves each cost, so turning it down spends more: a bigger cache saves origin fetches, a higher log level saves the CPU that logging takes.

func Special

func Special[T ~int | ~int64](v T, name string) Option

Special is one value outside the range that the service gives its own meaning, named for people and agents: Special(time.Duration(0), "no limit") for a time limit where 0 means none, Special(0, "unlimited") for a pool size. The code reads it as the value it is, so `if timeout > 0` keeps working. vis never calculates with it: people and agents choose it by its name, a default, a flag (SetDefault) or Env may start the knob at it, and a rule never steps into it or out of it. Its type must match the knob's.

func Unit

func Unit(u string) Option

Unit labels the knob's value for people and agents, for example "MiB".

func Uses

func Uses(cs ...Cost) Option

Uses says that turning the knob up uses more of each cost: a bigger cache uses more memory. When the service runs short of CPU or memory, the UI and agents are told which knobs use it, and how far up each one is, so whoever is on call knows what to turn down.

type PathStats

type PathStats struct {
	Probes   []string
	Requests int64
	Share    float64
	Errors   int64
	P50, P99 time.Duration
}

PathStats is the requests that ran the same probes, and their whole latency.

type Pressure

type Pressure struct {
	Resource Resource `json:"resource"`
	Why      string   `json:"why"`
	Levers   []Lever  `json:"levers"`
}

Pressure is a resource running short now, why vis thinks so, and the knobs that spend it.

type ProbeStats

type ProbeStats struct {
	Probe    string
	Requests int64
	Share    float64 // of the route's requests
	P50, P99 time.Duration
}

ProbeStats is one probe on one route: the requests that ran it and the time they spent in it.

type ProfileLine

type ProfileLine struct {
	Function string   `json:"function"`
	Where    string   `json:"where"`         // file:line in the owning function
	Via      string   `json:"via,omitempty"` // the frame under it where the cost lands, when that is runtime or library code
	Callers  []string `json:"callers,omitempty"`
	Value    float64  `json:"value"`
	Share    float64  `json:"share"`
	Events   int64    `json:"events,omitempty"` // mutex and block: how many waits
	Each     float64  `json:"each_s,omitempty"` // mutex and block: seconds per wait, on average
}

ProfileLine is one owner of the cost.

type ProfileReport

type ProfileReport struct {
	Kind    string  `json:"kind"`
	Seconds float64 `json:"seconds,omitempty" jsonschema:"how long it sampled; goroutine, goroutineleak and heap are a moment"`
	Unit    string  `json:"unit"`
	Total   float64 `json:"total"`
	// Vis is what vis's own goroutines added, left out of Total and Top: in a
	// block or goroutine profile they're parked waiting for work (a dashboard's
	// stream, a rule's next tick, an agent's next call), which costs the service nothing.
	Vis     float64       `json:"vis,omitempty"`
	Top     []ProfileLine `json:"top"`
	Summary string        `json:"summary"`
}

ProfileReport is a pprof profile read for a person or an agent: the code that owns the cost, biggest first. Owning code is the first frame outside the runtime and the sync, syscall and time packages, so a goroutine parked in a select is counted where it selects, and lock waits are charged to the code that held the lock.

type Record

type Record struct {
	Change   uint64     // shared by every audit record the Tx wrote
	Lease    uint64     // the lease group its values share; 0 means no expiry
	Effects  []Effect   // one per knob: sets, then steps, then clears, each in the Tx's order
	Replaced []Replaced // values the Tx's writes took the place of, in its own layer
}

Record is what a Tx did.

type Removal

type Removal struct {
	Knob  string
	Layer Layer
}

Removal clears one layer of one knob in a Tx. A person may clear any layer; an automated writer only its own.

type Replaced

type Replaced struct {
	Knob  string
	Value int64
	By    Writer
	Left  time.Duration
}

Replaced is a value a write took the place of in its own layer: setting a knob where the writer's layer already held one ends that one. Left is what was left of its lease; zero means it had none.

type Resource

type Resource string

Resource is something turning a knob up uses or saves: CPU or Memory, which vis measures itself, or one of the app's own gauges, whose meaning is the app's, named by the gauge.

const (
	CPU    Resource = "cpu"    // the process's CPU time, against the container's limit
	Memory Resource = "memory" // heap, against the memory limit
)

type Rest

type Rest struct {
	Members  []string           `json:"members"`
	Before   map[string]float64 `json:"before"`
	After    map[string]float64 `json:"after,omitempty"`
	Gossiped []string           `json:"gossiped,omitempty"`      // too busy to answer: taken from their gossip
	AfterOf  []string           `json:"after_members,omitempty"` // when the members that answered after differ
	Changed  []string           `json:"changed,omitempty"`       // the rest's own knob changes in the windows: "b: compress_level 9 → 1 by agent:oncall"
}

Rest is the rest of the fleet over the same windows as a change made on one member: its objectives' p99 from the other members' merged histograms. Their holding still while this member moved is what says the change did it; their moving too says something they share may have.

type RouteStats

type RouteStats struct {
	Route         string
	Requests      int64
	Errors        int64 // responses with a 5xx status, panics included
	Refused       int64 // responses with a 429: the service turned them away, fast, so they pull p99 down
	P50, P95, P99 time.Duration
}

RouteStats summarizes one route over a window.

type RuleSpec

type RuleSpec struct {
	Name     string
	Knob     Knob          // the knob it moves: the handle itself, not its name
	Watch    Measure       // what it watches, such as vis.SchedP99, vis.RouteP99(route) or a gauge's Measure()
	Over     Level         // its threshold: vis.Fixed(5*time.Millisecond), or a knob people can tune
	For      time.Duration // how long what it watches must stay over the threshold before acting
	Step     int64         // how far to move the knob per action, in the knob's own unit
	Do       Action        // instead of Step: vis.SetTo(v) puts the knob at v; vis.Reset() ends what rules set on it
	Cooldown time.Duration // the least time between actions, and how long a step gets to show its effect
	Lease    time.Duration // how long each step lasts
	Deadband Level         // the least improvement that counts as helping, in Over's unit; none by default
	Stall    int           // actions in a row that may fail to help before the rule stops; default 2
	MaxDrift int64         // total distance from the value below the rule's layer; default four steps
	Shadow   bool          // record what it would do, without doing it
	Every    time.Duration // how often to check; default 1s

	// Objective is what the rule answers to, lower being better: by default the
	// first SLO's p99. Name another for a rule that trades latency on purpose,
	// such as one that sheds load to save memory.
	Objective Measure
}

RuleSpec is a compiled-in reflex: when what it watches stays Over its threshold for For, it steps Knob by Step, at most once per Cooldown, under a lease. It carries these safety guards: a rule whose steps don't improve its signal stops (Stall), it moves the knob at most MaxDrift from the value below its layer, it can run in Shadow, and a freeze holds it.

A rule acts on its signal and answers to its Objective: a step that quiets the signal while the objective gets worse means the rule is pushing the wrong lever, so vis undoes its change and stops it until a person or an agent switches it back on. While a person's or an agent's change is being measured, rules hold off, so their steps don't confound it.

type RuleState

type RuleState struct {
	Name       string  `json:"name"`
	Knob       string  `json:"knob"`
	SignalName string  `json:"signal_name"`
	Unit       string  `json:"unit,omitempty"`
	State      string  `json:"state"`  // watching, acting, holding, stalled, stopped, at_limit, aside, overridden, frozen, shadow, disabled, error
	Stalls     int     `json:"stalls"` // actions in a row that didn't help
	Signal     float64 `json:"signal"` // the latest reading of what it watches
	Limit      float64 `json:"limit"`
	Warning    string  `json:"warning,omitempty"` // a reason to doubt the rule can help, found from its declarations
	Err        string  `json:"err,omitempty"`     // what went wrong, in the error state
	Moves      string  `json:"moves,omitempty"`   // where it may take its knob: "1..64", from the value below it and MaxDrift
	Action     string  `json:"action,omitempty"`  // what it does: "step -25%", "step -16", "set 8", "reset"
	Stopped    string  `json:"stopped,omitempty"` // why vis stopped it, until a person or an agent switches it back on
	Aside      string  `json:"aside,omitempty"`   // in the aside state, why: its knob is at its special value, which no rule moves
}

RuleState is what a rule is doing, for people, agents and the UI.

type RuntimeStats

type RuntimeStats struct {
	Over       time.Duration // the span the window actually covers; shorter until enough history exists
	SchedP50   time.Duration // how long runnable goroutines waited to run: CPU pressure shows here first
	SchedP99   time.Duration
	GCCPU      float64 // share of the process's CPU time spent on garbage collection
	HeapGoal   uint64  // the heap size the GC is aiming for
	GoMemLimit uint64  // GOMEMLIMIT; math.MaxInt64 when unset
	HeapRatio  float64 // HeapGoal / MemLimit, 0 with no limit; an OOM kill comes after 1
	Goroutines int
	GOMAXPROCS int

	// Container signals, from the process's cgroup (Linux, cgroup v2). Zero elsewhere.
	CPULimit      float64       // cores the container may use; 0 when unlimited or unknown
	CPUUsed       float64       // cores used over the window: the cgroup's, or without one the process's own, from the OS (any Unix)
	Throttled     float64       // share of scheduling periods in which the container hit its limit and was paused
	ThrottledTime time.Duration // how long it was paused over the window
	// Memory: what the process holds against where it ends. In a cgroup (a
	// container, a Kubernetes pod, a systemd unit with MemoryMax) the cgroup's
	// working set, less the page cache the kernel reclaims first; elsewhere (a
	// VM, a Mac, Lambda) what the Go runtime holds.
	MemFrom  string // "container" (a cgroup) or "process"
	MemUsed  uint64 // bytes in use
	MemLimit uint64 // bytes: the cgroup's memory.max, else Lambda's memory size, else GOMEMLIMIT; 0 when none
	// MemLimitBy is what sets MemLimit: "cgroup" or "lambda", where the
	// process is killed, or "GOMEMLIMIT", where the collector runs almost
	// without pause; "" when there is no limit.
	MemLimitBy string
	OOMKills   uint64  // processes the kernel killed in this container for memory, since it began
	MemGrowth  float64 // how fast MemUsed grew over the window, bytes a second; negative as it shrinks

	// The live heap: what the GC kept at its last cycle. Unlike the container's
	// memory it has no garbage in it, so a slow leak under a churning cache shows here.
	HeapLive   uint64
	HeapGrowth float64 // how fast it grew over the window, bytes a second
}

RuntimeStats is probe tier 1: the Go runtime's own counters, nearly free to read. Rates and percentiles cover a window, measured as the difference between two samples of cumulative counters.

type SLOStatus

type SLOStatus struct {
	Route    string
	P99      time.Duration // the objective
	Now      time.Duration // p99 over the last 20 seconds, measured inside the service: what Met judges
	Minute   time.Duration // p99 over the last minute, for context: it lags a recovery
	Requests int64         // over the last 20 seconds
	Met      bool          // true with no requests: nothing missed it
	Warning  string        // a reason to doubt the SLO is set up right
}

SLOStatus is a route against its objective over the last minute.

type ServeOption

type ServeOption func(*serveOptions)

ServeOption chooses what Serve serves, and where.

func ClusterKey

func ClusterKey(key string) ServeOption

ClusterKey is the secret every instance of the service shares, signing what peers send each other. VIS_CLUSTER_KEY sets it. With a key and no seeds, an instance listens for peers that list it as theirs.

func FleetWait

func FleetWait(d time.Duration) ServeOption

FleetWait is how long a fleet question waits for each member to answer: VIS_FLEET_WAIT, or 2 s. A member that doesn't answer in time is shown from what its gossip last carried. Raise it where members are slow to answer by design, such as during long shutdown grace periods.

func MCPAt

func MCPAt(addr string, opts ...MCPOption) ServeOption

MCPAt serves MCP on addr, with opts; "" turns it off. The default is localhost:7070, or VIS_LISTEN when set; an address chosen here or there that is taken fails Serve. Exposing MCP beyond localhost needs tokens.

func PeerAdvertise

func PeerAdvertise(addr string) ServeOption

PeerAdvertise is the address other instances reach this one at, when the one it listens on isn't: VIS_PEER_ADVERTISE, or the hostname with the port.

func PeerAt

func PeerAt(addr string) ServeOption

PeerAt is where the instance listens for peers: VIS_PEER_LISTEN, or :7946. Unlike MCP and the UI it must be reachable by the other instances.

func PeerDialer

func PeerDialer(dial func(ctx context.Context, network, addr string) (net.Conn, error)) ServeOption

PeerDialer reaches peers with dial. See PeerListener.

func PeerListener

func PeerListener(ln net.Listener) ServeOption

PeerListener serves peers on ln instead of listening at PeerAt, and PeerDialer reaches them with dial: for networks of their own, such as an in-memory one in tests (vistest.Ring) or a tailnet.

func Seeds

func Seeds(addrs ...string) ServeOption

Seeds are peers to join the ring through: host:port addresses, or a DNS name with a port that resolves to several. VIS_SEEDS sets them, comma-separated. An instance may list itself. Seeds need a ClusterKey.

func StateDir

func StateDir(dir string) ServeOption

StateDir keeps the instance's last word in dir, so the process that replaces it can say why it died: VIS_STATE_DIR, or for Start the temp dir. Give it a directory that outlives the process: an emptyDir volume on Kubernetes.

func UIAt

func UIAt(addr string, opts ...UIOption) ServeOption

UIAt serves the control UI on addr, with opts; "" turns it off. The default is localhost:7071, or VIS_UI_LISTEN when set. Keep it on localhost: it acts as one person.

type Served

type Served struct {
	MCP string
	UI  string
}

Served says where Serve is listening; an empty URL means that surface is off.

type SignalValue

type SignalValue struct {
	Name  string  `json:"name"`
	Value float64 `json:"value"`
	Unit  string  `json:"unit,omitempty"`
	About string  `json:"about,omitempty"`
	Err   string  `json:"error,omitempty"` // the read failed; Value is meaningless
}

SignalValue is one app-published signal, read now.

type StandOut

type StandOut struct {
	Member string
	Why    string
	Look   string
}

StandOut is a member that differs from the rest, and the call to look closer.

type StartOption

type StartOption interface {
	// contains filtered or unexported methods
}

StartOption is an option for Start: an InstanceOption, such as Service or SLO, or a ServeOption, such as UIAt or MCPAt.

type Step

type Step struct {
	Knob string
	By   int64
}

Step moves one knob by a relative amount from the value in effect, clamped to its range. vis computes it under its own lock, so a rule never races another writer between reading a value and writing the next one. A step that can't move, because the knob is at a bound, writes nothing.

type Story

type Story struct {
	ID    string    `json:"id"`
	Kind  string    `json:"kind"`  // rule, change, freeze, environment, watcher
	At    time.Time `json:"at"`    // when it began
	Until time.Time `json:"until"` // its latest event
	Alert bool      `json:"alert"` // it needs attention now
	Who   string    `json:"who"`   // who did it, as the viewer reads it: "you", "agent oncall", "rule batch_backoff"
	Title string    `json:"title"`
	// TitleParts says Title in runs, marking who acted, a rule, a knob and its
	// values, for a page that sets them apart from the words between. They
	// join to Title exactly.
	TitleParts []TitlePart `json:"title_parts,omitempty"`
	Body       string      `json:"body"`
	Knob       string      `json:"knob,omitempty"`
	Lease      uint64      `json:"lease,omitempty"` // the lease to revert, while it lasts
	Mark       string      `json:"mark,omitempty"`  // a short label for a timeline: "batch_size 32"

	// The story's parts, for a page that shows them apart from Body (which says
	// them all, for agents and copying): why, in one line; what it moved,
	// measured After its settle time; and what else changed in that window.
	Why        string   `json:"why,omitempty"`
	Effects    []Moved  `json:"effects,omitempty"`
	After      string   `json:"after,omitempty"` // "30s"
	Confounded []string `json:"confounded,omitempty"`
}

Story is what happened, told for people and agents alike: the UI shows it, and MCP's history tool returns it. One story follows one thing to its end, so it stays true as that thing unfolds: a rule's whole run, a change with its warning and its expiry, a freeze until it lifts.

type Target

type Target struct {
	// contains filtered or unexported fields
}

Target is what an objective asks of its route.

func P99

func P99(d time.Duration) Target

P99 asks that 99% of the route's requests finish within d, measured inside the service.

type TitlePart

type TitlePart struct {
	Text string `json:"text"`
	Kind string `json:"kind,omitempty"`
}

TitlePart is a run of a story's title. Kind is actor (a person or an agent), rule, knob or value, or empty for the words between them.

type Tx

type Tx struct {
	By     Writer
	For    time.Duration // the lease; required when an automated writer sets values, optional for people
	Reason string
	Set    []Write
	Step   []Step
	Clear  []Removal
	// Keep sets the values back after a restart, for what is left of the lease:
	// for a fix the next restart would undo. It needs a lease.
	Keep bool
	// contains filtered or unexported fields
}

Tx is one change: one writer setting or clearing any number of knobs, all or nothing. Everything it sets shares one lease, so values set together expire, hold during a freeze, and revert together.

type UIOption

type UIOption func(*uiOptions)

UIOption configures Instance.UI.

func UIHosts

func UIHosts(hosts ...string) UIOption

UIHosts allows Host names beyond localhost, for example a tailnet name. Every other Host is refused, against DNS rebinding.

func UIUser

func UIUser(id string) UIOption

UIUser names the person using the UI. Changes made there are their pins. The UI listens on localhost, so the person at this machine is who acts; it defaults to the operating system's user name.

type Write

type Write struct {
	Knob  string
	Value int64
}

Write sets one knob in a Tx. The layer follows from the Tx's writer.

type Writer

type Writer struct {
	Kind Kind
	ID   string
}

Writer is who makes a change. The ID comes from authentication (an OAuth subject, a static token's name, a rule's name), never from text the caller types.

func (Writer) String

func (w Writer) String() string

Directories

Path Synopsis
cmd
vis command
Command vis is vis's build tool.
Command vis is vis's build tool.
examples
cacheproxy command
Command cacheproxy is a test vehicle for vis: an HTTP cache in front of a slow, simulated origin, with knobs a person, an agent or a reflex can turn.
Command cacheproxy is a test vehicle for vis: an HTTP cache in front of a slow, simulated origin, with knobs a person, an agent or a reflex can turn.
cacheproxy/loadgen command
Command loadgen drives cacheproxy over real HTTP from outside its container, so squeezing the container's CPU throttles the server, not the load.
Command loadgen drives cacheproxy over real HTTP from outside its container, so squeezing the container's CPU throttles the server, not the load.
integrations
visecho module
visgin module
internal
gen
Package gen turns a package's // vis: directives into Go code: one vis_gen.go of ordinary vis calls, checked in and readable.
Package gen turns a package's // vis: directives into Go code: one vis_gen.go of ordinary vis calls, checked in and readable.
manifest
Package manifest reads what a service declares to vis (knobs, signals, objectives, rules) from its source, and says how two versions differ, for review: a change to a knob's bounds or to who may change it is reviewed like an API change.
Package manifest reads what a service declares to vis (knobs, signals, objectives, rules) from its source, and says how two versions differ, for review: a change to a knob's bounds or to who may change it is reviewed like an API change.
pipenet
Package pipenet is an in-memory network: listeners by address, and a dialer that reaches them over net.Pipe.
Package pipenet is an in-memory network: listeners by address, and a dialer that reaches them over net.Pipe.
spec
Package spec is what a vis declaration means, in one place: which measures are latencies, and which vis types hold latencies.
Package spec is what a vis declaration means, in one place: which measures are latencies, and which vis types hold latencies.
vet
Package vet holds vis vet's checks, as go/analysis analyzers: the mistakes in using vis that compile and run but are wrong.
Package vet holds vis vet's checks, as go/analysis analyzers: the mistakes in using vis that compile and run but are wrong.
Package vistest helps test code that uses vis: each test gets its own instance, so tests that change knobs can run in parallel.
Package vistest helps test code that uses vis: each test gets its own instance, so tests that change knobs can run in parallel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL