Test-driven, always
The loop, in order, for every behavior change:
- Define the behavior. State what the feature does and how it is observed, as an assertion, not a vibe.
- Write the failing test. It must fail for the right reason before any machinery exists. A bug fix starts with a test that reproduces the bug.
- Build the minimal machinery to make the test pass. Nothing more.
- Refactor with the test green.
A change that adds or alters behavior is incomplete without a test that failed before it
and passes after. Each change carries the right tier(s): unit for logic,
integration (real Postgres) for anything touching storage, e2e (API, CLI, UI) for
user-facing behavior. Bug fixes start with a failing regression test that stays in the
suite. make test is the gate: green before commit and before merge. Validate locally;
do not lean on CI to find what a local run would.
The console’s package manager
Section titled “The console’s package manager”make test, make gen, and the other build targets install the console’s dependencies with
pnpm install --frozen-lockfile, which installs exactly what web/pnpm-lock.yaml records and
fails rather than rewrite it, so git status stays clean. web/package.json’s packageManager
names the pnpm version, and pnpm 10 switches to it on its own. A dependency’s install script runs
only when web/pnpm-workspace.yaml allows the package under allowBuilds, and strictDepBuilds
makes the install fail (ERR_PNPM_IGNORED_BUILDS) on any install script the file does not decide, so a
new dependency that has one stops the install until it is listed there as true or false.
scripts/web_pnpm_test.go fails on any entry that does not also record its answer and the reason.
The spike carve-out
Section titled “The spike carve-out”A spike to learn whether something is possible may precede tests, but it must be labeled a spike and either deleted or stabilized with tests before it merges. “Spike” is not a standing excuse to skip the failing test.
The capability-primitive carve-out
Section titled “The capability-primitive carve-out”When a unit wraps an environment-risky capability (raw sockets, ICMP, privileged syscalls, an external protocol), a fake-based unit test is necessary but not sufficient.
- Commits may be incremental: a fake-green seam is a legitimate checkpoint commit.
- The real-implementation integration test is required to close the increment and is an absolute gate before any merge. It is never dropped, only sequenced within the increment.
The environment risk is the point of the primitive. A green fake with the real path unproven proves nothing about the capability.
- Unit: pure logic, fast, no I/O. Expression compile/eval, decode, request shaping, mapping.
- Integration: real Postgres, no mocking the database.
testcontainers-gogives each run an ephemeral instance on a random port; never bind a fixed host port. The simulator follows the same rule: a test serves it onsim.EphemeralPortsand aims its clients and endpoints at the address each face reports (fixed and ephemeral ports). A test that needs a dial refused aims atnettest.RefusedAddr, a loopback port held for the test’s life by a socket bound to it that never listens, so the connect is reset and no other process can take the port; never at a port found by listening on:0and closing, which a concurrent run can be handed before the dial. A UDP refusal aims at a privileged port, whichbind(:0)never hands out. A guard test (TestNoTestUsesAReleasedPort) fails any test that uses a raw listener’s or an httptest server’s address after closing it; a port released through a wrapper (a simulated face stopped and restarted) is the sibling guardTestNoTestRestartsAFaceAtALiteralAddress’s: such a test takes its address fromsimtest.ClaimLoopback, never a literal. - End-to-end: emulate the user at each entry point against the running stack: API
(drive the contracts as a client), CLI (run the real commands), UI (browser-drive the
SPA). Assert the user-observable outcome, not internals. The real binary follows the same
port rule: every end-to-end test in
internal/e2estartsomniglass serverthrough one helper,startServer, which asks for port 0 on both the API and the embedded bus and reads the addresses the server bound back from its ready file (a server on ports it picks). Nothing picks a free port, releases it and hands the number to a later bind, which a concurrent run on the host could take in between; a guard test in the package fails any test there that starts the server another way or sets its listen addresses. The browser tier, the docs screenshots, the demo pipeline and the probe run the server in Docker instead, each on a throwaway lab of a project of its own per run (omniglass lab run, throughweb/e2e/lib/lab.sh), on a loopback port Docker picks, which isolates them the same way. The browser tier’s lab is seeded with theemptyscenario, so its CRUD round-trips start from a fresh install; the screenshots’ lab runs with no outpost (--no-outpost), so the pages they photograph hold still. The browser tier has a floor no console route can dodge: the router renders from a route manifest (web/src/lib/routemanifest.ts) and the smoke spec (web/e2e/routes.spec.ts) drives the same manifest, visiting every route and failing on any page or console error, so adding a route adds its smoke test by construction.
No mocking the system under test. No tests-within-tests.
The storage test harness
Section titled “The storage test harness”Integration and end-to-end tests share one real-Postgres harness,
internal/storage/storagetest. It starts a single container per test binary,
lazily, and hands each test a fresh, migrated, isolated database, so tests never
share mutable state or collide on a host port.
The migration chain is applied once per test binary, into a template
database, and each test’s database is a CREATE DATABASE ... TEMPLATE copy of
it. A copy is a file-level clone rather than a replay of every migration, and it
carries schema_migrations with it, so a provisioned database is
indistinguishable from a migrated one, including to dbmate. Isolation is
unchanged: every test still gets its own database.
Starting the container and building the template are both per-binary work, so
the harness caches success and never failure on each. A sync.Once here
remembers one transient hiccup (a flapping container, a refused admin
connection) and fails every remaining test in the binary from it, all at 0.00s
with the same replayed message, which buries the one failure that was real.
Retrying on the next call keeps a blip costing one test, which is what the
per-test migration replay used to give for free. A start that fails terminates
whatever container it was handed on the way out: testcontainers returns the
container alongside the error when the create succeeded and the wait did not, so
a retry over a caller that drops it leaks one Postgres per attempt.
Postgres refuses to copy a template that has live connections, and
internal/migrate builds a dbmate.DB it never explicitly closes, so the
harness does not assume dbmate left nothing behind. After migrating it
terminates any backend still attached to the template and then sets
allow_connections = false, which makes the copy deterministic rather than
timing-dependent. Retrying on source database ... is being accessed by other users would only have turned a deterministic failure into an intermittent one.
Cleanup is a hard contract, not a convenience. Every package that uses the
harness must route its tests through storagetest.Main from a TestMain:
func TestMain(m *testing.M) { os.Exit(storagetest.Main(m)) }Main terminates the shared container after m.Run(), in-process, on normal
exit. This is the reason cleanup is reliable: it does not depend on the
testcontainers reaper (ryuk), which is only a backstop for hard kills and cannot
be relied on alone. In some environments (for example Docker Desktop on WSL2)
ryuk is disabled or torn down before it can reap, so a container with no
in-process teardown leaks and stays running indefinitely.
That contract is enforced, not documented. NewDSN refuses to provision a
database for a test binary that is not running under Main, and fails with the
TestMain to add. The paragraph above was already true and already written when
three packages drifted off it anyway, leaving one stray container each per gate
run; a doc comment is not a mechanism. The check sits exactly on the defect,
since the call that would start an unreclaimed container is the one that fails,
inside the offending package.
For orphans left by a genuinely hard kill (a SIGKILL or a Docker restart before
either mechanism fires), sweep them with make clean-testcontainers. It
force-removes leftover Postgres test containers, scoped by the testcontainers
label and the postgres:18 image so it never touches the compose dev stack.
Tests run in parallel, and a fixture is seeded once
Section titled “Tests run in parallel, and a fixture is seeded once”Because every test owns a database, tests in internal/storage,
internal/devseed, internal/api and internal/outpost are independent by
construction, and they run in parallel on the package’s one container. The api
and outpost end-to-end stacks bind ephemeral ports only, which is what lets them
overlap; a test that needs a fixed port says // Serial:. A test that is not parallel puts its whole length on
the gate’s critical path, so the default is a rule: every top-level test starts
with t.Parallel(), or says in a // Serial: comment why it cannot. The reasons
that hold up are process-wide state the test changes or asserts on: a
package-level cap hook, slog.SetDefault, a global counter such as
rules.CompileCount. Serial tests finish before any parallel test is released,
so they never overlap one. storagetest.RequireParallelOrSerial is the scanner,
and each package runs it as a test, so the gain cannot quietly rot. Queries over
cluster-wide views such as pg_stat_activity filter on
datname = current_database(), or one test sees another’s sessions. The harness
starts Postgres with fsync=off and max_connections=400, safe for a throwaway
database and sized for the parallelism; TEST_PARALLEL=1 still bounds how many
packages share a machine.
The same idea one layer up is storagetest.NewDSNFrom(t, key, build): a
derived template is the base template plus a build step (a boot seed, a
seeded fleet), run once per test binary, sealed, and cloned per test. A test
that only reads seeded state takes a clone; a test that verifies the seeding
itself (idempotence, an option’s effect, the large scenario) still runs the seed.
Like the base template it caches success and never failure. internal/devseed
spent most of its time seeding the same fleet into every test before this, and
internal/api now clones one booted seed (seededDSN) instead of running it in
each of about two hundred tests.
Fixtures are minted, not borrowed
Section titled “Fixtures are minted, not borrowed”A behavior test that needs “a product classified display” mints one:
p := storagetest.MintProduct(t, ctx, gw, "display")MintProduct creates a throwaway, randomly named product under the
component type the test chose, which is the only fact the test actually
depends on (an empty type takes the gateway’s own generic floor). What it
replaces is borrowing a seeded SKU as a fixture of convenience: the #802
catalog rename broke ~50 tests and only ~15 were seed-contract pins doing
their job; the rest were behavior tests that had coupled themselves to the
catalog’s identity for no reason the test could state.
The rule is enforced, not documented, in the house pattern: a guard in
internal/build fails any *_test.go that names a seeded product SKU
outside the designated pin files (the seed’s own tests and the demo fleet’s),
reading the SKU list from the seed’s own render so it can never drift from
the catalog it protects. The pin files, in turn, derive their expectations
(counts, slot shapes, accepted types, contract defaults) from the embedded
YAML instead of restating it. A future catalog change touches the YAML and
the pin files, and nothing else (#804).
Two edges of the rule: a test about official-row behavior (the seed-owned
read-only refusals) still needs a genuinely seeded product and uses the
generic floor (generic-device), which is catalog vocabulary rather than a
brand; and a test whose assertions read the type tree (stems, labels,
inherited facts) mints a product under the type it needs, because the walk
under test never looked at the product anyway.
Six performance instruments, four of which gate
Section titled “Six performance instruments, four of which gate”Performance has six instruments in this repo, and they are deliberately not the same thing. Knowing which answers a given question is most of the value:
| Round-trip counting | Access-path assertions | Ingest footprint | Scale lab gate | Lab footprint | Wall-clock benchmarks | |
|---|---|---|---|---|---|---|
| Catches | N+1s: cost that grows with row count | A read that cannot reach the index it was built for | What one outpost batch costs the database: statements, rows per observation, bytes per row | A fleet that loses work or costs more to run than the committed baseline: closed-loop gaps, delivery loss, rows and bytes per system, latency, CPU and memory | What a running lab costs per container and per day: CPU, memory, rows a minute, growth, read latency | Cost inside one statement: a recursive CTE that stops being bounded, a plan that degrades on real volume |
| Blind to | Anything a single statement does | Everything except one relation’s access path | Reads, and time | A regression smaller than its tolerance or the runs’ spread; times and usage on a host other than the baseline’s | Anything smaller than the host’s neighbours move it by | Anything smaller than the host’s own noise |
| Determinism | Exact. Same number every run | Exact. Independent of the fixture’s size | Exact, except index bytes, which are bounded | Exact for the loss figures; the rest a median of N runs against a spread | Noisy. A median of N windows, with the range beside it | Noisy. Interpreted by comparison, never by threshold |
| Gates a merge | Yes. Ordinary tests in make test | Yes. Ordinary tests in make test | Yes. An ordinary test in make test | Opt in. Fails the change it runs on; never a required check | No. A diagnostic | No. Inert without -bench |
| Fleet it reads | The test’s own fixture | The test’s own fixture | The dev scenario’s fleet, one standard workload | The corporate scenario at a named rung (300 or 1000 systems), stated in the baseline it compares with | The corporate scenario at 20 systems by default, read from the lab’s labels | The benchmark’s own fixture |
| How you run it | make test | make test | make test; make footprint prints it | make perf-check SIZE=300, by hand on a test VM | make lab-footprint | make bench, deliberately, before and after |
They are complements, not alternatives. A dropped index issues exactly as many statements as the index scan it replaced, so counting never moves; an N+1 that doubles from twenty to forty statements is well inside the wall clock’s noise on a laptop, so the benchmark never notices; and neither of those can tell an index that is present from an index that is reachable. Each is the only instrument that sees its own class.
Asserting an access path, never a plan
Section titled “Asserting an access path, never a plan”internal/storage/storagetest/accesspath is the primitive, and the distinction it rests on
is the whole design (ADR-0094,
as amended). A plan a fixture PREFERS says nothing about production, because preference is a
function of table statistics and no fixture here is production-sized. Whether a query can
REACH an index at all is a different question: planned with set enable_seqscan = off,
which prices the sequential path out rather than forbidding it, the answer is stable across
an empty table, a fixture with no statistics, and the same fixture analyzed, while the join
shapes around the scan move freely between those states.
That is the failure this catches and nothing else can: an index sits in pg_indexes while
the read it exists for cannot use it, because a predicate got a function wrapped around it,
a type coerced, a leading column dropped from the filter, or (for a partial index) its
predicate stopped being provable from the query’s own clauses. The statement count is
identical throughout, and so is the catalog.
Three rules, and an assertion that breaks one of them is worse than none:
- One relation’s access path, never the plan’s shape. Everything above the scan is stats-dependent and will flap.
- Assert the index CONDITION, not only the index name. A scan node can name an index
and carry no condition, meaning the planner walks the whole index and filters afterwards.
That is the shape a coerced predicate produces, and it reads as a pass to anything that
greps for the name.
Plan.MustReachchecks the name, the condition, and that the outpost is not one the planner was forced into. - Explain the statement the code really issued.
querycount.Counter.Callshands back each captured statement WITH its arguments, so the guard replays the gateway’s own SQL rather than a copy maintained beside it; a copy is exactly what stops failing when the original changes.
Counting what ingest costs
Section titled “Counting what ingest costs”TestIngestFootprint (internal/bus/footprint_test.go) holds what one outpost batch costs the
database (ADR-1272).
It seeds the dev scenario’s fleet for real and delivers a standard workload through the
telemetry handler exactly as JetStream would: the owner binding, LandBatch with its receipt,
locks, transition guard, rule evaluation and the endpoint’s seen stamp. The catalog fingerprint is
read on the warm-up and the catalog’s clock is frozen, so the window’s batches reuse it as a
fleet’s do between reads. Only the transport is a double. The workload (internal/footprint) is one batch
per outpost per tick, a group per task, built deterministically from the tasks and the tick, so two runs land the
same rows and a number that moves is the code moving.
It holds five things and reports the rest:
- Statements per batch, exact. A change that adds one fails with the statements a batch issued, so the failure names what moved.
- Rows per observation on each lane, exact. A metric stores every observation; a property stores transitions only, so a steady window writes no property rows.
- Metric rows per full heap page, exact, after
VACUUM. Density rather than a page count, so a fleet that grows by a few endpoints moves nothing unless a row does. The metric table is partitioned by day (storage), so its bytes are summed over its partitions. - The metric table’s index definitions, exact, so an added, dropped or re-keyed index fails by name.
- Index bytes per stored metric row, bounded, measured after
REINDEX. A live index’s page splits follow the fleet’s component uuids, which the dev seed mints at random, so its size differs from run to run by about a fifth; a rebuilt index is the same every run, and the bound sits just over it. - Reported only: the live index size, receipt bytes per batch, the
metric_seriesrows and bytes (one per series, not per sample), and WAL bytes per observation, which moves with checkpoint timing and is the cost a replica or a WAL archive pays. Wall-clock time isBenchmarkIngestFootprint’s, inmake bench.
The workload is declared by shape, not by driver: storage cost follows series per component,
lane, cadence and how often a value changes, not the protocol that produced it.
footprint.StandardMix is calibrated to a measured lab run and is re-derived when the
simulated fleet changes. A change that moves a held number on purpose (batched writes,
narrower rows) updates the constant in the same PR and says why; make footprint prints the
current figures, and BenchmarkIngestFootprint in make bench times the same path.
Measuring a running lab
Section titled “Measuring a running lab”The ingest footprint counts one batch through the handler; it cannot say what a lab costs to
run. make lab-footprint does
(ADR-1277).
It builds the image, brings up a throwaway lab of its own project, the corporate scenario at
20 systems (-scenario and -systems change it), at a
cadence profile, warms it up, and measures N
back-to-back windows. Every lab level that measures runs the corporate scenario at a stated size, so
a figure from here compares with the same size on the
scale ladder; the dev lab is the showcase,
never a lab measurement’s basis, and the report names the scenario and size it read from the lab’s
labels (ADR-1719).
- CPU per container (server, the outposts summed into one row, Postgres), in millicores, from each cgroup’s CPU time as the Engine reports it.
- Memory per container, the working set: anonymous plus shared memory, never RSS, which counts the binary’s file pages and the page cache the kernel would reclaim.
- Rows a minute on the metric and property lanes, from Postgres’s cumulative statistics, so measuring scans nothing. A lane is summed over its partitions.
- Growth a day of the metric and property tables (with their indexes), the receipts, the whole database, and the WAL a replica or archive would carry.
- Series read latency over 24 h and 30 d, through the API the console reads, with the server and Postgres held to one vCPU while the reads are timed (and only then, so ingest is measured unthrottled).
Each figure is the median of the windows, printed with the lowest and the highest. Read the range before the median: on a shared host the neighbours move every figure here, which is why it gates nothing. Measure on a quiet machine, with nothing else of yours running, and compare two runs you took minutes apart. When it is done it stops the lab and fails if any container, network or volume of its project is left.
make lab-footprint # corporate at 20, the lab profile, 5 one-minute windowsmake lab-footprint LAB_FOOTPRINT_ARGS="-cadence default -windows 7 -json out.json"-cadence takes any of the lab guide’s
cadence profiles; -json writes the report for a
generator to render.
A scale lab’s figures are diagnostic, but one thing it reads is not a cost and is held: whether
every request an outpost sent reached its simulated endpoint and was answered. omniglass lab measure
reconciles each outpost’s tally against what its simulators observed and what landed, hop by hop
(connect-not-accepted, sent-not-received, received-not-settled, answered-not-returned,
published-not-landed, spool-dropped, unhit-endpoint), each a lower bound with its masking
term beside it (how to read them).
The arithmetic is pure and unit-tested gap by gap; make test-lab brings up a 20-system corporate
scale lab, measures it with lab measure’s own path at that size, and fails on any loss, any face that saw two requests at once, any polled protocol that
drew no request, or a restart inside the window. It needs the image make builds, so it is outside
make test and CI.
Comparing metric compression formats
Section titled “Comparing metric compression formats”make compress-bench answers one question the instruments above cannot: what a metric
sample costs under a different storage format. It compresses the same seeded series (with
duplicate instants, ADR-0061) under each candidate on throwaway Postgres 18 containers, at
10 s, 30 s, 60 s, 5 m, 1 h and 24 h. The candidates are blocks of SQL arrays in
benchmark-only tables, one row per series per span (hour and day everywhere, week and month
too at 1 h; a block longer than an hour carries per-hour summary arrays), raw rows, and
TimescaleDB. It reports bytes per sample after VACUUM (heap, TOAST, indexes and any
companion or chunk tables), the share of those bytes the summaries take, the share of rows
Postgres actually compressed, compression time per thousand samples, the 24 h raw and 30 d
bucketed read latency, and what one late sample costs to merge (time and WAL bytes), each
the median of N runs. Every candidate must give back exactly what it was given, hourly
summaries included, before and after the late merge, or the run fails. From those cells it
derives a span rule: per cadence, the shortest span whose rows compress, and the cadence at
which a series stays raw. Then the fit probes ask pg_deltax and TimescaleDB, on a real server,
what happens to retention, a late row, DETACH, pg_dump and a streaming standby. The extension
images are test-only, built from official, unmodified releases with their licenses
(internal/compressbench/images). Like the lab footprint it gates nothing.
-plain measures the summary-free block instead: each series-day takes the span its count
earns (hour, day, or a share of an ISO-week block), beside the summary-carrying blocks and an
hourly trend table. It sweeps week blocks from 1 to 168 samples a week against raw rows for the
week minimum, then holds a week of series that change cadence mid-week to the span rule, sample
for sample.
make compress-bench # formats, span rule and fit probesmake compress-bench COMPRESS_BENCH_ARGS="-probes=false" # formats and span rule, about a quarter hourmake compress-bench COMPRESS_BENCH_ARGS="-cadences 1h -days 30 -probes=false"make compress-bench COMPRESS_BENCH_ARGS="-bench=false -probes=false -plain" # summary-free blocks, about ten minutesBenchmarks are diagnostic, never a gate
Section titled “Benchmarks are diagnostic, never a gate”make bench runs go test -bench over internal/storage and the ingest handler in
internal/bus, at a small fleet and a larger one, against real Postgres through the same harness the integration tests use. What it
deliberately does not do is as much of the design as what it does:
- No CI job and no merge gate. A wall-clock threshold on a shared runner either sits so loose it catches nothing or it flakes and gets muted, and a perf job everybody ignores is worse than none because it reads as coverage.
- No stored baseline. Comparison is between two runs you took, on one machine,
minutes apart, with
benchstat(a separate install:go install golang.org/x/perf/cmd/benchstat@latest). A baseline committed to the tree would be a number from a different machine on a different day. - No timing assertion, anywhere. Not in a benchmark, not in a test. Timing assertions flake on a dev laptop, and that flake is the reason the counting instrument exists.
Those three refusals hold for a benchmark. A whole scale lab answers each of them differently, and is
the one instrument that gates on time at all
(ADR-1640).
make perf-check SIZE=300|1000 measures three throwaway labs of a rung of the ladder and compares them with
that size’s committed baseline:
- Run by hand, never in CI. It runs on a test VM, the host class every rung’s baseline was generated on, and is never a required check (ADR-1787).
- A stored baseline, but generated and fingerprinted.
make perf-baselinewrites it on the host class it gates (every rung’s file on a test VM of 8 cores and 16 GiB), with that host’s CPU, cores and memory. Times and usage gate only on a matching host and readreportedelsewhere; the counts gate everywhere. A PR that changes a baseline says why. - Medians against a spread, never one run. A figure fails only past its tolerance and past the
baseline’s spread plus the runs’ spread; runs that spread past the tolerance read
noisy, which does not fail. The loss figures (closed-loop gaps, delivery loss, redeliveries) are exact and must be 0.
How to run and read it is in the lab guide’s Checking against the baseline.
Three rules make a benchmark here mean anything:
- Setup is outside the timed section. Provisioning a database and seeding it costs far
more than any query being measured, so a benchmark that includes its own fixture build
measures the harness and moves whenever the harness does. Fixtures are built once per
size and shared;
b.ResetTimerruns before the loop. - Two sizes, always. One number cannot tell a constant apart from a linear cost, and the growth curve is the whole question: a list should grow with the fleet, a tag cascade walking one component’s ancestors should not, and only the pair says whether that is still true.
- Subtract the floor.
BenchmarkRoundTripFloormeasures one pool acquire and one empty statement, and every other number contains one copy of it per statement issued. A call that issues dozens of statements is mostly transport, so a plan regression inside it moves the total by very little. That is a real limit on what this instrument can see, and a path measured to sit past it should be counted rather than timed.
Waiting on the event, not on a window
Section titled “Waiting on the event, not on a window”An end-to-end test that waits for something to land waits on the event, with a ceiling generous enough that only a real absence reaches it. A wait that is a window (a pushed change lands “within a second”, a rejection clears “within five”) is a claim about the speed of the machine, and the shared runner that carries three shards at once cannot keep it: one run saw a change land 4.8 s after it happened where a quiet machine needs 100 ms, and sixteen outpost tests failed together with no code cause (#1717). A red shard has to mean a regression.
In internal/outpost the ceilings are two helpers (patience_test.go), not numbers
typed at each wait:
patience(base)is the ceiling for an event the test is not timing: a property landing, a session coming up, a command settling. It is a multiple of the base a quiet machine needs, with a floor, and costs nothing when the event arrives.pushWindowis for a change that must have been pushed rather than polled. The cadence it has to beat is a minute or an hour (the test removes the polls where it can), so the window bounds the push from the poll and is not a latency budget.
Where latency is itself the behavior, a window cannot be asserted on a shared runner; bound the work instead (the count of pulls a burst of changes may cost), as the next section does for reads.
Counting round trips, not timing them
Section titled “Counting round trips, not timing them”Read performance is asserted as a count of SQL statements, not as a duration. The Gateway’s dominant cost is round trips to Postgres, and the regression that hurts at fleet scale is the N+1: fifteen thousand components paying two or three queries each. A count is deterministic. It needs no stored baseline, no threshold policy, and no warm-up, and it fails with an exact number that names the defect, where a wall-clock measurement on a laptop or a shared runner has variance that swamps anything short of a catastrophe. What a count cannot see is a missing index or a sequential scan inside one query; that is the other instrument above, not a reason to skip this one.
internal/storage/storagetest/querycount is the primitive.
storagetest.NewCountingDB hands back a gateway plus a querycount.Counter, and
the counter is a pgx.QueryTracer attached to the pool’s connection config, so it
sees every statement the gateway issues.
The seam is the whole design, and it fails silently. A count means nothing if
the code under test does not go through the counted seam: a counter wrapped around
some argument that the code never reaches for reports a small, flat, entirely
fictional number, and the assertion built on it reads as coverage while measuring
nothing. The gateway’s List methods take a scope.Set and query the pool
directly, so only the pool tracer observes them; Counter.Wrap observes only a
function that takes its querier as a parameter, such as the address-attach hooks.
A count of zero where several statements were expected is the tell.
Every count assertion checks both properties, because neither alone has teeth:
- Flatness: the same cost at a small page and a larger one. A ceiling alone passes an implementation that is flat at a bad number.
- A ceiling: an absolute maximum. Equality alone passes an implementation that is still per-row with a smaller constant, and passes anything at all if the two pages are secretly the same size.
The fixture has to vary the dimension the count grows along, which is subtler than page size: an address walk grows with the number of distinct rooms a page spans, so a page confined to one room makes a per-room loop look exactly as flat as a batch. And a new assertion earns its place by mutation: break the batching or the join, watch the number move, revert. A count test whose only red was a build failure has not been shown to measure anything.