Observability

Observability

This guide covers monitoring and observability for self-hosted Huitzo deployments, including Prometheus metrics, logging, and alerting.

Built-in Metrics Endpoint

Huitzo exposes metrics in Prometheus format at /metrics. The endpoint is token-gated and fails closed: it requires the HUITZO_METRICS_TOKEN bearer token, and when that variable is unset the endpoint is disabled and returns 503 (it never serves metrics unauthenticated). Set the token on every deployment you intend to scrape:

# Backend container environment
HUITZO_METRICS_TOKEN=<a long random secret>

A deployment that does not scrape metrics can leave it unset; the backend logs a startup warning in non-debug mode when it is missing, so a dark /metrics is visible in the boot logs rather than discovered via a failed scrape.

Scrape it with the bearer token:

# pseudocode: the source-built stack, where the backend's port is published
curl -H "Authorization: Bearer $HUITZO_METRICS_TOKEN" http://<backend host>:<port>/metrics

On a deployment installed with install.sh, the first run generates HUITZO_METRICS_TOKEN in .env with the other secrets and the compose passes it to the backend. The backend port is not published and the HTTPS proxy does not route /metrics, so scrape http://backend:8000/metrics from a container attached to the compose network (huitzo-customer_huitzo-network).

An .env written before the token was generated has no HUITZO_METRICS_TOKEN line, and re-running install.sh does not add one (it never rewrites an existing .env). Generate a value with python3 -c 'import secrets; print(secrets.token_hex(32))', add HUITZO_METRICS_TOKEN=<value> to .env, then run docker compose up -d (Metrics token on an existing install).

Example output:

# HELP huitzo_command_duration_seconds Command execution duration
# TYPE huitzo_command_duration_seconds histogram
huitzo_command_duration_seconds_bucket{namespace="analytics",command="analyze",le="0.1"} 12
huitzo_command_duration_seconds_bucket{namespace="analytics",command="analyze",le="0.5"} 45
huitzo_command_duration_seconds_bucket{namespace="analytics",command="analyze",le="1.0"} 78
...

# HELP huitzo_command_total Total commands executed
# TYPE huitzo_command_total counter
huitzo_command_total{namespace="analytics",command="analyze",status="success"} 156
huitzo_command_total{namespace="analytics",command="analyze",status="error"} 3

Key Metrics

Command Execution

Metric Type Labels Description
huitzo_command_duration_seconds histogram namespace, command Command execution duration
huitzo_command_total counter namespace, command, status Total commands executed
huitzo_active_tasks gauge queue Currently running tasks per queue
huitzo_queued_tasks gauge queue Tasks waiting in queue

Storage Operations

Metric Type Labels Description
huitzo_storage_operations_total counter operation, status Storage operations (save, get, delete)
huitzo_storage_operation_duration_seconds histogram operation Storage operation latency

Storage operation counts and latency are exported; there is no huitzo_storage_bytes_total (byte volume) series.

System Health

Metric Type Labels Description
huitzo_http_requests_total counter method, endpoint, status HTTP request count
huitzo_http_request_duration_seconds histogram method, endpoint HTTP request latency

Liveness and readiness are exposed via the health endpoints, not as Prometheus gauges — there is no huitzo_worker_status or huitzo_database_connections series.

Billing & Funnel

Metric Type Labels Description
huitzo_product_events_total counter event_type Product events stored in product_events (signup, paid_signup, checkout_abandoned, command_executed, dashboard_*, …). Named huitzo_billing_events_total before Core migration 0053
huitzo_product_events_dropped_total counter event_type Product events lost because the insert failed. The request that emitted the event still succeeds, so this counter and the backend's product event dropped: <type> insert failed ERROR line are the only signs. Alert on any increase

Cloud-LLM usage and cost are recorded by the metering system, not as Prometheus counters. The one huitzo_llm_* series is the reservation breaker's state, below. Local-AI inference is instrumented separately (huitzo_local_ai_*).

Studio runner channel

Metric Type Labels Description
studio_ingest_rejected_total counter reason Runner agent events the Hub ingest guard dropped because it could not prove them metadata-only. reason is a fixed tag: seq-negative, kind-not-allowlisted, richer-kind-requires-opt-in, payload-not-metadata-only. Each drop also logs one studio.ingest_rejected warning with the event kind and reason, never the payload

LLM Metering

Metric Type Labels Description
huitzo_llm_reservation_breaker_open gauge (none) 1 while this process's LLM reservation circuit breaker is open: platform-key LLM calls get HTTP 503 after repeated failures to reach the credit ledger, apart from a retry probe every 30 seconds or sooner. Else 0

Each API and worker process has its own breaker, so the gauge is per process. Only the backend's /metrics is scraped today; worker processes are not (#1881). A gauge at 1 returns to 0 when an LLM call in that process writes a credit hold again, or when the process restarts. With billing off, the default for self-hosted installs, no reservation is attempted, so no failure is recorded and the gauge stays 0.

Ledger invariant check (SaaS)

Exported only by a backend with the SaaS extension mounted.

