Skip to content

Add usage collector for the hosted registry - #1877

Merged
rdimitrov merged 2 commits into
mainfrom
rdimitrov-usage-collector-go
Nov 20, 2026
Merged

rdimitrov merged 2 commits into
mainfrom
rdimitrov-usage-collector-go

Conversation

@rdimitrov

@rdimitrov rdimitrov commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

What this adds

cmd/usage-collector is a new, separate binary that records how the hosted registry was used on each full UTC day, and what was published to it. Its logic is in internal/usage/.

It is specific to the hosted instance. It is not part of the registry server binary or image, so nothing here affects self-hosted registries. This PR is the program and its tests only: no image build, workflow, .ko.yaml, deploy/ or dashboard changes.

For one day it:

  1. reads the gateway's request counters from a Prometheus-compatible store, for totals;
  2. reads the gateway's access records from Cloud Logging, for who used the registry and how;
  3. scales the sampled access records back to the counter totals, hour by hour;
  4. writes the day's totals and breakdowns to Postgres, where the dashboards read them.

It can also write the day's report as Markdown. cmd/usage-collector/README.md is the operator's guide.

Behaviour worth reviewing

  • Missing days fill themselves. A run without --day collects every day in the look-back window that is not stored. A missed night or the first backfill needs no manual job.
  • Incomplete days wait. A day is not collected if something it needs could not be used (counters, network reference files, an up-to-date catalogue). This is known before the logs are read, so they are not read. A stored day is not collected again on its own, so storing a poor one would be permanent.
  • Last chance. On the last scheduled run that looks at a day, it is stored with its caveats rather than lost. The one exception is a day without request counters, which cannot be sampled or scaled.
  • Schema. The program applies its own schema: additive, idempotent, tracked, under an advisory lock. Collecting a day again replaces that day's rows in one transaction.
  • Publishing. It reads the registry's servers table, only the versions changed since the last run, in pages of 500 inside short read-only transactions with a statement timeout. The registry moves is_latest between versions without touching updated_at, so the reader also refreshes that flag for the servers it sees change.
  • Dashboard arithmetic. The view and functions the dashboards call weight every rate by what it is a rate of, and return nothing where a figure cannot be worked out from what is stored. They are tested against figures worked out by hand.
  • Quality record. Each day stores the ratio of the log-based estimate to the counters, so a change in the log format or the sampling rule shows up as drift.
  • Reader role. An optional setting names an existing role that is granted read-only access to what the dashboards query.

Settings

All settings are USAGE_COLLECTOR_* environment variables. Nothing about a particular environment is built in.

Variable Meaning
GCP_PROJECT, CLUSTER_NAME, LOG_NAMESPACE, LOG_CONTAINER where the access records are
GCP_QUOTA_PROJECT project charged for log reads, for user logins
METRICS_URL the store with the request counters
DATABASE_URL where the usage tables live
REGISTRY_DATABASE_URL the registry database, read-only
READER_ROLE role to grant read-only access for the dashboards
ORGANIZATION_ALIASES names for organizations' own networks
LOOKBACK_DAYS, MAX_RECORDS, DOLLARS_PER_GIB, CACHE_DIR tuning

Only hosting providers are recognised by name in the code. Organizations are never built in; they come from ORGANIZATION_ALIASES.

Privacy

  • Client addresses are used only in memory, to count distinct sources and look up the network owner. They are never logged, written to the report, or stored.
  • A requested server name is stored only if that server is published. Every other requested name is counted in one group and never written down.
  • User agents are reduced to a short product name of plain characters. A product name that says who or where the client is (an address, an email address, a private host name, a long identifier) is replaced by a fixed label, and the client counts as unnamed.
  • Requests to the gateway's own test hosts are left out, as they are from the gateway's counters.
  • The collector's own log holds counts and status codes only.
  • Every fixture is synthetic: addresses come only from documentation ranges, and organizations are fictional. Two tests enforce this: one searches the stored rows, the report and the log for anything sensitive from the fixtures, and one checks every address in testdata/.

How parity with the prototype is tested

