Repository navigation
Add usage collector for the hosted registry - #1877
Merged
Merged
Conversation
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]>
Contributor
There was a problem hiding this comment.
🟡 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
… 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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


What this adds
cmd/usage-collectoris 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 ininternal/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:
It can also write the day's report as Markdown.
cmd/usage-collector/README.mdis the operator's guide.Behaviour worth reviewing
--daycollects every day in the look-back window that is not stored. A missed night or the first backfill needs no manual job.serverstable, only the versions changed since the last run, in pages of 500 inside short read-only transactions with a statement timeout. The registry movesis_latestbetween versions without touchingupdated_at, so the reader also refreshes that flag for the servers it sees change.Settings
All settings are
USAGE_COLLECTOR_*environment variables. Nothing about a particular environment is built in.GCP_PROJECT,CLUSTER_NAME,LOG_NAMESPACE,LOG_CONTAINERGCP_QUOTA_PROJECTMETRICS_URLDATABASE_URLREGISTRY_DATABASE_URLREADER_ROLEORGANIZATION_ALIASESLOOKBACK_DAYS,MAX_RECORDS,DOLLARS_PER_GIB,CACHE_DIROnly hosting providers are recognised by name in the code. Organizations are never built in; they come from
ORGANIZATION_ALIASES.Privacy
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.
internal/usage/testdata/README.mdlists 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.Because byte-identical output depends on summation order and tie-breaking,
pycompat.goand parts of the aggregation reproduce Python semantics on purpose.internal/usage/testdata/README.mdexplains 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/usagepasses with-race. Statement coverage ofinternal/usageis about 90%.cloud.google.com/go/authandgolang.org/x/textwere already required indirectly and are now direct.The database tests need PostgreSQL on
localhost:5432, as the existing unit tests do.Not verified
serverstable 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.