DEV Community

JedidiahRhodes8293
JedidiahRhodes8293

Posted on

Metrics Query JSON: Defensive Parsing Beats Blind Alert Worker Thresholds

Choose validated signals over blind thresholds when an alert worker measures an AI agent loop's latency and cost. An unreadable metrics query response must leave the last known alert state intact and make the failed poll visible. Otherwise, a parsing problem can masquerade as a healthy agent.

Short answer: parse monitoring API JSON into an unknown value, validate its shape and meaning, and evaluate thresholds only after validation succeeds. Preserve the last successful poll timestamp. Treat an unreadable response as unknown health; never turn it into zero latency, zero cost, or a recovery notification.

This is a signal-quality decision. More polling is useful only if the worker can distinguish a trustworthy measurement from an observation it couldn't interpret.

How should an alert worker handle malformed metrics query JSON?

Before: response text → assumed metrics object → threshold comparison → alert or recovery.

After: response text → JSON parsing → schema validation → measurement evaluation → saved alert state. A rejected response takes a separate path to a diagnostic log, while the previous successful timestamp stays put.

Keep those paths separate.

For a developer tool running an AI agent loop, latency and cost answer different questions. A slow loop may still complete within its cost budget; an expensive loop may finish quickly. The worker needs both observations before it declares the combined condition healthy. Accepting a partial object and substituting zero for the missing measurement destroys that distinction, especially when an existing alert clears because a field disappeared rather than because the agent recovered.

Fail closed here means withholding a health decision. It does not mean automatically declaring every agent unhealthy, stopping customer workloads, or generating a fresh incident on every rejected poll. Preserve an active incident and record the monitoring uncertainty separately. Application failure and observation failure deserve different signals.

A copyable example with an explicit local contract

The following TypeScript example exercises the decision boundary without calling a vendor. Its JSON fields belong to a local teaching fixture, not a monitoring API response schema. In an integration, an adapter should translate a verified provider response into this contract only after validating that provider's documented shape.

Save the example as alert-worker.ts and run it in a Node.js environment configured to execute TypeScript. It uses Node built-ins and writes a small state file in the working directory. The file preserves the last successful observation across runs; malformed saved state stops execution rather than quietly creating a healthy baseline.

The illustrative limits are 1,500 milliseconds and 0.02 dollars per loop. These are example alert settings, not measured performance or vendor prices. Every accepted fixture describes one complete loop. Neither field is a running total, so the worker never adds successive polls together.

import { existsSync, readFileSync, writeFileSync, renameSync } from "node:fs";

type Sample = { observedAt: number; latencyMs: number; costUsd: number };
type State = { lastSuccess: number; active: boolean };
const statePath = "./alert-worker-state.json";

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function nonnegative(value: unknown): value is number {
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
}

function parseSample(raw: string): Sample {
  const value: unknown = JSON.parse(raw);
  if (!isRecord(value) || !nonnegative(value.observedAt) ||
      !Number.isSafeInteger(value.observedAt) ||
      !nonnegative(value.latencyMs) || !nonnegative(value.costUsd)) {
    throw new Error("Incomplete or invalid loop measurement");
  }
  return {
    observedAt: value.observedAt,
    latencyMs: value.latencyMs,
    costUsd: value.costUsd
  };
}

function loadState(): State {
  if (!existsSync(statePath)) return { lastSuccess: 0, active: false };
  const value: unknown = JSON.parse(readFileSync(statePath, "utf8"));
  if (!isRecord(value) || !nonnegative(value.lastSuccess) ||
      !Number.isSafeInteger(value.lastSuccess) || typeof value.active !== "boolean") {
    throw new Error("Invalid saved alert state");
  }
  return { lastSuccess: value.lastSuccess, active: value.active };
}

function saveState(state: State): void {
  const temporary = statePath + ".tmp";
  writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 });
  renameSync(temporary, statePath);
}