This replaces a Python prototype, and it has to produce the same figures from the same records.

  • Golden files. 13 synthetic scenarios were run through the prototype. The Go tests must reproduce its report byte for byte and its rows digit for digit. Where the collector deliberately differs from the prototype (the two privacy and population rules above, and organization aliases coming from a setting), the same correction was applied to the prototype in memory; internal/usage/testdata/README.md lists each difference. The scenarios cover a normal day, a sub-sampled day, each source being unavailable, a day before user agents were logged, and a file of malformed records.
  • Single functions. About 1,200 inputs were run through the prototype's own classification and parsing functions, and the results are replayed against the ports.
  • Real days. Outside the repository, three real days were collected with this binary. Each report was byte-identical to the prototype's, and every row matched exactly.
  • Publishing. The reader's output for a full copy of the public catalogue matched the prototype's derivation on every row.

Because byte-identical output depends on summation order and tie-breaking, pycompat.go and parts of the aggregation reproduce Python semantics on purpose. internal/usage/testdata/README.md explains where the expected output comes from and how to update it now that the prototype is retired.

Checks

  • go test ./internal/... ./cmd/... passes, and ./internal/usage passes with -race. Statement coverage of internal/usage is about 90%.
  • golangci-lint v2.14.0 reports 0 issues.
  • No new modules. cloud.google.com/go/auth and golang.org/x/text were already required indirectly and are now direct.

The database tests need PostgreSQL on localhost:5432, as the existing unit tests do.

Not verified

  • The registry reader has not run against the real registry database. It was run against a local servers table rebuilt from the public catalogue, and against tests that write through the registry's own publish and delete code. Its SQL has not met real, full server documents, nor the production database's size and load.
  • It has not run in a cluster. Credentials there, network egress for the two public reference files, and the database roles are for the rollout PR.

Add cmd/usage-collector, a separate binary that records how the hosted
registry was used on each full UTC day and what was published to it.
It is specific to the hosted instance and is not part of the registry
server image.

For a day it reads the gateway's request counters and its access
records in Cloud Logging, scales the sampled records back to the
counter totals hour by hour, and writes the day's totals and
breakdowns to Postgres. It can also write the day's report as
Markdown.

- Ported from the Python prototype. For the same records it produces
  the prototype's report byte for byte and its rows digit for digit;
  the tests replay the prototype's output on synthetic fixtures.
- Publishing is read from the registry database, only the versions
  changed since the last run, in short read-only pages.
- Each run fills any day in the look-back window that is not stored.
  A day that lacks a source it needs is not collected, so a later run
  collects it properly. On the last run that looks at a day, it is
  stored with its caveats instead, unless its request counters are
  missing.
- The schema is applied by the program, additively and idempotently.
  Collecting a day again replaces its rows in one transaction.
- An optional reader role is granted read-only access to what the
  dashboards query.
- Each day records how closely the log-based estimate matched the
  counters, so a change in the log format or sampling rule shows up.
- Settings come from USAGE_COLLECTOR_* environment variables; nothing
  about an environment is built in. That includes the names of
  organizations' networks, which come from a setting; only hosting
  providers are built in.
- Client addresses are used only in memory. A requested server name is
  stored only if that server is published.

No new modules: cloud.google.com/go/auth and golang.org/x/text were
already required indirectly and are now used directly.

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved findings include incorrect listing denominators and multi-day client shares, address-like user-agent labels leaking into storage and reports, and fixture traffic contaminating usage metrics.

5 open issues
What changed in this PR

Adds a standalone usage collector for the hosted registry, separate from the registry server. It combines gateway counters, sampled access logs and publication data into daily PostgreSQL records and optional Markdown reports; deployment changes are deferred.

Changes:

  • Adds collection, backfill and degraded-day handling with environment-based configuration.
  • Adds catalogue synchronization, usage storage and dashboard query definitions.
  • Adds synthetic fixtures, prototype-parity checks, privacy tests and operator documentation.
