Designing Antigravity Agent Traces That Tell You Why It Failed — Observability in Practice
How to add OpenTelemetry spans to your own agent loop so a failure can be read in a few lines. Covers span structure, what to keep and drop in attributes, a failure_class taxonomy, a retry table, three dashboard views, cost attributes, and PII handling — with code that runs.
The agent ran overnight and had failed by morning. The log held a single error line, and nothing in it said which cycle, which tool call, or why. I had been scattering console.log calls and scrolling from the top, and that stopped working the moment the number of runs grew.
This article is the line I drew after that. It is not a write-up of measured results — only the design that made me feel "if the cycle boundary is recorded, failures read differently."
One premise first. I cannot reach inside Antigravity itself, so the instrumentation here goes into an agent loop you write yourself — a script, a worker, or the tools the agent calls. Antigravity does not emit this span structure out of the box.
Why agents end up in the "I can't tell why it failed" hole
I think the causes cluster into three.
The first is fuzzy step boundaries. An agent cycles through "tool call → LLM inference → state update," and if that boundary is not recorded you cannot tell which step of which cycle broke. A flat, time-stamped log does not show the structure between cycles.
The second is opaque inputs and outputs. The LLM call itself is logged, but the context passed in and the raw response that came back are not. The failure ends as "the LLM said something odd" and cannot be reproduced.
The third is no failure taxonomy. Errors are logged, yet afterward you cannot tell whether a failure was retryable, worth telling the user about, or a plain bug. That leads straight to alert fatigue and a retry policy that falls apart.
Observability design means wiring these three into a structure before you need it.
The base unit of a trace — pick a span structure
I align with OpenTelemetry semantics and represent agent execution like this. The shape is generic, not Antigravity-specific, but adding a "cycle" level is what makes it work for agents.
- agent.run (root span: one full agent execution)
- agent.cycle (one reason-and-act cycle)
- agent.plan (LLM decides the next action)
- agent.tool_call (tool execution, one span per tool)
- agent.observe (fold the result back into context)
- agent.cycle
- ...
The reason to make agent.cycle its own span is simple. If the agent runs eight cycles and fails in the fifth, without a per-cycle span a person has to read logs by eye to extract "the tool died in cycle five."
The implementation is a single call at the start of each cycle. In Python it looks like this — note that running out of cycles is also recorded as a classified failure.
from opentelemetry import tracefrom opentelemetry.trace import Status, StatusCodetracer = trace.get_tracer("antigravity.agent")class AgentError(Exception): def __init__(self, message, failure_class): super().__init__(message) self.failure_class = failure_classdef run_agent(task): with tracer.start_as_current_span("agent.run") as run_span: run_span.set_attribute("task.id", task.id) run_span.set_attribute("task.kind", task.kind) run_span.set_attribute("agent.policy", task.policy_name) run_span.set_attribute("agent.tools_available", list(task.tools)) try: for cycle_idx in range(MAX_CYCLES): with tracer.start_as_current_span("agent.cycle") as cycle_span: cycle_span.set_attribute("cycle.index", cycle_idx) action = plan_next_action(task) if action is None: cycle_span.set_attribute("cycle.terminated", True) run_span.set_attribute("run.cycle_count", cycle_idx + 1) run_span.set_attribute("result.status", "success") return success(task) cycle_span.set_attribute("cycle.action_type", action.kind) result = execute_tool(action) observe(task, result) # Exhausting the loop is also a failure worth classifying raise AgentError("max cycles exceeded", "cycle_budget_exceeded") except AgentError as e: run_span.set_status(Status(StatusCode.ERROR, str(e))) run_span.set_attribute("run.cycle_count", MAX_CYCLES) run_span.set_attribute("result.status", "failure") run_span.set_attribute("result.failure_class", e.failure_class) raise
When an exception escapes a with block, the OpenTelemetry Python SDK records it on the span and sets the status to ERROR by default. You still have to attach failure_class yourself, because the SDK cannot know what a failure means.
In TypeScript (Node.js), the same structure with @opentelemetry/api. A span handed to startActiveSpan is not closed automatically, so call end() in a finally.
Always put cycle.index on agent.cycle. Sooner or later you will want a query like "show me only what happened in cycle three."
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦An OpenTelemetry-aligned four-level span structure (agent.run / agent.cycle / agent.plan / agent.tool_call) with Python and TypeScript implementations
✦An eight-class failure_class taxonomy, and a single table that holds retry and notification policy in one place
✦Three dashboard query examples, plus a storage design that keeps raw I/O and PII out of the trace itself
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
What I deliberately leave out is the raw input and output text. Putting it in the trace inflates storage and invites PII accidents. Raw I/O goes into a separate object store keyed by trace ID, and the trace carries only the storage key.
def record_io(span, payload: bytes, kind: str): # Raw I/O goes to a separate store; the span carries only key and size ctx = span.get_span_context() key = f"{ctx.trace_id:032x}/{ctx.span_id:016x}/{kind}" object_store.put(key, payload) # your own R2 / S3 client span.set_attribute(f"io.{kind}.storage_key", key) span.set_attribute(f"io.{kind}.size_bytes", len(payload))
With this, once you find the trace you care about in Grafana, io.input.storage_key gets you the raw input in one more query. Splitting into "search, then drill down" costs less overall than stuffing long text into attributes. For storage pricing, check the official pricing page of whichever service you choose (Cloudflare R2, S3, and so on) and run your own volume through it.
Failure tags — result.failure_class
Recording every agent failure as a bare "error" is stopping at the front door of observability. I attach one of these eight classes as result.failure_class.
failure_class
Meaning
tool_unavailable
An external API is down, or credentials expired
tool_misuse
The agent passed invalid input to a tool (a prompt-design fault)
model_refusal
The LLM declined on safety grounds
model_hallucination
The LLM tried to call a tool or function that does not exist
cycle_budget_exceeded
The maximum cycle count was exceeded
token_budget_exceeded
The token budget was exceeded
validation_failed
Tool output failed schema validation
unknown_runtime_error
Any runtime error that fits none of the above
This taxonomy is something you grow while operating. Aiming for perfect from day one means you never start, so in the first month I would skim the errors that appear, classify only the frequent ones, drop everything else into unknown_runtime_error, and revisit once a month.
Once the tags are in place you can slice a dashboard down to "only tool_unavailable and validation_failed," and that feeds directly into retry policy and user-facing wording.
Mapping failure_class to retry policy
The biggest payoff of a clean failure_class is that "which failure gets handled how" fits in one table. Below is the starting table I use as a draft. The counts and seconds are examples — tune them to your tools and budget.
The point of this table is to gather design decisions in one place. Adding a new failure_class means updating it here and nowhere else. Once retry logic is scattered across the codebase, operations breaking is only a matter of time.
Dashboard design — three views for "readable in three lines"
After the traces flow into a tool such as Grafana or Honeycomb, these are the three views worth building first. None of them ships as an official template, so you build them against your own schema.
View 1: failed traces in the last 24 hours
Filter on result.status = failure and group by result.failure_class. You see at a glance what is happening most right now. If model_hallucination jumps after a model or environment update, you notice before any user report arrives.
With Loki and OpenTelemetry Logs, the LogQL looks like this.
sum by (failure_class) ( count_over_time( {service="antigravity-agent"} | json | result_status="failure" [1h] ))
View 2: distribution of cycle counts
Chart run.cycle_count for successful agent.run spans. In Honeycomb, a HEATMAP of run.cycle_count split by task.kind shows shifts such as "a task that used to finish in three cycles now takes six." Prompt-design decay shows up in this distribution before it shows up in success rate. For the week after a model switch, checking it daily is a habit that fits.
View 3: error rate per tool over time
For each tool.name, plot the share of calls that ended in an error. A tool degrading bit by bit shows up early. Note that the PromQL below assumes a counter you emit yourself (agent_tool_call_total) — it is not a metric generated automatically from spans.
sum by (tool_name) (rate(agent_tool_call_total{error_kind!=""}[1h]))/sum by (tool_name) (rate(agent_tool_call_total[1h]))
If the attributes are in place as above, building the views themselves should take little time for anyone comfortable writing PromQL or LogQL in a query editor.
Cost visibility — one chart for "what is eating the wallet"
Agents are a domain where cost jumps before you notice. Put cost attributes on the trace and decisions get faster. Add cost.input_tokens, cost.output_tokens and cost.usd_estimate to agent.run, then view the trend per task kind with a query like this.
sum by (task_kind) ( rate(agent_run_cost_usd[1h]))
This too assumes a counter you emit yourself. Compute the estimate as tokens × unit price, and keep the unit price in a config file — prices get revised, and hard-coding them will hurt later.
Only once this is visible do the improvements show up: "one task kind dominates the total," or "we hand over the whole old document every time."
Whether the notice-then-fix loop turns depends on the resolution of what you measure.
Handling PII and audit-grade logging
Agents handle data that can contain users' personal information. A safe rule is to never write PII-prone fields — email addresses, payment details, user text — into trace attributes. Use this flow instead.
Wrap PII-prone text in a SecureBlob type and save it to a dedicated store.
Put only pii.storage_key and pii.kind on the trace.
Require a separate permission to look up the PII store from a trace ID.
This is a minimal posture for GDPR and Japan's personal information law, but operationally it structurally prevents the "it slipped into the logs" accident. It takes one wrapper type to route everything through, so the cost of adopting it is small.
With instrumentation in place, problems that were only a feeling take a form you can reproduce. Here are four typical patterns I expect these views to catch. None of them claims a particular period or number — they are design expectations.
The first is failures concentrated on one external tool. Break tool_unavailable down by tool.name and the concentration is visible. Once it is, a health check before the call and a fallback path, added at that one spot, is enough.
The second is model_hallucination rising right after a model switch. When you can see it, putting a re-evaluation step into every model switch becomes an easy call.
The third is one task kind with an unusually high cycle count. Often the initial context is thin and the agent spends extra cycles gathering information; adding context shifts the distribution to the left.
The fourth is the first few minutes of incident response changing. The time to find the cause becomes the time to read three lines of a trace, not the time to read logs. Observability feels like the area where the first hour of investment pays back best.
Pitfalls once this runs in production
Right after adding instrumentation, the trouble is often not an error but "something I should see is missing," so here are the pitfalls up front.
Pitfall
Symptom
Fix
Forgetting end()
The span never closes and never reaches the backend; one run is missing from the dashboard
Close in a finally in TypeScript; prefer the with form in Python
Only successful traces survive
Probabilistic sampling drops the rare failures
Keep every failed trace (tail-based sampling)
Using task.id as a metric label
Series count balloons; storage cost and query time jump
Restrict labels to low-cardinality values such as task.kind and failure_class
Not recording exit by cycle limit
A failure is reported with a success status
Tag the path that exhausts the loop with cycle_budget_exceeded too
In my case the sampling setting was the pitfall that lingered longest. Before moving to production, I recommend deliberately failing a run once and confirming that the trace shows up in the list.
Recommended adoption order
For anyone starting now, these are the four steps I would take if I were doing it again from zero.
Add only the agent.cycle span — one start_as_current_span("agent.cycle") in the existing loop makes the cycle boundary visible.
Define just five failure_class values — pick the ones most frequent in your agents from the eight above and attach them as result.failure_class.
Build dashboard view 1 — a list of failed traces is enough to change how you respond to incidents.
Add cost attributes — put cost.usd_estimate on agent.run and watch the trend per task kind.
The remaining classes and views can be added little by little as you operate.
Start today with a single line in your loop — the agent.cycle span.
Your ability to read a failure is set not by how much you log, but by how many boundaries you record. For a while I had the order backwards, and kept reaching for more logs.
Thank you for reading.
Share
Thank You for Reading
Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.