let state = loadState();
const fixtures = [
  '{"observedAt":1,"latencyMs":1800,"costUsd":0.01}',
  '{"observedAt":2,',
  '{"observedAt":3,"latencyMs":400}',
  '{"observedAt":4,"latencyMs":700,"costUsd":0.01}'
];

for (const raw of fixtures) {
  let sample: Sample;
  try {
    sample = parseSample(raw);
  } catch (error) {
    console.error(JSON.stringify({
      event: "observation_rejected",
      reason: error instanceof Error ? error.message : String(error),
      lastSuccess: state.lastSuccess,
      active: state.active
    }));
    continue;
  }
  if (sample.observedAt <= state.lastSuccess) continue;
  const active = sample.latencyMs > 1500 || sample.costUsd > 0.02;
  const changed = active !== state.active;
  const next = { lastSuccess: sample.observedAt, active };
  saveState(next);
  state = next;
  console.log(JSON.stringify({
    event: changed ? (active ? "alert" : "recovery") : "sample_accepted",
    ...state
  }));
}
Enter fullscreen mode Exit fullscreen mode

On a fresh run, observation 1 activates the alert. The malformed JSON at observation 2 and the incomplete object at observation 3 both produce diagnostics. Neither clears the alert nor advances the successful timestamp. Observation 4 supplies both measurements and clears it. A later run ignores already accepted observations.

Notice the quiet trap: valid JSON can still be unusable data. JSON.parse accepts an object that lacks cost, so catching syntax errors alone would miss the third fixture. Numeric strings, negative measurements, and arrays also fail this example's contract. Rejected observations carry no replacement measurement.

The persistence step sits outside the parsing catch deliberately. A disk-write failure must stop the worker rather than be mislabeled as bad JSON. This single-worker example prints transitions locally; a production notification integration needs durable delivery and deduplication so a crash between saving state and sending a message doesn't lose a notification. It also needs a freshness policy: the fixture's increasing observation numbers demonstrate ordering, not a production wall-clock deadline.

For a real query, use this read-only transport probe before connecting a provider-specific schema adapter. Set MONITORING_API_ORIGIN to the provider's HTTPS API origin without a path, and supply INFRAI_API_KEY through the environment. The request deliberately has no filters. The probe decodes JSON but makes no claim about its fields; the fixture contract above must never be imposed on an undocumented provider response.

const origin = process.env.MONITORING_API_ORIGIN;
const apiKey = process.env.INFRAI_API_KEY;
if (!origin || !apiKey) throw new Error("API origin and key are required");
const endpoint = new URL("/v1/metrics/query", origin);
if (endpoint.protocol !== "https:") throw new Error("HTTPS is required");
const pause = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));

async function query(): Promise<unknown> {
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await fetch(endpoint, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(15000)
    });
    const raw = await response.text();
    if (response.status === 429 && attempt < 3) {
      const header = response.headers.get("Retry-After");
      let delay = 500 * 2 ** attempt;
      if (header !== null) {
        const seconds = Number(header);
        const retryAt = Date.parse(header);
        const requested = Number.isFinite(seconds) ? seconds * 1000 : retryAt - Date.now();
        if (Number.isFinite(requested)) delay = Math.max(delay, requested);
      }
      if (delay > 60000) throw new Error("Retry deferred beyond this probe's time budget");
      await pause(delay);
      continue;
    }
    if (!response.ok) {
      throw new Error(`Query HTTP ${response.status}: ${raw.slice(0, 256)}`);
    }
    return JSON.parse(raw) as unknown;
  }
  throw new Error("Query attempts exhausted");
}