File Description
README.md Lists the collector and usage package.
Makefile Adds the collector build target.
internal/​usage/​testdata/​scenarios/​typical/​scenario.json Configures normal-day coverage.
internal/​usage/​testdata/​scenarios/​typical/​report.md Records the normal-day report baseline.
internal/​usage/​testdata/​scenarios/​subsampled/​scenario.json Configures subsampling coverage.
internal/​usage/​testdata/​scenarios/​subsampled/​report.md Records the subsampled report baseline.
internal/​usage/​testdata/​scenarios/​no-networks/​scenario.json Simulates unavailable network ownership data.
internal/​usage/​testdata/​scenarios/​no-networks/​report.md Records unknown-network output.
internal/​usage/​testdata/​scenarios/​no-network-types/​scenario.json Simulates unavailable network classifications.
internal/​usage/​testdata/​scenarios/​no-network-types/​report.md Records fallback classification output.
internal/​usage/​testdata/​scenarios/​no-hourly-counters/​scenario.json Simulates unavailable hourly counters.
internal/​usage/​testdata/​scenarios/​no-hourly-counters/​report.md Records whole-day scaling output.
internal/​usage/​testdata/​scenarios/​no-counters/​scenario.json Simulates unavailable request counters.
internal/​usage/​testdata/​scenarios/​no-counters/​report.md Records log-estimated totals.
internal/​usage/​testdata/​scenarios/​no-catalogue/​scenario.json Simulates an unavailable catalogue.
internal/​usage/​testdata/​scenarios/​no-catalogue/​report.md Records output without catalogue lookups.
internal/​usage/​testdata/​scenarios/​no-bytes-counter/​scenario.json Simulates an unavailable byte counter.
internal/​usage/​testdata/​scenarios/​no-bytes-counter/​report.md Records estimated data-volume output.
internal/​usage/​testdata/​scenarios/​no-aliases/​scenario.json Tests classification without organization aliases.
internal/​usage/​testdata/​scenarios/​no-aliases/​report.md Records unaliased network names.
internal/​usage/​testdata/​scenarios/​mixed-user-agents/​scenario.json Simulates partial user-agent logging.
internal/​usage/​testdata/​scenarios/​mixed-user-agents/​report.md Records partially identified client output.
internal/​usage/​testdata/​scenarios/​hostile/​scenario.json Configures malformed-record coverage.
internal/​usage/​testdata/​scenarios/​hostile/​rows.json Records malformed-input row baselines.
internal/​usage/​testdata/​scenarios/​hostile/​report.md Records malformed-input report output.
internal/​usage/​testdata/​scenarios/​empty/​scenario.json Configures an empty-log scenario.
internal/​usage/​testdata/​scenarios/​empty/​report.md Records the empty-period message.
internal/​usage/​testdata/​scenarios/​before-user-agents/​scenario.json Simulates records predating agent logging.
internal/​usage/​testdata/​scenarios/​before-user-agents/​report.md Records historical-format output.
internal/​usage/​testdata/​README.md Explains fixture provenance and updates.
internal/​usage/​testdata/​networks/​peeringdb-net.json Supplies synthetic network classifications.
internal/​usage/​testdata/​networks/​ip2asn-v4.tsv Supplies synthetic address ownership ranges.
internal/​usage/​testdata/​entries/​typical.counters.json Supplies daily and hourly counter fixtures.
internal/​usage/​testdata/​entries/​empty.jsonl Supplies an empty access-log fixture.
internal/​usage/​sources.go Implements log and metrics readers.
internal/​usage/​sources_internal_test.go Tests paging, retries and metrics responses.
internal/​usage/​settings.go Defines and validates collector settings.
internal/​usage/​schema/​002_dashboard_queries.sql Defines dashboard views and aggregate queries.
internal/​usage/​schema/​001_tables.sql Defines usage, publication and state tables.
internal/​usage/​run.go Coordinates collection, backfill and reporting.
internal/​usage/​publishing.go Implements incremental registry catalogue reads.
internal/​usage/​publishing_internal_test.go Tests catalogue synchronization and pagination.
internal/​usage/​prototype_internal_test.go Replays prototype function expectations.
internal/​usage/​privacy_internal_test.go Checks outputs for sensitive fixture values.
internal/​usage/​networks_internal_test.go Tests network lookup, caching and settings.
internal/​usage/​golden_internal_test.go Checks report and row parity.
internal/​usage/​fixtures_internal_test.go Provides synthetic sources and fixture checks.
internal/​usage/​database_internal_test.go Provides isolated database test helpers.
internal/​usage/​classify.go Classifies clients, endpoints and request usage.
internal/​usage/​catalogue.go Resolves published names and package types.
internal/​usage/​aggregate.go Produces daily totals and breakdown rows.
go.mod Promotes two existing dependencies to direct use.
cmd/​usage-collector/​README.md Documents operation, settings and data handling.
cmd/​usage-collector/​main.go Adds CLI flags and collector startup.

Review effort: Balanced