Metric Type Labels Description
huitzo_ledger_invariant_last_run_timestamp_seconds gauge - Unix time the latest invariant run finished; 0 until one is recorded
huitzo_ledger_invariant_last_run_violations gauge - Violations the latest run found
huitzo_ledger_invariant_last_run_failed_checks gauge - Passes and checks of the latest run that failed
huitzo_ledger_invariant_last_run_status gauge status 1 for the latest run's status (ok, violations, failed, skipped), 0 for the others
huitzo_ledger_invariant_gauges_refreshed_timestamp_seconds gauge - Unix time this backend last read the run record successfully; 0 if it never has. The four gauges above are only as fresh as this

Scrape-time refresh

The Celery worker exposes no /metrics endpoint, so a value a worker task produces cannot be a worker-side gauge. The ledger invariant gauges are therefore set by the backend: the worker writes the run to ledger_invariant_runs, and the backend reads the latest row just before it renders each scrape. The read is cached for 60 seconds, bounded by a 2-second timeout, and never fails the scrape: when it fails, the gauges keep their last values, the next attempt waits 30 seconds (so a database that is down does not cost every scrape the timeout), and huitzo_ledger_invariant_gauges_refreshed_timestamp_seconds stops moving, which the HuitzoLedgerInvariantGaugesStale rule below fires on. An extension registers such a refresher when it mounts (register_scrape_refresher in metrics.py; the gauges are in invariant_run_metrics.py).

Prometheus Configuration

Basic Setup

Add Prometheus to your docker-compose.yml:

# docker-compose.yml
services:
  # ... existing services ...

  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.retention.time=15d'

volumes:
  prometheus_data:

Prometheus Configuration

# prometheus.yml
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'huitzo'
    static_configs:
      - targets: ['backend:8000']  # the backend's container port on the Docker network
    metrics_path: /metrics
    # /metrics is token-gated (503 without it). The shipped stack presents the
    # token from a mounted file (git-ignored, per-host, mode 0644) — Prometheus
    # does not expand env vars in scrape credentials. The backend must receive the
    # SAME token via HUITZO_METRICS_TOKEN (a line in .env, which app.env carries
    # to the backend) + docker-compose.observability.yml (the Prometheus file mount).
    authorization:
      type: Bearer
      credentials_file: /etc/prometheus/metrics-token

  - job_name: 'huitzo-workers'
    static_configs:
      - targets: ['worker:9100']  # If worker exposes metrics

  - job_name: 'redis'
    static_configs:
      - targets: ['redis:9121']  # Redis exporter

  - job_name: 'postgres'
    static_configs:
      - targets: ['postgres:9187']  # Postgres exporter

Adding Exporters

For database and cache metrics, add exporters:

# docker-compose.yml additions
services:
  redis-exporter:
    image: oliver006/redis_exporter:latest
    environment:
      - REDIS_ADDR=redis://redis:6379
    ports:
      - "9121:9121"

  postgres-exporter:
    image: prometheuscommunity/postgres-exporter:latest
    environment:
      - DATA_SOURCE_NAME=postgresql://huitzo:${POSTGRES_PASSWORD}@postgres:5432/huitzo?sslmode=disable
    ports:
      - "9187:9187"

Grafana Dashboard

Setup

Add Grafana to your stack:

# docker-compose.yml
services:
  grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
      - GF_USERS_ALLOW_SIGN_UP=false
    volumes:
      - grafana_data:/var/lib/grafana
      - ./grafana/dashboards:/etc/grafana/provisioning/dashboards
      - ./grafana/datasources:/etc/grafana/provisioning/datasources

volumes:
  grafana_data:

Datasource Configuration

# grafana/datasources/prometheus.yml
apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true

Dashboard JSON

Create a Huitzo dashboard at grafana/dashboards/huitzo.json:

{
  "dashboard": {
    "title": "Huitzo Platform",
    "panels": [
      {
        "title": "Command Execution Rate",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(huitzo_command_total[5m])",
            "legendFormat": "{{namespace}}.{{command}} - {{status}}"
          }
        ]
      },
      {
        "title": "Command Duration (p95)",
        "type": "graph",
        "targets": [
          {
            "expr": "histogram_quantile(0.95, rate(huitzo_command_duration_seconds_bucket[5m]))",
            "legendFormat": "{{namespace}}.{{command}}"
          }
        ]
      },
      {
        "title": "Active Tasks",
        "type": "gauge",
        "targets": [
          {
            "expr": "sum(huitzo_active_tasks)",
            "legendFormat": "Active"
          }
        ]
      },
      {
        "title": "Error Rate",
        "type": "graph",
        "targets": [
          {
            "expr": "sum(rate(huitzo_command_total{status=\"error\"}[5m])) / sum(rate(huitzo_command_total[5m])) * 100",
            "legendFormat": "Error %"
          }
        ]
      },
      {
        "title": "Storage Operations",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(huitzo_storage_operations_total[5m])",
            "legendFormat": "{{operation}}"
          }
        ]
      }
    ]
  }
}

AlertManager Rules

Setup

Add AlertManager:

# docker-compose.yml
services:
  alertmanager:
    image: prom/alertmanager:latest
    ports:
      - "9093:9093"
    volumes:
      - ./alertmanager.yml:/etc/alertmanager/alertmanager.yml

Alert Rules

Create alert rules in prometheus-rules.yml:

