📚 Consolidate backend metrics guidance

Keep collector wiring, HTTP sampling, and log counter behavior in one
memory. Link it from the backend index and existing sections.

AI-assisted-by: gpt-6.2-sol
This commit is contained in:
Andrey Antukh 2026-11-23 21:55:49 +00:00
parent 0cffbb4816
commit 4483d4274c
4 changed files with 24 additions and 12 deletions

View File

@ -4,7 +4,8 @@ JVM Clojure backend. Start in `app.main` for Integrant wiring, `app.rpc.commands
## Focused memories
- RPC wrapper order, config, HTTP middleware and metrics: `mem:backend/subtleties`.
- RPC wrapper order, config and HTTP middleware: `mem:backend/subtleties`.
- Metric recording, HTTP and JVM sampling, and log-derived counters: `mem:backend/metrics`.
- Transaction ownership, after-commit callbacks and advisory locks: `mem:backend/db-transactions`.
- RPC concurrency limit declarations, acquisition order and queue diagnosis: `mem:backend/rpc-concurrency`.
- Injected component schemas and startup assertion failures: `mem:backend/integrant-schemas`.

View File

@ -21,4 +21,4 @@
- Do not infer the owner, resource or expiry from business params. A public job belongs to its profile; an absent job and another profile's job both answer `not-found`. Registry metadata such as job family and routing is interpreted by consumers, not the substrate. Family quotas count live jobs from registered definitions, not a fixed list of names.
- Internal retention and user expiry are separate. Job GC must retire a row and arrange cleanup of its resource together; a bare delete would cascade events without touching the resource. Use the bucket's owner and lifetime rules in `mem:backend/storage`.
- Metric definitions live in `app.jobs.metrics`. Keep labels bounded (no IDs, payloads or exception text). A histogram's `_count` is the counter for that event; dispatch and claim measure different events. Claim wait includes the dispatcher gap, not just time in Redis. Use SQL for backlog rather than adding a gauge to the write path; debounce does not reset `created_at`.
- Record SQL-backed metrics via `db/after-commit` inside the writing transaction. Wire a metrics instance into the cfg before writing: a missing dependency discovered only in a callback may be swallowed. A user-owned event writer also needs a message bus on its cfg.
- Record SQL-backed metrics inside the writing transaction; see `mem:backend/metrics`. Wire a metrics instance into the cfg before writing: a missing dependency discovered only in a callback may be swallowed. Profile-job events require a message bus before insertion so they do not lose their notification. Jobs resolve it from the cfg; `app.msgbus` operations take the instance itself.

View File

@ -0,0 +1,18 @@
# Backend metrics
## Recording
- Start at `app.metrics` for collectors and sampling, `app.main/default-metrics` for backend metric definitions, and `app.jobs.metrics` for job metrics. For queue signals see `mem:backend/rpc-concurrency`.
- `app.metrics/run!` catches failures while recording on a collector, not missing-instance errors: validation and collector lookup happen outside that guard. Wire the instance into the component and use `app.metrics/instance` when resolving it from a cfg. Register SQL-backed metrics inside the writing transaction via `db/after-commit`; see `mem:backend/db-transactions`.
## HTTP and process sampling
- A component owns its `app.metrics/create-sampler` scheduler and stops it on halt. A failed sample must not cancel future samples. Start at `app.http/sample-http-metrics`; listener stats depend on Yetti's `:server/statistics` option.
- XNIO's negative samples mean missing data, not zero. Use worker pool size for retained threads: the busy count can stay at zero while threads are blocked in CLIMIT. Undertow exposes absolute totals; publish positive deltas and advance the baseline even on reset so the next sample counts correctly.
- `app.metrics/create-registry` calls `DefaultExports/register`. Keep `jdk.management` in the backend runtime image: without it, reflective OS MXBean lookups can fail silently and `process_*` collectors disappear. See `backend-tests.metrics-test`.
- Body parsing happens before endpoint instrumentation. Count malformed bodies where middleware classifies the failure, using the service's own collector. Do not expect the endpoint counter to include requests rejected before dispatch.
## Log-derived counters
- `app.loggers.metrics/reporter` counts only application `warn`, `error` and `fatal` records that pass through `app.common.logging`; it is not a count of all Loki records. Metric `level` labels are lowercase, unlike Loki's uppercase levels. Keep `logger` values fixed rather than deriving them from request data.
- The watcher runs inside the logging path. Never let a recording failure interrupt logging or log recursively from the watcher itself. A flat counter alone is not proof that no errors occurred.

View File

@ -40,22 +40,15 @@
## HTTP server self-metrics
- `app.http` enables Undertow connection statistics via the yetti option `:server/statistics` (requires yetti ≥ v11.11, which exposes it; before the patch `ListenerInfo#getConnectorStatistics` returned `nil`).
- `app.metrics/create-sampler` holds the sampler shape: a single daemon `px/scheduled-executor` thread with a self-rescheduling `px/schedule` chain, so a failing sample never cancels the next one; the owner starts it in `ig/init-key` and stops it with `px/shutdown-now` in its `halt-key!`. Http and CLIMIT both sample every 15 s.
- `app.http` uses it to publish worker and listener state: `penpot_http_worker_queue_size`, `penpot_http_worker_pool_size`, `penpot_http_worker_max_pool_size`, `penpot_http_connector_active_connections`, `penpot_http_connector_requests_total`, `penpot_http_connector_errors_total`. Definitions live in `app.main/default-metrics`. The xnio busy-thread count is not published: it reads 0 with threads blocked inside a limiter, which is why it was deleted.
- The xnio worker MXBean can return transient `-1` (e.g. on the queue or the pool size); negative samples are discarded (gauge keeps its previous value). Undertow exposes absolute request/error totals, so the sampler keeps a watermark atom and publishes deltas; a counter reset (decreasing totals) skips the negative delta and moves the watermark forward.
- The `process_*` families (`process_open_fds`, `process_max_fds`, `process_cpu_seconds_total`, …) come from the prometheus client `StandardExports`, registered by `app.metrics/create-registry`. They read the OS MXBean reflectively and need the `jdk.management` module: on a pruned `jlink` JRE the MXBean is `sun.management.BaseOperatingSystemImpl`, the getters throw `NoSuchMethodException` and `StandardExports#collect` swallows it, so those families silently vanish from `/metrics`. `docker/images/Dockerfile.backend` keeps `jdk.management` in the `--add-modules` list, and `backend-tests.metrics-test` pins the contract.
- HTTP listener and worker sampling, missing samples and JVM runtime requirements: `mem:backend/metrics`.
## Metrics recording
- `app.metrics/run!` is safe by default: a recording failure never throws (a metrics bug must not change the behavior of the measured operation). The first failure per metric id logs at `warn`, later ones at `debug`. The `instance` precondition is a plain assert (the backend enables `:backend-asserts`), and the collector lookup sits outside the recording guard, so a missing instance fails hard even when asserts are disabled. `::mtx/metrics` is required by the storage, s3-backend, db-pool and jobs APIs; jobs helpers never silently skip a missing metrics instance. The resolver is `app.metrics/instance` and it raises, unlike `run!`.
- `app.msgbus` (`pub!`, `sub!`, `purge!`) keeps taking the **instance** on purpose: msgbus is what produces it, and `app.rpc.notifications` already shows the caller passing a cfg. `app.jobs` resolves `::mbus/msgbus` from the cfg internally, and `insert-event` keeps its explicit pre-insert check so a profile job never loses its notification.
- Register SQL-backed metrics via `app.db/after-commit` inside the writing transaction; see `mem:backend/db-transactions`.
- `penpot_http_malformed_requests_total` (counter, no labels) counts requests whose body the parser could not read. `app.http.middleware/wrap-parse-request` emits it where it classifies the error, so the instance travels as a middleware argument (`[mw/parse-request (::mtx/metrics cfg)]`) and each service declares the definition with its own prefix (nexus: `nexus_http_malformed_requests_total`). The per-endpoint request counters of nexus do not count these requests: they sit inside the parse middleware, so the failure happens before them.
- Collector failures, metrics wiring and transaction boundaries: `mem:backend/metrics`.
## Log-derived metrics
- `app.loggers.metrics/reporter` counts the log records the application emits and publishes them as `penpot_log_events_total{logger, level}` (counter), so the error panels do not have to count text in Loki. It is a component that hooks `add-watch` on `app.common.logging/log-record`, like `app.loggers.database`, but with no thread and no channel: the increment is in memory, so it goes straight in the watcher. Only `warn`, `error` and `fatal` are counted, and only the records that go through `app.common.logging` (the application's own logs; a library writing straight to log4j2 is not counted, and today that is one line in a thousand). The body of the watcher is wrapped in a `try/catch` that swallows the error on purpose: the watcher fires from the `swap!` of the log record, inside the logging path. With `::l/sync?` (`app.binfile.v1`, `app.msgbus`) an exception there would reach whoever was logging; on the async path it escapes to the logging executor worker, whose trace goes to the thread's uncaught handler -- outside the application's logging -- and the pool replaces the dead worker, so logging continues and that line is lost. The catch also makes a publication that fails every time invisible: `penpot_log_events_total` stays flat and nothing is written about it. The published `level` values are lowercase (`warn`), unlike the `level` label of the Loki logs (`ERROR`), so a panel that moves from one source to the other has to change it. Cardinality is `logger` (fixed names taken from the code) times `level`; a logger built from a dynamic value would break that.
- What the reporter counts and how its labels differ from Loki: `mem:backend/metrics`.
## Storage and media