Comment thread internal/usage/classify.go Resolved
Comment thread internal/usage/sources.go Resolved
… base

Address the review of the usage collector.

Privacy. The product name taken from a user agent is no longer stored
when it says who or where the client is: an IPv4 or IPv6 address (with
or without a port, also inside a longer word), a hardware address,
someone@somewhere, a host name with a private suffix, or a UUID or long
hexadecimal identifier. A fixed label is stored in its place and the
client counts as unnamed. The rule errs towards withholding. The privacy
test now checks the names taken out of user agents, not only whole user
agents.

Counter population. Access records for the gateway's two test hosts are
left out, in the log filter and again when records are read, because the
gateway's counters leave them out. A test fails if the hosts here and
the gateway's rule disagree.

Dashboard arithmetic.
- Shares in the listing_use and page_size dimensions are of listing
  traffic, and are now turned into volumes with the day's listing
  totals, in the view and in both functions.
- Cache and compression rates are combined across days and rows
  weighted by what they are rates of.
- The client that looked a server up most, and its share, are exact or
  empty: shown when every stored row behind a line has the same winner,
  empty when the rows disagree.
- A period that includes a day lacking what a figure is made of has no
  such figure, rather than one made of part of its days.

Schema. New columns arrive in an additive migration that also fills the
listing totals of days stored earlier from their endpoint shares. The
view and functions keep their names, arguments and result columns; the
view gains one column at the end. They move from a numbered file to one
that is applied again whenever its content changes.

The golden files change where the prototype was wrong. The same
corrections were applied to the prototype in memory to produce them, and
the fixture notes list each deliberate difference.

