Skip to content

Add the opt-in observability stack (Prometheus, Tempo 3, Grafana) with per-provider cost - #4

Open
emphilip wants to merge 4 commits into
mainfrom
add-observability-stack
Open

emphilip wants to merge 4 commits into
mainfrom
add-observability-stack

Conversation

@emphilip

Copy link
Copy Markdown
Collaborator

What and why

openCG promised observable stages, but spans only reached a collector log, only the pipeline served /metrics, the MCP server had no telemetry, and there was no cost estimate. This adds Prometheus, Tempo 3 and Grafana as an opt-in overlay (make up-obs), closes the instrumentation gaps, and reports token usage and estimated cost per LLM provider everywhere tokens are shown.

OpenSpec change

openspec/changes/add-observability-stack/ (approved by the owner on 2026-11-12). Tasks done: all except 7.3 (deliberate broken-config runs), 7.5's live ruleset step, and close-out items 9.4, 9.4a and 9.5.

Highlights:

  • Opt-in overlay: prom/prometheus:v3.15.1, grafana/tempo:3.1.1, grafana/grafana:13.2.5. The default stack, make smoke and the stack job are unchanged. Measured overlay RAM: about 700 MB (Tempo ~340, Grafana ~260, Prometheus ~70).
  • One connected trace per MCP tool call (MCP server → pipeline → model.* spans), with correlation_id on every span, including FastAPI's own request spans.
  • /metrics on the MCP server and ingestion service (multiprocess mode, so CLI runs are counted). Stage latency, provider errors, request outcomes, audit writes, ingestion runs and ingestion embedding tokens are now recorded.
  • Each LLM endpoint has its own provider label: ollama (local) and ollama-cloud. Breaking for saved queries: Cloud chat was previously labelled ollama.
  • Price table in opencg.yaml (Ollama Cloud's published per-token rates, each row with source and as_of). Unpriced models show as "unpriced", never $0.
  • Default chat model moves to gemma4:31b (owner decision), because gemma3:4b has no published price.
  • Cost in the usage envelope, in retrieval audit rows (060_audit_cost.sql; apply by hand on an existing volume, see OPERATIONS) and beside every token count in the admin UI.
  • Six Grafana dashboards as code, linted in make ci-static. Grafana requires sign-in.
  • New observability CI job on every PR, push to main and nightly. It is listed as required in .github/rulesets/main-branch-protection.json; the live ruleset is updated only after this job has passed on main.

Package notes:

  • At versions older than two weeks, prom-client and @opentelemetry/sdk-trace-node are deprecated upstream. The MCP server uses their named replacements, @prometheus-io/client and @opentelemetry/sdk-trace + @opentelemetry/context-async-hooks.
  • A pnpm override pins the transitive @opentelemetry/semantic-conventions to 1.44.0 (two-week rule).

Checklist

  • The OpenSpec change exists, passes openspec validate add-observability-stack --strict, and was agreed before implementation
  • The change's tasks.md is updated, including anything discovered during implementation
  • Unit tests added or updated; make ci-static passes
  • make smoke passes against a live stack (and make smoke-obs with the overlay)
  • make e2e passes (21/21), and new admin UI behaviour has an e2e test
  • New shared admin UI components have a *.stories.tsx neighbour
  • Docs updated (README, docs/OPERATIONS.md, .env.example, CHANGELOG, agent guides)
  • No secrets, .env files or real credentials in the diff
  • Archived: after merge, in a follow-up

Dashboard screenshots were captured locally after make smoke-obs. All six dashboards render; only the error, rejection and provider-error panels show "No data", because nothing failed.

🤖 Generated with Claude Code

Edward and others added 2 commits November 12, 2026 12:17
- Prometheus v3.15.1, Tempo 3.1.1 and Grafana 13.2.5 as an opt-in compose
  overlay (`make up-obs`, `make smoke-obs`); six dashboards as code with a
  static lint in `make ci-static`; Grafana sign-in required.
- One connected trace per MCP tool call: the MCP server traces tool calls and
  propagates W3C traceparent; the pipeline continues it; correlation_id on
  every span, including FastAPI's own request spans.
- /metrics on the MCP server and ingestion (multiprocess mode so CLI runs
  count); stage latency, provider errors, request outcomes, audit writes and
  ingestion runs wired up; ingestion embedding tokens now counted.
- Cost estimation from a price table in opencg.yaml (Ollama Cloud's published
  per-token rates); unpriced models are flagged, never shown as $0; each LLM
  endpoint reports its own provider label (`ollama`, `ollama-cloud`).
- Cost in the usage envelope, retrieval audit rows (060_audit_cost.sql) and the
  admin UI.
- Required `observability` CI job on every PR to main and nightly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gemma3:4b has no published Ollama Cloud per-token price; gemma4 does
($0.14 / $0.40 per million input / output tokens). Adds the gemma4:31b
price row and a knowledge-graph spec delta for the new default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PrabS-EM
PrabS-EM previously approved these changes Nov 23, 2026

@PrabS-EM PrabS-EM left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving, with fixes requested before merge (or as an immediate follow-up):

  1. Existing databases break on upgrade. AuditStore.write now inserts estimated_cost_usd and usage_by_provider. On an existing volume where 060_audit_cost.sql hasn't been applied by hand, every /retrieve returns a 500. The manual step is documented, but nothing catches it. Please add a readiness check for the new columns (or apply the script at startup) so a missed step shows up as "not ready" rather than failed requests.
  2. The Grafana password defaults to admin. GF_SECURITY_ADMIN_PASSWORD falls back to admin, and Prometheus and Tempo have no auth. Today they bind to loopback by default, so this is fine for now. But #6 makes non-loopback binds the normal setup for OIDC, so please refuse to start (or fail make up-obs) when the default password is still set and the bind address isn't loopback.

Minor: relabelling Ollama Cloud chat to ollama-cloud breaks saved provider="ollama" queries. It's flagged in the CHANGELOG already; please also call it out in the release notes.

…ESS is

Review on #6: OIDC deployments set a non-loopback OPENCG__BIND_ADDRESS,
which also published Prometheus and Tempo (no auth; traces carry principal
and tenant) and Grafana on its default password. Prometheus and Tempo now
always bind to 127.0.0.1; Grafana binds to OPENCG__GRAFANA__BIND_ADDRESS
(default loopback), and make up-obs refuses a non-loopback Grafana with an
unset or 'admin' password.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Propose the Next 16 upgrade for the admin UI (upgrade-admin-ui-next-16)

Owner-approved: Next 16.4.5 as a security-release exception, a nightly
hydration stress pass in CI, Tremor kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Upgrade the admin UI to Next.js 16.4.5 and React 19 (fixes #2)

- next / eslint-config-next 16.4.5 (security release, owner-approved
  exception to the two-week rule), react / react-dom 19.3.1, types 19.3.0.
- Native flat ESLint config; four commented inline disables for the new
  react-hooks/set-state-in-effect rule; Tremor kept with a peer allowance.
- middleware.ts -> proxy.ts (Node runtime); tsconfig.json and next-env.d.ts
  as rewritten by `next build`.
- New `make hydration-stress` check (services/admin-ui/scripts) and a
  nightly 4 x 10 pass in the CI stack job.
- Issue #2: 0 hydration errors in 1,680 stressed loads on Next 16 vs 34 in
  560 on 15.5.29; the e2e reload workaround is removed (3 green e2e runs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Propose identity (OIDC) and OPA entitlement (add-identity-and-opa)

Owner-approved 2026-11-12: default mode none, API keys dev-only, Keycloak
bundled in the same workload, pre-registered MCP clients for Entra ID,
public/internal/confidential:<domain> classifications.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Drop the fixed hydration error from README known issues (#2)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add OIDC identity and OPA entitlement (add-identity-and-opa)

- OPENCG__AUTH__MODE (none | oidc) in every service; OIDC access tokens
  validated against one issuer's JWKS (RS256/ES256, iss/aud/exp/nbf, 60 s
  skew); identity only from the token in oidc mode.
- OPA (1.21.4) decides every retrieval candidate (one batched call, before
  the token budget) and every API action, in both modes; fails closed with
  503 policy_unavailable. Policies, data and tests in infra/opa/.
- Append-only opencg.access_audit_log (denials and allowed writes, in the
  write's transaction); auth_method and per-candidate policy decisions on
  retrieval audit rows; real actor on graph audit rows.
- MCP server is an OAuth protected resource; the shared-password OAuth
  stopgap is removed. Admin UI signs in with code + PKCE and Valkey
  sessions; the password gate is removed. Removed settings refuse startup.
- Bundled Keycloak (26.8.1) in the same compose project, Postgres-backed,
  dev users only in dev/test. API keys only when OPENCG__ENVIRONMENT=dev.
- Ingestion classification (CLI and API) and requested_by.
- Smoke and e2e run in oidc mode by default (OPENCG_TEST_AUTH_MODE), and
  in CI's stack and observability jobs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Track infra/opa/data (was caught by the data/ ignore rule)

The root .gitignore's data/ rule excluded infra/opa/data/opencg.json, so
CI's opa check failed with 'stat data: no such file or directory'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Address PR #6 review: dev-only secrets, tenant scoping, schema readiness

- Refuse any OPENCG__*/KC_* variable still holding a dev-only-* value from
  .env.example outside OPENCG__ENVIRONMENT=dev/test, in every service and
  the Keycloak entrypoint (names only, never values).
- A configured tenant claim is now required (401 token_invalid without
  it); /audit/recent and /audit/{id} are scoped to the caller's tenant.
- /readyz (pipeline and ingestion) checks the tables and columns from
  060_audit_cost.sql and 070_access_audit.sql and names the script.
- entitle.run fails closed (PolicyUnavailable) on a missing decision.
- Guard registered with scope="function": the fallback access-audit
  write finishes before the response, so a failed write is a 500.

Spec deltas, tasks (section 14), OPERATIONS, .env.example and CHANGELOG
updated. The overlay-port fix is on add-observability-stack, merged in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Address Ponytail review of #6: entity entitlement, OPA lockdown, safe defaults

Must-fix findings from a full review of the PR's code:
- GET /entities and /entities/{id} now apply opencg.entitlement (shared
  with /search/vector): readers no longer see confidential rows, and a
  denied entity is a 404.
- OPA runs with --authorization=basic (policies/system_authz.rego allows
  only decision queries and /health), and its host port is always
  loopback: its API no longer accepts policy or data writes.
- Compose defaults OPENCG__ENVIRONMENT to production, as the services do.
- The admin UI refuses cross-origin writes to /api/** in both modes.
- Admin UI refresh keeps a session another instance already rotated,
  ends it only on invalid_grant, and survives brief IdP outages.

Also: issuer matched exactly as configured (trailing slash), unused auth
glue removed, entitle skips OPA for an empty candidate list. Spec deltas,
tasks (section 15, with three follow-ups), OPERATIONS and CHANGELOG updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Make the nightly hydration stress run work in oidc mode

With add-identity-and-opa merged into this branch, CI's stack job runs
every service in oidc mode, so the nightly stress run's browsers landed
on the Keycloak sign-in page and failed every night with a misleading
'no seed data' message. The script now reuses the signed-in alice
session that make e2e saves (or STORAGE_STATE), defaults BASE_URL to
localhost like e2e so that session's cookie applies, and names the
sign-in redirect when it has no session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Edward <edward@mac.home>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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