Enforcing Observability Contracts in CI/CD With Open Policy Agent

Enforcing Observability Contracts in CI/CD With Open Policy Agent

At 2:07 PM on a Thursday, we shipped checkout-worker v4.11.2 to production EKS. All 194 unit tests were green. The integration suite passed. ArgoCD synced the pods cleanly, health checks returned 200 OK, and our main Grafana overview stayed calm and green all afternoon. We did not find out anything was wrong until 8:19 PM, when a merchant in our enterprise Slack channel asked why none of their paid orders since 2:30 PM had triggered fulfillment webhooks. When I exec'd into one of the pods and tailed stdout, the worker was chewing through a dead-letter backlog of 1,840 failed webhook jobs. A Redis connection pool change had caused silent ECONNRESET drops on the third retry. Why didn't PagerDuty fire? Because two weeks earlier, a developer had split handleWebhookJob() into a new module and forgotten to wrap it in our withTelemetry() helper. Zero Prometheus counters incremented. Zero OpenTelemetry spans left the pod. On paper, checkout-worker was having the quietest, healthiest day of the year. Our dashboards were lying because the code had stopped talking to them. Why Traditional Tests Never Catch Missing Telemetry Most CI pipelines check two things well: does the code compile, and do the functional assertions pass? Neither check cares if a service is completely invisible once it hits production. When we did the post-mortem on Friday morning, we found 11 other endpoints and background consumers across four TypeScript/Node services that had either zero spans, stale metric names, or catch blocks that logged to console.log without incrementing an error counter. None of those gaps showed up in code coverage—Jest happily reported 86% line coverage on checkout-worker the day it went blind. And asking engineers to "remember to check telemetry in code review" does not work. We tried that for three months. When a PR touches 19 files and fixes a P1 bug, nobody stops to verify whether otel_span_name or webhook_failures_total is still wired up. We needed the pipeline to fail loudly before merge, the exact same way it fails on a type error. Treating Observability as a Merge Contract With OPA Instead of inventing a custom bash script full of grep hacks (which break the moment someone formats an object across two lines), we split the problem into two clean pieces: A static AST extractor that scans every route handler and queue consumer in the repo and emits a small JSON manifest (otel-manifest.json) listing what telemetry each handler actually produces. An Open Policy Agent (OPA) Rego policy that evaluates otel-manifest.json in CI and exits non-zero if any handler ships without a trace span, an error counter, or a declared SLO owner. Why OPA? Because we already used Rego for Kubernetes admission policies, and keeping deployment gates in one declarative policy language meant our SRE and SDET folks could read the exact same rulebook. No hidden regex magic. Step 1: Extract What Each Handler Actually Emits We wrote a 110-line TypeScript AST script (scripts/extract-otel-manifest.ts) using the standard typescript compiler package. It walks src/handlers/ and src/workers/, finds exported handler functions, and checks whether they call our withTelemetry wrapper or tracer.startActiveSpan plus at least one Prometheus counter (inc(). Here is the script we put in the repo: import fs from 'node:fs'; import path from 'node:path'; import ts from 'typescript'; interface HandlerTelemetry { file: string; handlerName: string; hasTraceSpan: boolean; hasErrorCounter: boolean; spanNames: string[]; metricNames: string[]; } const TARGET_DIRS = ['src/handlers', 'src/workers']; function walkTsFiles(dir: string): string[] { if (!fs.existsSync(dir)) return []; const entries = fs.readdirSync(dir, { withFileTypes: true }); return entries.flatMap((entry) => { const full = path.join(dir, entry.name); if (entry.isDirectory()) return walkTsFiles(full); return entry.name.endsWith('.ts') && !entry.name.endsWith('.test.ts') ? [full] : []; }); } function inspectFile(filePath: string): HandlerTelemetry[] { const code = fs.readFileSync(filePath, 'utf8'); const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true); const results: HandlerTelemetry[] = []; function scanNode(fnNode: ts.Node, handlerName: string) { let hasTraceSpan = false; let hasErrorCounter = false; const spanNames: string[] = []; const metricNames: string[] = []; function visit(node: ts.Node) { if (ts.isCallExpression(node)) { const callText = node.expression.getText(sf); if (callText.includes('startActiveSpan') || callText === 'withTelemetry') { hasTraceSpan = true; const firstArg = node.arguments[0]; if (firstArg && ts.isStringLiteral(firstArg)) { spanNames.push(firstArg.text); } } if (callText.endsWith('.inc') || callText.includes('recordErrorMetric')) { hasErrorCounter = true; metricNames.push(callText.replace(/\.inc$/, '')); } } ts.forEachChild(node, visit); } visit(fnNode); results.push({ file: path.relative(process.cwd(), filePath), handlerName, hasTraceSpan, hasErrorCounter, spanNames, metricNames, }); } ts.forEachChild(sf, (node) => { const isExported = ts.canHaveModifiers(node) && ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword); if (!isExported) return; if (ts.isFunctionDeclaration(node) && node.name) { scanNode(node, node.name.text); } else if (ts.isVariableStatement(node)) { for (const decl of node.declarationList.declarations) { if (ts.isIdentifier(decl.name) && decl.initializer && ts.isArrowFunction(decl.initializer)) { scanNode(decl.initializer, decl.name.text); } } } }); return results; } const manifest = { service: process.env.SERVICE_NAME || 'checkout-worker', generatedAt: new Date().toISOString(), handlers: TARGET_DIRS.flatMap(walkTsFiles).flatMap(inspectFile), }; fs.writeFileSync('otel-manifest.json', JSON.stringify(manifest, null, 2)); console.log(`Extracted telemetry manifest for ${manifest.handlers.length} handlers.`); Notice it is intentionally boring. It does not try to execute the service or spin up a local collector. It just reads the TypeScript AST in ~400 milliseconds and writes otel-manifest.json. Step 2: Enforce the Policy With OPA Next, we wrote policy/observability_gate.rego. Every exported handler or queue worker must emit both a trace span and an error counter. If a handler is marked in an explicit exemptions list (for example, a /healthz liveness probe that Kubernetes hits every 5 seconds), OPA lets it pass. Everyone else gets blocked with a clear file and function name. package ci.observability import rego.v1 exempt_handlers := { "healthzHandler", "readinessCheck", } deny contains msg if { some handler in input.handlers not handler.handlerName in exempt_handlers not handler.hasTraceSpan msg := sprintf( "BLOCKED: %s (%s) emits zero OpenTelemetry spans. Wrap with withTelemetry() or tracer.startActiveSpan().", [handler.handlerName, handler.file], ) } deny contains msg if { some handler in input.handlers not handler.handlerName in exempt_handlers not handler.hasErrorCounter msg := sprintf( "BLOCKED: %s (%s) has no Prometheus error counter (.inc or recordErrorMetric).", [handler.handlerName, handler.file], ) } Step 3: Wire It Into GitHub Actions Before Deploy We added a telemetry-gate job in GitHub Actions that runs extract-otel-manifest.ts and feeds otel-manifest.json straight into opa eval --fail-defined. If deny returns even one message, the job exits with code 1 and blocks the production deploy job (needs: [test, telemetry-gate]). jobs: telemetry-gate: runs-on: ubuntu-latest timeout-minutes: 2 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: npm ci --ignore-scripts - run: npx tsx scripts/extract-otel-manifest.ts - name: Install OPA run: | curl -sSL -o /usr/local/bin/opa https://openpolicyagent.org/downloads/v1.0.0/opa_linux_amd64_static chmod +x /usr/local/bin/opa - name: Enforce Observability Contract run: | opa eval --fail-defined -i otel-manifest.json -d policy/observability_gate.rego "data.ci.observability.deny" The whole job finishes in 9 seconds on a standard ubuntu-latest runner. What Broke When We Turned It On (and How We Fixed It) The first day we ran this across our four core services, it flagged 14 handlers. Two of them were legitimate exemptions (/healthz and /metrics itself). The other 12 were real blind spots—including a Stripe dispute webhook handler that had been logging errors to stderr for four months without a single metric attached. There was one annoying edge case we did not anticipate: shared middleware. Two Express routes delegated error counting to a global Express error middleware (errorMetricsMiddleware) instead of calling .inc() inside the route handler itself. Our initial AST check flagged both routes as missing an error counter. Instead of weakening the Rego policy, we standardized on wrapping every route with withTelemetry('route.name', handler) at the export site. That way, both tracing and error counting live in one visible place per handler, and anyone reading the file can see the exact span name in two seconds. Here is the 25-line wrapper we used so devs did not have to wire startActiveSpan and prom-client by hand in every file: import { trace, SpanStatusCode } from '@opentelemetry/api'; import { Counter } from 'prom-client'; const tracer = trace.getTracer('checkout-worker'); const handlerErrors = new Counter({ name: 'worker_handler_errors_total', help: 'Unhandled errors inside exported handlers', labelNames: ['handler', 'error_type'], }); export function withTelemetry( spanName: string, fn: (...args: TArgs) => Promise ) { return async (...args: TArgs): Promise => { return tracer.startActiveSpan(spanName, async (span) => { try { return await fn(...args); } catch (err) { const errorType = err instanceof Error ? err.name : 'UnknownError'; span.recordException(err as Error); span.setStatus({ code: SpanStatusCode.ERROR }); handlerErrors.inc({ handler: spanName, error_type: errorType }); throw err; } finally { span.end(); } }); }; } Step 4: Unit-Testing the Rego Policy (opa test) One mistake teams make with policy-as-code is treating .rego files like throwaway config. Two months in, someone tweaks a condition, accidentally makes deny evaluate to empty, and the gate silently passes everything forever. We added a policy/observability_gate_test.rego file and ran opa test policy/ right next to opa eval in CI: package ci.observability_test import data.ci.observability.deny import rego.v1 test_blocks_handler_without_span if { result := deny with input as {"handlers": [{ "file": "src/workers/refund.ts", "handlerName": "processRefund", "hasTraceSpan": false, "hasErrorCounter": true, }]} count(result) == 1 } test_allows_exempt_healthz if { result := deny with input as {"handlers": [{ "file": "src/handlers/health.ts", "handlerName": "healthzHandler", "hasTraceSpan": false, "hasErrorCounter": false, }]} count(result) == 0 } It runs in under 200 milliseconds. Cheap insurance. Step 5: Catching High-Cardinality Metric Bombs in the Same Pass Once the AST scanner was already parsing src/handlers/ and src/workers/, we added one more check that saved us from a nasty billing surprise. In August, someone had passed order_id as a Prometheus label on a retry counter. Within 48 hours, our custom metrics cardinality exploded past 400,000 unique time series and triggered a $1,640 overage on our monitoring bill. So we added a bannedLabelKeys check inside extract-otel-manifest.ts (userId, orderId, email, requestId, sessionId) and let OPA block any .inc({ ... }) call that tried to attach high-cardinality IDs to a metric. Logs and traces get IDs; metrics get bounded enums. Rolling It Out Without Stopping Every Deploy on Day One If you drop a hard opa eval gate onto a legacy monorepo on Monday morning, you will block 40 unrelated PRs and everyone will hate you by lunch. We rolled it out in two phases over two weeks: Warn-only mode for 7 days: The GitHub Actions job ran opa eval without --fail-defined, posting a PR comment listing any missing spans or counters. That gave teams a week to clean up the 12 existing blind spots and add legitimate /healthz exemptions without freezing releases. Hard-fail on new and modified files: Once main hit zero violations, we flipped --fail-defined on. From that point forward, you could not merge a handler that emitted zero telemetry unless you explicitly added it to exempt_handlers in the same PR—which meant another engineer had to see it in the diff and approve the exemption. That social friction turned out to be half the value. Nobody wants to be the person adding a new endpoint to exempt_handlers just to avoid writing a single withTelemetry() call. The Numbers 60 Days Later We did not have to buy a new observability vendor or rewrite our services. Two months after turning on telemetry-gate: CI overhead: 9 seconds per PR. PRs blocked before merge: 14 PRs caught with missing spans or dropped error counters before they ever reached staging. Silent production incidents (zero-metric outages): Dropped from 3 in the prior quarter to 0. On-call triage time: We estimated ~19 hours saved in the first two months because every new worker had a trace ID and failure counter from day one (roughly $3,420/month in avoided senior engineering firefighting, though that part is our internal estimate). Testing whether code works on your laptop is table stakes. Testing whether production can tell you when it is dying is a completely different job—and if your CI pipeline does not enforce it automatically, a refactor will eventually turn your dashboards into expensive green wallpaper.

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.