# prometheus-rules.yml
groups:
  - name: huitzo-alerts
    rules:
      # High error rate
      - alert: HuitzoHighErrorRate
        expr: |
          sum(rate(huitzo_command_total{status="error"}[5m]))
          / sum(rate(huitzo_command_total[5m])) > 0.05
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "High command error rate"
          description: "Error rate is {{ $value | humanizePercentage }} (threshold: 5%)"

      # Command latency spike
      - alert: HuitzoHighLatency
        expr: |
          histogram_quantile(0.95, rate(huitzo_command_duration_seconds_bucket[5m])) > 30
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "High command latency"
          description: "p95 latency is {{ $value | humanizeDuration }}"

      # Queue backup
      - alert: HuitzoQueueBacklog
        expr: huitzo_queued_tasks > 100
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "Task queue backlog"
          description: "{{ $value }} tasks waiting in {{ $labels.queue }} queue"

Worker liveness and database reachability are surfaced by the health endpoints (/health, /health/live, /health/ready), not by Prometheus gauges — alert on those probes (or your orchestrator's health checks) rather than on a huitzo_worker_status / huitzo_database_connections series, which the backend does not emit.

Ledger invariant alerts

The repository ships the rules for the nightly money check in deploy/compose/observability/rules/ledger-invariants.yml. The shipped stack loads every file in that directory: docker-compose.observability.yml mounts observability/rules/ at /etc/prometheus/rules/ and prometheus.yml lists rule_files: /etc/prometheus/rules/*.yml.

Alert Fires when Severity
HuitzoLedgerInvariantViolated The latest run found one or more violations critical
HuitzoLedgerInvariantRunFailed The latest run has a failed pass or check, or its status is failed or skipped critical
HuitzoLedgerInvariantRunMissing The latest run finished more than 26 hours ago critical
HuitzoLedgerInvariantGaugesStale The backend has not read the run record for 15 minutes, so the other rules are judging old values warning
HuitzoLedgerInvariantNeverRan The timestamp gauge has been 0 for an hour: no run has ever been recorded, or the backend cannot read the run record. Expected once, between the first deploy that has the run record and the first run; run the task to clear it warning

What each means and what to do: Ledger invariants runbook.

A rule that fires notifies nobody by itself. It shows on Prometheus's Alerts page and in Grafana. To be paged, add an alerting: block pointing at an Alertmanager (below) or a Grafana contact point. A deployment that keeps its Prometheus configuration outside this repository must do both steps there: mount the rule file and add the rule_files entry, then route the alerts. Until then the channels that work with no extra wiring are the admin Overview panel and the staff email (Credits: invariant runs).

Database backup alerts

The rules for Hub-managed database backups ship in deploy/compose/observability/rules/db-backups.yml, loaded the same way. Each rule and the metric behind it is specified in admin console §5.11.14. The backup sidecar serves its metrics on its own /metrics; the denied-request counter is the backend's. The shipped stack loads these rules but does not scrape the sidecar yet (the deployment adds that job, B6/B7): until it does, the sidecar rules never fire. A textfile exporter (HUITZO_BACKUP_METRICS_TEXTFILE) carries only the gauges, so the rules on counters and on the schedule gauges need the /metrics scrape. Staff events (a download ticket, a delete, a settings change, the schedule turned off) also email HUITZO_PLATFORM_STAFF_EMAILS, best effort.

Alert Fires when Severity
HuitzoBackupFailed A backup run failed in the last 15 min critical
HuitzoBackupStale The newest verified scheduled backup is older than twice the last enabled interval critical
HuitzoBackupScheduleOff The schedule has been off for 5 min warning
HuitzoBackupIntegrityFailure A verify found a hash or signature mismatch critical
HuitzoBackupUntrustedFile An unsigned or unknown-signer backup is in the directory critical
HuitzoBackupRetentionFloorHit Retention was held at an env floor in the last hour warning
HuitzoBackupRetentionUnexpectedCount More than 5 retention deletions within 15 min critical
HuitzoBackupDownloadCompleted A download stream ended warning
HuitzoBackupDeniedRequests The backup routes refused a request (401, 403, 429) warning

HuitzoBackupStale compares two series with different labels: the age carries trigger, the interval series has none. Its expression puts the matching modifier on the comparison (> ignoring(trigger) 2 * …); a modifier on the scalar 2 * is dropped and the rule can never fire. The promtool unit tests in deploy/compose/observability/rules-tests/db-backups.test.yml replay the staging case (a 900 s interval, the newest backup 2,254 s old). The test.yml test job runs promtool check rules on every rule file and these unit tests, with a checksum-pinned promtool of the release the observability compose runs (a test keeps the two versions equal), on any change to the rules, that compose file or the backend; test_backup_docs_and_topology.py also checks the expression shape. To run them locally:

promtool test rules deploy/compose/observability/rules-tests/db-backups.test.yml
# or, without a local promtool:
docker run --rm -v "$PWD/deploy/compose/observability:/o:ro" -w /o \
  --entrypoint promtool prom/prometheus test rules rules-tests/db-backups.test.yml

AlertManager Configuration

# alertmanager.yml
global:
  smtp_smarthost: 'smtp.example.com:587'
  smtp_from: '[email protected]'
  smtp_auth_username: '[email protected]'
  smtp_auth_password: 'password'

route:
  group_by: ['alertname']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 1h
  receiver: 'email-notifications'

receivers:
  - name: 'email-notifications'
    email_configs:
      - to: '[email protected]'

  - name: 'slack-notifications'
    slack_configs:
      - api_url: 'https://hooks.slack.com/services/xxx/xxx/xxx'
        channel: '#alerts'

Structured Logging

Studio LLM refusal logs

A Studio stage refused by the LLM seam writes one line named for the stage: studio_llm_refusal (CLARIFY), specify_llm_refusal (SPECIFY, written by the worker), decompose_llm_refusal and decide_llm_refusal. Every one carries:

Field Meaning
kind router (no route resolves, or a transient provider failure: 5xx, 429, 408), provider_rejected (the route resolved and the provider answered another 4xx, or the model answered and stopped without a result: see stop_reason), budget, input_too_large, and per stage scope / plan_scope / unknown
stage, profile the orchestration stage (CLARIFY_TRIGGER, SPECIFY, DECOMPOSE, DECIDE) and the profile the policy maps it to
provider, model, provider_status the provider's own LLMError fields, when a provider answered; null otherwise
stop_reason refusal (the model declined the request) or max_tokens (it reached its output-token ceiling before finishing) when the model answered with HTTP success and no usable result; null otherwise. provider_status is null on such a line
exc_type, error_message the refusal and its message
cause_type, cause_message the wrapped provider/router error and its message (provider body included)
intent_id / plan_id / spec_job_id, tenant_id what was refused, for whom

Credential-shaped text (sk-… keys, Bearer and Basic credentials, URL query credentials and userinfo, api_key=/authorization:/password values) is replaced with [REDACTED] and the message is then cut to 1000 characters; prompts are never logged. router and provider_rejected are warnings, unknown an error, the rest info. A provider_rejected refusal is answered 502 by the API (SPECIFY: written to the spec job's error_detail) so it is never read as "no model route resolves".

Log Configuration

# Environment variables (all backend settings use the HUITZO_ prefix)
HUITZO_LOG_LEVEL=INFO         # DEBUG | INFO | WARNING | ERROR | CRITICAL
HUITZO_LOG_FORMAT=json        # json | text
HUITZO_LOG_OUTPUT=stdout      # stdout | file
HUITZO_LOG_FILE_PATH=/var/log/huitzo/app.log

Log level (HUITZO_LOG_LEVEL)

HUITZO_LOG_LEVEL sets the effective root logging level for the backend. It is read by the application Settings (Pydantic, HUITZO_ env prefix) and applied when logging is configured at startup.

  • Default: INFO.
  • Accepted values: DEBUG, INFO, WARNING, ERROR, CRITICAL (case-insensitive — debug and DEBUG are equivalent). Any other value is rejected at boot, so a typo fails fast instead of silently logging at the wrong verbosity.
  • Interaction with HUITZO_DEBUG: debug mode implies maximum verbosity, so when HUITZO_DEBUG=true the effective level is forced to DEBUG regardless of HUITZO_LOG_LEVEL. Outside debug mode, HUITZO_LOG_LEVEL is honored verbatim.
Environment Recommended HUITZO_LOG_LEVEL
Production WARNING (or INFO for richer request traces)
Staging INFO
Development DEBUG

Earlier releases shipped unprefixed LOG_LEVEL, LOG_FORMAT, LOG_OUTPUT, and LOG_FILE_PATH variables in the compose files and .env examples that the backend never read — every backend setting binds under the HUITZO_ prefix, so log verbosity and formatting were untunable. Those dead variables have been replaced by their HUITZO_-prefixed equivalents (HUITZO_LOG_LEVEL, HUITZO_LOG_FORMAT, HUITZO_LOG_OUTPUT, HUITZO_LOG_FILE_PATH); there are no backward-compatible aliases.

Log Format

JSON logs include correlation IDs for request tracing:

{
  "timestamp": "2026-01-22T10:30:00.000Z",
  "level": "INFO",
  "logger": "huitzo.executor",
  "message": "Command completed",
  "correlation_id": "abc-123-def",
  "tenant_id": "org_456",
  "user_id": "user_789",
  "command": "analytics.analyze",
  "duration_ms": 1234,
  "status": "success"
}

Request correlation IDs (X-Request-ID)

Every inbound HTTP request is assigned a request correlation id by the backend request middleware. The id is bound into the structlog context under the request_id key, so every log line emitted while handling that request carries the same request_id — auth, licensing, metrics, route handlers, and errors alike. The same id is returned to the client as the X-Request-ID response header, so a client (or a log search) can pivot from a single response to the full server-side log trail.

Aspect Behavior
Response header X-Request-ID set on every response, including the auth/licensing/handler error responses produced inside the app.
Log binding key request_id (structlog contextvar, merged into every log line).
Inbound X-Request-ID Honored if present and valid; echoed back unchanged.
Validation Opaque token, ASCII [A-Za-z0-9._-], length ≤ 128. Anything else (missing, oversized, control characters, CRLF) is discarded and a fresh UUID4 is generated.
Generated id Random UUID4 — carries no secrets or PII.
Lifetime Bound at request entry, reset at request exit. Never leaks across requests sharing a worker.

The one response that does not carry the header is the last-resort 500 synthesized by the ASGI server's outermost error handler for an unhandled exception — that response is generated outside the correlation middleware. Every error response raised within the application (401/403/404/422/handled 500s) flows back through the middleware and carries the header.

Echoed inbound ids are sanitized before they reach the response header, so a hostile client cannot smuggle a second header (CRLF injection) through X-Request-ID. If you terminate TLS or route traffic through a reverse proxy (nginx, Caddy, a CDN), forward the inbound X-Request-ID request header to honor edge-assigned ids, and pass the X-Request-ID response header back through to clients.

Relationship to command correlation IDs

The request_id is per HTTP request. It is distinct from the per-command correlation_id (the id stored on each command_executions row and bound while a pipeline executes). The two coexist on the same log line — a command invoked over REST carries both request_id (the transport-level request) and correlation_id (the command execution). The request middleware only binds and resets request_id, so it never clobbers a command's correlation_id.

The example below is abridged to highlight the two ids; see the Log Format example above for the complete field set a log line carries.

{
  "timestamp": "2026-05-24T10:30:00.000Z",
  "level": "INFO",
  "logger": "huitzo.executor",
  "message": "Command completed",
  "request_id": "8f1c2e3a-...",
  "correlation_id": "abc-123-def",
  "tenant_id": "org_456",
  "status": "success"
}

To trace one request end-to-end: read X-Request-ID from the response (or the client's chosen inbound id), then search logs for that request_id (e.g. in a Loki-backed stack, {job="huitzo"} | json | request_id="<id>"; see Log Shipping).

Worker Logs

The Celery worker emits the same structured JSON as the API process. Both call the single configure_logging entrypoint in apps/backend/src/backend/observability/logging.py — there is no second logging configuration to keep in sync.

Celery installs its own root-logger handlers at worker startup by default, which would replace structlog and emit non-JSON lines. The worker prevents this by connecting receivers to two Celery signals (see apps/worker/src/worker/logging_config.py):

Signal Process Purpose
setup_logging main worker + Beat Connecting any receiver tells Celery to skip its own logging setup; the receiver installs structlog instead.
worker_process_init each pool child Re-applies structlog in every forked/spawned worker process.
# pseudocode — see apps/worker/src/worker/logging_config.py
on(setup_logging):       configure_logging(get_settings())   # blocks Celery's hijack
on(worker_process_init): configure_logging(get_settings())   # per child process

Per-task correlation. The execute_command task binds the request's correlation_id and tenant_id (along with the command namespace and the Celery task_id) into structlog's context variables for the duration of the task, so every log line a command emits is tagged and can be traced back to the originating request — matching the API's correlation behaviour. Context is cleared when the task finishes so it never leaks into the next task on a long-lived worker process.

Which extra= fields are rendered. Per-call extra= fields on a stdlib logger are rendered into the JSON line alongside the bound context, under two rules (add_first_party_extras in apps/backend/src/backend/observability/logging.py):

  • First-party loggers only. A record's extras are rendered when its logger is in one of this codebase's namespaces: backend, worker, receiver, huitzo_core, or an extension package huitzo_ext_*. A dependency's record (Celery, kombu, uvicorn, SQLAlchemy, httpx, a pack's own logger) renders its message and none of its extras. Celery attaches extra={"data": ...} holding the task's argument repr to its task-received, succeeded and failed lines, and uvicorn attaches a color_message copy of the line; neither reaches the output.
  • Existing keys win. An extra never replaces a key the line already has: event, level, logger, timestamp, and bound context such as request_id, correlation_id, tenant_id and task_id keep their value. An extra named after one of them is dropped from the line.

The email tasks that carry a raw token, a coupon code or a recipient address (password reset, email verification, coupon, welcome) are also enqueued with kwargsrepr="<redacted>", so Celery's task events and inspect output show the placeholder instead of the arguments.

Before huitzo#1979 extra= fields were dropped from every line in the backend and the worker; log_with_fields in apps/backend/src/backend/observability/logging.py additionally binds its fields as context variables for the one call and refuses a field named after a key the formatter writes itself. The ledger invariant lines (ledger: reconciliation incident: …) and the stuck-hold sweep's lines use it for their row ids (Credits: invariant runs).

The same HUITZO_LOG_FORMAT / HUITZO_LOG_OUTPUT environment variables documented under Log Configuration apply to the worker.

Quota-skipped scheduled dispatch. Because the Beat/worker processes expose no /metrics endpoint, a scheduled command refused by the monthly_command_cap gate (worker/tasks/scheduled.py, issues #1288/#1311) is surfaced as an ERROR log line starting with the stable, greppable key scheduled_dispatch_quota_skipped rather than as a Prometheus counter. The message itself is self-contained — schedule identity (the command namespace for manifest cron, the schedule id for a per-user ADR-030 schedule), the tenant id, and the quota numbers rendered as current/limit (e.g. 137/100, so real overage is visible, never clamped) — so the line reads on its own in a plain grep; the same values are also JSON fields of the line (tenant_id, namespace, quota_limit, quota_current, see the note above). A recurring skip means the tenant's scheduled workload is exhausting its monthly command cap; the remedies are raising monthly_command_cap on the tenant or pausing the offending schedule (see admin-console.md §5.6.3).

Unclaimed scheduled dispatch. A manifest-cron occurrence is enqueued only after its tracking row is inserted as the occurrence's claim (issue #1737). If that insert fails, the occurrence is skipped rather than risked twice, and the worker logs an ERROR line starting with the stable key scheduled_dispatch_claim_failed, naming the command namespace, the occurrence key and the tenant, followed by the database traceback. The key is cron-<opaque id>-<UTC minute>: the middle segment is derived from the pack and command name and matches no table's id. One line means one skipped run; a run of them means the worker cannot write to the database: it is unreachable, or it refuses the insert (read-only after a failover, a privilege or row-level-security change). The traceback names which. A duplicate tick that loses the claim is normal and logs at INFO with the key scheduled_dispatch_claim_lost; a steady stream of those means a second scheduler process is running (scaling.md#scheduled-dispatch-idempotency).

Log rotation and container log limits

Logs are bounded on two independent paths so neither can grow without limit: the file sink (when you log to a file) and the container log driver (what holds a service's stdout/stderr on disk).

File sink rotation. The default destination is stdout (LOG_OUTPUT=stdout), which the logging layer does not size-cap — the container driver below bounds that path. When you instead write to a file (LOG_OUTPUT=file), the backend and worker install a size-based rotating handler on LOG_FILE_PATH, so the file rolls over instead of growing forever.

Setting Env var Default Meaning
Max file size HUITZO_LOG_FILE_MAX_BYTES 52428800 (50 MiB) Roll over to a new file once the active log reaches this size.
Backups kept HUITZO_LOG_FILE_BACKUP_COUNT 5 Rotated files retained (app.log.1 … app.log.5); older ones are deleted.

With the defaults a file sink is capped at roughly 300 MiB per process (one active file plus five rotations). Rotation applies only to the file sink; the stdout JSON default is unchanged.

Multi-process caveat. RotatingFileHandler is not safe for multiple processes rotating the same file. A Celery worker running the default prefork pool configures one handler per pool child, so concurrent rollovers can drop lines or clobber backups at the rotation boundary (the ~300 MiB bound then holds only for a single-process sink). For a multi-process worker prefer the stdout default (bounded by the container driver below), give each process its own LOG_FILE_PATH (e.g. include the PID), or rotate externally with logrotate (copytruncate).

Container log limits. Under Docker Compose the long-running services emit stdout/stderr to the json-file log driver, which has no size limit by default — those logs grow until the disk fills. Every long-running service in deploy/compose/ therefore pins a bounded json-file driver:

# deploy/compose/docker-compose.yml (applied per service)
logging:
  driver: json-file
  options:
    max-size: "10m"   # rotate each container log file at 10 MB
    max-file: "5"     # keep at most 5 files (~50 MB per container)

This caps each container's on-disk log footprint at about 50 MB. The base file sets the block on backend, worker, dashboard, postgres, and redis; the override files (*.dev.yml, *.prod.yml, *.external-db.yml, *.azure-pg.yml) do not override the logging: key, so those services inherit the base limits unchanged. Services not present in the base file pin their own block: nginx (in docker-compose.prod.yml), docs (in both docker-compose.prod.yml and the standalone docker-compose.docs.yml), and the optional observability stack (docker-compose.observability.yml). If you ship logs off-box to log shipping, these limits only bound the local buffer, not your retention.

Log Shipping (Loki + promtail)

The observability stack ships every container's structured JSON logs to Grafana Loki so they are queryable in Grafana alongside the Prometheus metrics. This turns the JSON described above (Log Format) into a searchable, label-indexed log store.

How logs flow

backend / worker containers   (structlog → JSON on stdout, json-file driver)
        │
        ▼
   promtail                    (Docker service discovery via the daemon socket;
        │                       attaches compose labels, parses the JSON line)
        ▼
     Loki                      (indexes labels, stores log lines, enforces
        │                       retention)
        ▼
   Grafana                     (Loki datasource → Explore / dashboards)

promtail discovers running containers through the Docker daemon socket (mounted read-only) rather than tailing log files by path, so it picks up the compose service and container names automatically — no per-container configuration. It keeps a positions file on a named volume so a restart resumes where it left off instead of re-shipping everything.

Security note. The Docker socket is mounted read-only, but read-only is a file permission — not a Docker API boundary. Socket access still lets promtail read every container's metadata (labels, env) and logs on the host, so treat it as a privileged mount. This is the deliberate trade-off for socket-based log discovery; the blast radius is narrowed by a relabel keep that scopes scraping to the huitzo compose project. promtail also ships container stdout verbatim — any secret or PII must be redacted upstream at the structlog layer (see Log Format); it cannot be filtered here.

The canonical implementation lives in the observability stack — see these files for the exact, pinned configuration:

File Role
deploy/compose/docker-compose.observability.yml loki + promtail services, volumes, healthchecks
deploy/compose/observability/loki/loki-config.yml Loki single-binary config, filesystem store, retention
deploy/compose/observability/promtail/promtail-config.yml Docker discovery, relabeling, JSON pipeline
deploy/compose/observability/grafana/datasources/loki.yml Loki Grafana datasource (provisioned)

Labels vs. parsed fields

Loki indexes labels, so only low-cardinality dimensions become labels; everything else stays inside the stored JSON line and is parsed at query time with | json. High-cardinality fields like request_id are deliberately not labels — promoting them would explode Loki's index.

Field Exposed as Why
job (always huitzo) label Single entry point for "all platform logs".
service (backend, worker, dashboard, …) label Filter backend vs. worker; bounded set.
container label Disambiguate scaled replicas; bounded set.
level (info, warning, error, …) label Bounded set; the common first filter.
request_id parsed field (via json) Per-request — unbounded cardinality.
correlation_id parsed field (via json) Per-command-execution — unbounded.
tenant_id parsed field (via json) Grows with tenant count; kept off the index.

Querying in Grafana

Open Grafana → Explore → Loki and use LogQL. The label job="huitzo" selects the whole platform; | json parses the stored JSON line so any field becomes filterable:

# example queries — replace the placeholder ids with real values
# All worker error logs
{service="worker", level="error"}

# Follow a single request end-to-end across backend + worker
{job="huitzo"} | json | request_id="8f1c2e3a-..."

# One command execution
{job="huitzo"} | json | correlation_id="abc-123-def"

# Everything for one tenant, errors only
{job="huitzo", level="error"} | json | tenant_id="org_456"

This is the log half of the request-tracing workflow described under Request correlation IDs: read X-Request-ID from a response, then paste it into the request_id filter above.

Retention

Loki runs its compactor with retention enabled. The default retention_period is 168h (7 days); expired chunks are deleted on the compactor's schedule. Tune it in loki-config.yml (limits_config.retention_period) to match your disk budget and compliance requirements. Logs are stored on the loki-data named volume — size the host disk for retention_period × daily log volume.

Loki here uses the filesystem object store (single-binary mode), which is right for a single-host self-hosted deployment. For multi-node or high-volume installs, point Loki at object storage (S3/GCS/Azure Blob) — see the upstream Loki storage docs.

Health Checks

Endpoints

Endpoint Description
GET /health Overall system health (DB reachability + license state)
GET /health/live Liveness probe (is process running?)
GET /health/ready Readiness probe (can accept requests?)
GET /health/integrations Per-integration health (LLM, HTTP, email, Telegram)

There is no /health/detailed endpoint — use /health for the system summary (it carries the license state) or /health/integrations for per-integration status.

/health/integrations is unauthenticated, so its llm row is deliberately terse: LLM configured (healthy) or LLM not configured (degraded, never boot-blocking). It names no provider and no admin path. The operator hint goes to the backend log as a WARNING, once per unconfigured spell rather than on every probe: no LLM provider API key is configured, set one at /admin/llm — or, when the registry has never been read (database unreachable), that the registry is unavailable, so the fault is not misdirected to /admin/llm.

Response Format

GET /health checks database reachability and returns the license state. On success (200) it returns:

{
  "status": "healthy",
  "deployment_mode": "self_hosted",
  "version": "2.0.0",
  "license_status": {
    "license_state": "valid",
    "valid_until": "2027-01-22T00:00:00+00:00",
    "detail": null
  }
}

license_status is the operational centerpiece — license_state reads valid while in date, grace once valid_until passes but still inside the offline grace window, and invalid once grace runs out (or the file is missing/tampered). An optional extensions block is appended when enabled extensions report their own health. If the database is unreachable the endpoint returns 503 with {"status": "unhealthy", ...}.

Kubernetes Probes

# kubernetes deployment
spec:
  containers:
    - name: huitzo
      livenessProbe:
        httpGet:
          path: /health/live
          port: 8000  # container port (uvicorn --port 8000)
        initialDelaySeconds: 10
        periodSeconds: 10
      readinessProbe:
        httpGet:
          path: /health/ready
          port: 8000  # container port (uvicorn --port 8000)
        initialDelaySeconds: 5
        periodSeconds: 5

Complete Observability Stack

The canonical, version-pinned stack ships in the repository as deploy/compose/docker-compose.observability.yml. It overlays the base compose file and bundles these components:

Component Image Port Purpose
Prometheus prom/prometheus 9090 Metrics collection (15d retention)
Grafana grafana/grafana 3001 Metrics + logs visualization
Loki grafana/loki 3100 Log aggregation (see Log Shipping)
promtail grafana/promtail — Ships container logs to Loki
redis-exporter oliver006/redis_exporter 9121 Redis metrics
postgres-exporter prometheuscommunity/postgres-exporter 9187 PostgreSQL metrics

Grafana datasources (Prometheus + Loki) and dashboards are provisioned from deploy/compose/observability/. Exact image tags are pinned in the compose file — consult it rather than copying versions from this guide, so the two never drift.

Before bringing the overlay up, note two deliberate hardening choices:

  • GRAFANA_PASSWORD is required (there is no insecure admin default) — set it in your deploy environment or docker compose will fail interpolation.
  • All overlay ports bind to 127.0.0.1 (Prometheus 9090, Grafana 3001, Loki 3100, exporters 9121/9187) — nothing is published on a public interface. Reach them over an SSH tunnel (e.g. ssh -N -L 3001:127.0.0.1:3001 <host>) or a reverse proxy, not directly.
  • Prometheus scrapes the token-gated backend /metrics using a bearer token read from deploy/compose/observability/metrics-token (git-ignored, per-host, mode 0644 so the non-root Prometheus process can read it). The backend must receive the same token via HUITZO_METRICS_TOKEN (base compose).

Run the full stack alongside your main services:

GRAFANA_PASSWORD='<a strong password>' \
docker compose -f docker-compose.yml -f docker-compose.observability.yml up -d

Backend and worker error tracking (Sentry)

The backend, the Celery worker and Celery beat report to Sentry when HUITZO_SENTRY_DSN is set on that process. Unset, the integration is a no-op with no network egress.

Variable Set on Description
HUITZO_SENTRY_DSN backend, worker Sentry project DSN. Unset or empty: never initialized
HUITZO_SENTRY_ENVIRONMENT backend, worker Environment tag on every event (production, staging)
Process Captured
Backend Unhandled request exceptions (FastAPI and SQLAlchemy integrations)
Worker, beat A task that raises (Celery integration) and every ERROR log record (the SDK's logging integration)

The worker half exists so a failure on a money path reaches a person: a failed ledger invariant run fails its task, and each violated invariant logs an ERROR line. Before it, a beat task that failed or logged an error was visible only in the worker's own log.

Both processes send no PII (send_default_pii is off), share one before_send filter that strips authorization headers and request bodies, and drop events from the huitzo.pack logger so a pack's own log lines cannot spend the quota. The worker also removes the row id fields of a log record (ids, sample, charge_id, charge_ids, idempotency_key, tenant_id) from every event and breadcrumb: a ledger invariant's ERROR line carries a sample of the offending row and tenant ids for the operator reading the worker log, and those six fields never leave the process. Stack frames are sent without their local variables (include_local_variables is off on the worker), because the frames that log an incident hold the same ids. The line's text and its other fields (the invariant and the counts) are still sent. Source: backend/observability/sentry.py, worker/sentry.py.

Frontend error tracking (Sentry)

The Hub dashboard ships an optional, opt-in integration with Sentry for browser-side error tracking. It captures unhandled render errors (via the React error boundary) and unexpected authentication failures, so operators can see frontend crashes the same way the backend surfaces server-side errors.

The integration is off by default. With no DSN configured it is a complete no-op — Sentry is never initialized and no network calls are made. This keeps local development and Sentry-less self-hosted deployments untouched.

Configuration

Sentry is configured at container runtime, never at build time. The dashboard ships as one image for every deployment — the same bytes run in staging, SaaS production, and on self-hosted boxes. The release pipeline promotes the green staging image to production (it re-tags the staging digest rather than rebuilding), and that identical image is what self-hosted customers pull. A DSN baked into the bundle at build time would therefore leak Huitzo's DSN into production and every self-hosted deployment — so the DSN is never part of the image.

Instead the DSN is read at startup from a small runtime config object. The dashboard's nginx container runs /docker-entrypoint.d/40-runtime-config.sh before nginx starts; that script writes /usr/share/nginx/html/config.js from the container's environment, and index.html loads config.js before the app module so the value is present when initSentry() runs. (nginx is configured to serve config.js with no-store, so a regenerated value is never masked by a stale browser cache.)

Variable (container env) Required Effect
SENTRY_DSN No Sentry project DSN. Unset or empty → Sentry is never initialized (no-op), zero network egress. Set it to enable error tracking.
SENTRY_ENVIRONMENT No Environment tag attached to events (e.g. production, staging). Falls back to the build mode when unset.
  • Self-hosted: off by default. With SENTRY_DSN unset the integration is a complete no-op — nothing is sent anywhere. A self-hoster who wants browser error tracking sets their own DSN; Huitzo's DSN is never shipped to them.
  • Staging / SaaS-prod: opt in via the deploy env. The deploy environment sets SENTRY_DSN (and SENTRY_ENVIRONMENT) on the dashboard container, which turns Sentry on for that deployment only — no rebuild, no image divergence.

The DSN is a project ingest key, not a secret — but because the image is shared with self-hosted customers it is supplied per-deployment at runtime rather than embedded, so no deployment ever inherits another's DSN.

# pseudocode — enable Sentry by setting the DSN on the dashboard container
services:
  dashboard:
    environment:
      SENTRY_DSN: "https://<public-key>@<org>.ingest.sentry.io/<project>"
      SENTRY_ENVIRONMENT: "production"

For local vite dev and unit tests there is no container entrypoint, so the init path also falls back to the build-time VITE_SENTRY_DSN / VITE_SENTRY_ENVIRONMENT variables when the runtime object is absent. Those build-time vars are a dev/test convenience only — production images are built without them, keeping the shipped bundle DSN-free.

Redaction guarantee (PII / secrets never leave the browser)

Every event is passed through a beforeSend (and breadcrumbs through a beforeBreadcrumb) hook that deeply scrubs every string in the payload — message, exception values, breadcrumbs, request data, extra, and user context — before it is transmitted. The scrubber reuses the exact same redaction primitive (redactPii) as the frontend's safeLog console wrapper, so the two surfaces are guaranteed to strip identical classes of data:

Class Example Result
Access codes HUITZO-ABCD-1234 [redacted]
Email addresses [email protected] [redacted]
Stripe Checkout session ids cs_test_… / cs_live_… [redacted]

Sentry's own sendDefaultPii option is also left disabled, so the SDK does not attach IP addresses or other default PII. Because the scrubber walks the whole event and the redaction rules are shared with safeLog, the Sentry surface can never ship a weaker scrubber than the console path.

The redaction logic and Sentry bootstrap live in apps/dashboard/src/lib/sentry.ts; the shared redaction primitive lives in apps/dashboard/src/lib/safe-logger.ts.

# pseudocode — event scrubbing flow
beforeSend(event):        deepRedact(event)        # every string → redactPii(...)
beforeBreadcrumb(crumb):  deepRedact(crumb)        # same primitive as safeLog

What is captured

Surface Source Notes
Render errors React ErrorBoundary.componentDidCatch Includes the component stack; no new error UI is introduced.
Auth failures Auth store login / register Only unexpected failures (5xx / network). Ordinary credential rejections (4xx) are user errors and are not reported.