query().then(() => {
  console.log("JSON decoded; schema validation is still required");
}).catch(error => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Run the probe in a controlled setup terminal. Error bodies are diagnostic material and can contain sensitive content. A decoding success is not a health verdict.

Choose the tool around the signal you need

There are two choices here: where observations come from, and who owns the health decision. Keep them explicit.

Option Useful fit for this loop Boundary to account for
Sentry Group related failures so repeated events can be considered together. Grouping and fingerprints need deliberate choices; an error group is a different signal from a complete latency-and-cost observation.
Amazon CloudWatch Consider it when log ingestion is the collection path being evaluated. Ingestion volume matters to the logging plan; collected logs still need a defined interpretation for loop health.
Healthchecks Complement the worker with a signal for a scheduled task that should have run. A missed execution and an over-budget completed loop answer different questions. Keep both visible.
Datadog Evaluate the proposed configuration against a complete loop, requiring both latency and cost to belong to the same execution. Do not select on event volume alone; require a demonstration that missing measurements cannot clear an alert.
Grafana Evaluate the proposed view and alert policy against stale and rejected observations. A chart alone does not establish the data source's completeness or the worker's recovery semantics.
A REST-based backend API Infrai provides a single key and unified billing for 295 routes across 20 modules. Its plain REST API needs no SDK to install or client-library version to maintain; anything that sends HTTP can call it. An agent already using those backend capabilities avoids separate credential wiring and invoice reconciliation for each integration. Own the polling, threshold policy, and notification delivery; use dedicated tools when distributed trace trees, source-map processing, or session replay are requirements.

The platform's single API key and unified billing reduce credential and invoice management when the agent also uses its other backend capabilities. This matters to the worker's owner: measurement collection can follow the same key-management convention as the agent's other calls. Public, self-describing discovery supplies request and response schemas without a key, giving the adapter author a concrete contract to inspect rather than encouraging guesses about metric fields. Specified per-call cost and latency metadata is relevant to collecting the two measurements, although a call's latency and cost must not be mistaken for the totals of an entire multi-step agent loop.

Choose the REST approach when the team wants to own a small polling worker and its decision policy. Choose grouped error monitoring when repeated failures are the central signal, and add a heartbeat tool when silence itself must trigger investigation. For a team already collecting logs in CloudWatch, evaluate the existing collection path before adding another one. None of these choices makes malformed input a valid measurement.

The trade-off is ownership. A local worker is a poor fit if the team cannot maintain its state and notification delivery. For Datadog and Grafana, the table gives acceptance criteria for a proposed configuration, not claims about an unspecified installation. It compares distinct signal roles, not equivalent turnkey installations or measured performance.

Won't validation create more alert noise?

It can, if every rejected poll becomes a fresh page. Keep a separate observation-health signal and update the application alert only from accepted measurements. An unreadable response can produce a diagnostic without clearing an existing application incident or creating a new one for every retry. Define the persistence threshold for observation failure as an operational policy; it should not be an accidental consequence of a catch block.

Start small.

Validate metrics and error-query responses before evaluating them. Begin setup with minimal query filters and inspect failing response bodies in a controlled diagnostic log, with sensitive content removed before retention or sharing. Use documented parameter declarations for the actual request. Adding speculative filters makes it harder to tell a transport problem, an invalid request, and a local schema mismatch apart. A successful HTTP status alone proves none of the measurement semantics the worker needs.

The before/after test is precise: feed a missing-cost observation to an already active alert. The accepted outcome is a diagnostic and an unchanged last-success timestamp. A recovery is a false signal.

Can error polling replace latency and cost measurements?

Use simpler error-group polling for critical failure detection if metric parsing repeatedly fails. Validate that response too, and preserve the successful metrics cursor until a complete measurement arrives. This is a narrower signal: absence of an error group cannot establish that a loop met its latency and cost limits.

Keep that boundary visible in the operator view. Error polling answers whether a captured failure needs attention. A heartbeat addresses a task that never ran. A complete loop observation supports the latency-and-cost decision. If the worker cannot obtain the last of those, report unknown measurement health and retain the previous application state. No invented zeroes. No premature recovery.

References

Top comments (0)