Co-authored-by: Copilot App <[email protected]>
@rdimitrov
rdimitrov merged commit 77c7a9b into main Nov 20, 2026
18 checks passed
@rdimitrov
rdimitrov deleted the rdimitrov-usage-collector-go branch November 20, 2026 20:25
rdimitrov added a commit that referenced this pull request Nov 20, 2026
Runs the usage collector (#1877) once a day in the hosted clusters and
shows what it records in Grafana, on top of the dashboards (#1875) and
alert rules (#1876) that are now provisioned from this repository.
Everything is created by Pulumi behind one setting,
`mcp-registry:usageCollector`.

This pull request sets it to `"true"` in staging, so **merging deploys
all of it to staging**. Production has no setting and is not changed;
`deploy/Pulumi.gcpProd.yaml` is untouched.

## The setting

| Value | Effect |
|---|---|
| not set | Nothing is created and nothing changes. Production today. |
| `"true"` | Everything in the next section. |
| `"false"` | Retired: the workload is removed and Grafana deletes the
data source, dashboards and alert rules, which it would otherwise keep.
The stored history and its backups stay. |

It is only accepted on the hosted stacks with the standalone Gateway,
which produces the request counters the collector scales by.

## What staging gets on merge

- **Daily run:** CronJob `registry-usage-collector` in `monitoring`,
01:15 UTC. A run collects every missing day of the last 13, so a missed
run heals itself.
- **History:** database `registry_usage` on the existing `grafana-pg`
cluster, kept indefinitely.
- **Three confined database roles**, as CNPG `DatabaseRole` objects with
generated passwords. Neither CNPG `Cluster` object is modified.
  - `registry_usage_collector` owns the usage database.
  - `registry_usage_grafana` can only read what the dashboards query.
- `registry_usage_reader` reads the registry database through
`pg_read_all_data` and can write nothing. Today that database holds
`servers` and `schema_migrations`.
- **Google access:** `roles/logging.viewer` and a key for the existing
`registry-usage-reader` service account. The account itself is not
managed.
- **Grafana:** a read-only PostgreSQL data source and the "Registry
usage" and "Registry publishing" dashboards. Grafana restarts once to
read them.
- **Two alert rules** (a missed day; the log-based estimate drifting
more than 10% from the gateway counters), only where
`mcp-registry:alertDiscordWebhook` is set too. Staging does not have it,
so staging gets no rules yet.
- **Backup:** see below.
- **Image:** `ghcr.io/modelcontextprotocol/registry-usage-collector`,
built in `deploy-staging.yml` in a job of its own, which the deploy does
not wait for, and in `release.yml`.

A run cannot hold up a deployment or the registry. Pulumi waits for none
of the jobs, the volume or the database objects. The pod has small
requests, hard limits and a priority below every other workload. It
reads the registry database over one connection in short read-only
transactions.

`deploy/README.md` has a new "Usage collector" section covering all of
this.

## Backup of the history, and its restore

`grafana-pg` is a single instance, so CronJob
`registry-usage-history-backup` archives the usage database every day at
03:30 UTC, the same way the registry's backup works: `pg_dump`, read
back and checksummed, then Restic with 28 daily snapshots.

- It goes to a bucket of its own,
`mcp-registry-<environment>-usage-backups`. The collector's service
account is granted that bucket and no other, so it cannot reach the
registry's backups.
- The archive is made by `registry_usage_collector` in read-only
transactions. No credential of Grafana's own database is used.
- Retiring the collector keeps the bucket and its snapshots, and Pulumi
never deletes the bucket.
- The Restic password is a fixed, documented string, not a secret: a
generated one would be lost with the Pulumi state that held it. The job
creates its repository if there is none. A failed backup is not alerted
on.
- **Restore:** fetch the archive with Restic, then `pg_restore --clean`
into `registry_usage` as its owner. It works on an empty database and on
one the collector has written to since. The collector then collects
whatever of the last 13 days is missing. The commands are in the README
under "Restoring the history".

## Steps by hand

1. After the first staging build, make the GHCR package
`registry-usage-collector` public. A new package is private and the
clusters pull without credentials. Until then the daily job cannot
start; nothing else is affected.
2. After the deploy, start the first run instead of waiting for 01:15
UTC: `kubectl -n monitoring create job
--from=cronjob/registry-usage-collector usage-first-run`. It takes about
an hour.
3. Optional: set `mcp-registry:usageCollectorOrganizationAliases` as an
encrypted secret.

## Where the staging deploy itself could fail

A failed Pulumi run in staging blocks later staging deploys, so these
are the points I could not rule out locally:

- **Grafana must become ready.** Pulumi waits for the chart's
Deployment. The data source and dashboard provider files load on Grafana
12.4.14 locally, but with SQLite as Grafana's own database; staging's
uses PostgreSQL.
- **The `random` provider plugin.** Pulumi fetched it on demand locally
with 3.272. CI uses 3.188.0, which obtains the gcp and kubernetes
plugins the same way.
- **Applying a saved plan with values unknown at preview** (three
passwords and the key). The staging restore's key-to-Secret flow has the
same shape and works.
- **The new bucket.** Its name is free today, and the deploy account
holds `roles/storage.admin`.

Already checked against staging: a server-side dry run of the three
`DatabaseRole` objects and the `Database` was accepted, with nothing
persisted.

Not waited for, so they cannot fail the deploy: the two CronJobs, the
cache volume and CNPG's reconciliation. If the organization does not let
Actions create a new package, the image job fails and the deploy still
runs.

## How it was checked

- `go -C deploy test ./...`, with new tests for all three states of the
setting, credential handling, role confinement and the backup; the
deploy script tests; the collector's tests.
- On a local PostgreSQL 17, with the roles shaped as `DatabaseRole`
creates them, the collector's code as merged in #1877 created its
schema, read a registry database through the read-only role and stored
13 days from its synthetic fixtures. 35 checks confirm what each role
can and cannot do.
- Grafana 12.4.14 was started with the files this code generates. All 52
panel queries run as the read-only role for day, week and month; both
rules evaluate correctly for fresh, stale, drifted, empty and
missing-table data; `"false"` removes the data source, both dashboards
and both rules and nothing else.
- The backup's two scripts ran against that database. A snapshot
restored into an empty database was identical to the original, and the
dashboards and the collector worked on it.
- The generated objects pass strict schema validation against both
clusters' published schemas.
- The collector image builds with ko for amd64 and arm64.

## What only staging can show

- How the CNPG operator reconciles the `DatabaseRole` and `Database`
objects, including a password change and retirement.
- Key creation, the IAM grant, the new bucket and its grants with the
real deploy account.
- The collector in the cluster: image pull, egress to Google and the two
public reference sites, the cache volume, memory on real data.
- Restic against Google Cloud Storage with the service account key, and
`pg_dump` from the job's pod.
- Whether CNPG recreates the database and roles after `grafana-pg` is
rebuilt, which the restore relies on.
- The real one-hour and two-hour alert timings.

---------

Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants