Catching "Running but Doing Nothing" Antigravity Subagents — A 3-Layer Observability Pattern
Logs green, output zero — the silent failure every overnight Antigravity subagent eventually produces. A three-layer design (Heartbeat / Output Trace / Decision Log) that tells missed starts, stale inputs, and write-less loops apart, with the SQL and code to copy.
At 2 a.m. the Cloud Scheduler dashboard was a wall of green "success" rows. In the morning I opened the store and nothing had changed since the night before. The first month after I handed nightly update jobs to Antigravity subagents, I woke up to mornings like that more than once.
There were no errors and no exceptions. The agents had run — they just hadn't actually done anything. I had always assumed the painful incidents arrive when something crashes.
Nothing crashed, so I had no way to notice. That is what separated this from every outage I was used to.
This article is the implementation memo for the three-layer observability design I built afterward: Heartbeat, Output Trace, and Decision Log. It is how I keep "running but doing nothing" out of production — the state Antigravity's own run screen does not surface — with the code and SQL included.
The one principle I want to put first:
Don't count whether the agent finished. Count whether the world changed — from outside the agent.
The Three Archetypes of Silent Failure — stale context / no-op loop / silent retry
Let me pull "silent failure" apart into three shapes first. Run Background Agents or subagents long enough and you will meet at least one of them.
stale context — treating an old snapshot as ground truth
The agent does exactly what you asked. But the repository snapshot or AdMob report cache it is reading is hours or days old, so it concludes "nothing changed" and does nothing.
Real quiet days exist too, so you cannot simply equate "zero output" with "failure." That was the awkward part.
no-op loop — tasks advance but no side effect ever happens
Tool calls do happen, but they are all read-only: grep, read_file, and the like. The agent ends with "conclusion: no issues" and exits normally.
The write-side tools you actually wanted — write_file, gh pr create — were never called.
silent retry — internal retries swallow the real error
When an external API returns a 5xx, the subagent's own retry policy quietly tries again. After a few attempts it returns the same stale result as the first try and finishes. The log says success, but the API's current state never made it in.
The three look different, so each needs its own detection logic — and I took a detour before I understood that. My first attempt was one catch-all alert, and it drowned in false positives until I stopped trusting it.
The 3-Layer Picture, and Why the Stacking Order Matters
To catch silent failures you need three independent sources of truth, kept outside the agent in separate channels.
Layer 1 Heartbeat — measure from outside whether the agent started and finished
Layer 2 Output Trace — compare hashes to confirm the artifacts actually changed
Layer 3 Decision Log — record tool calls so you can answer "why didn't anything change?"
The order has a reason. Build Decision Log first and the volume balloons until nobody can read it, and the whole effort stalls. Heartbeat plus Output Trace already covers most of the archetypes. I recommend shipping that light pair first and using Decision Log to close what remains.
How the archetypes map to the layers:
Archetype
Heartbeat
Output Trace
Decision Log
Never started (outside the three)
◎ caught by matching against dispatch
—
—
stale context
×
◎ reference vs input hash mismatch
○ rising empty ratio
no-op loop
×
○ changed stays false
◎ zero write-side tool calls
silent retry
○ attempt is 2 or more
○ output identical to last run
◎ repeated calls with identical arguments
The data flows one way:
Cloud Scheduler (cron)
↓ HTTP POST
Dispatcher (Cloud Run) ── writes a dispatch row to BigQuery (issues start_token)
↓ starts the agent with start_token
Antigravity Subagent (your workload)
├─ [Layer 1] Heartbeat → BigQuery (duration, exit_code, attempt)
├─ [Layer 2] Output Trace → BigQuery (hashes of reference, input, output)
└─ [Layer 3] Decision Log → BigQuery (tool, result kind, side effect)
↓
Scheduled queries (every few minutes via Cloud Scheduler)
↓
Slack #ops (minor) / PagerDuty (severe)
✦
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
✦A minimal setup that separates "clean exit, zero output" using an externally issued start_token and three kinds of hashes
✦Which layer and which query catches each of the three archetypes: stale context, no-op loop, silent retry
✦A Cloud Scheduler + BigQuery + Slack/PagerDuty stack, and the pitfalls of log volume, leaked secrets, and retention
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.
Layer 1 Heartbeat — match the promise to start against the report of finishing
The heart of Layer 1 is issuing start_tokenoutside the agent. If the agent issues it, you can never detect "the day the agent didn't even start."
Cloud Scheduler calls a Dispatcher (a tiny Cloud Run service). The Dispatcher issues the start_token, writes a "promised to start" row into a dispatch table, and launches the agent. Just before exit, the agent writes a Heartbeat row with the same start_token.
So a missed start shows up simply as a promise row (dispatch) with no report row (heartbeat).
// src/observability/heartbeat.tstype HeartbeatPayload = { start_token: string; // UUIDv4 issued by the Dispatcher agent_name: string; // e.g. "wallpaper-nightly-refresh" started_at: string; // ISO8601 finished_at: string; // ISO8601 duration_ms: number; exit_code: 0 | 1 | 2; // 0=ok, 1=app-error, 2=infra-error triggered_by: "scheduler" | "manual" | "retry"; attempt: number; // 1 = first run, 2+ = retry};export async function emitHeartbeat(p: HeartbeatPayload) { try { const res = await fetch( "https://bigquery.googleapis.com/bigquery/v2/projects/PROJ/datasets/obs/tables/heartbeat/insertAll", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${await getAccessToken()}`, }, // Never make the agent wait on observability signal: AbortSignal.timeout(3000), body: JSON.stringify({ // Include attempt so retry rows are not deduplicated away rows: [{ insertId: `${p.start_token}:${p.attempt}`, json: p }], }), } ); if (!res.ok) console.error("heartbeat insert failed", res.status); } catch (e) { // Even if this fails, do not take the agent down. The missing row is caught by the next query. console.error("heartbeat insert threw", e); }}
I put attempt into insertId so second and later attempts are not dropped as duplicates. At first I used start_token alone, and the trace of silent retries had vanished before I realised it.
The query that finds missed starts
Look for dispatch rows with no matching heartbeat. Keeping a grace_minutes value on the dispatch side — normal duration plus some slack, per agent — stops long and short jobs from being judged by one threshold.
SELECT d.start_token, d.agent_name, d.dispatched_atFROM `PROJ.obs.dispatch` AS dLEFT JOIN `PROJ.obs.heartbeat` AS h USING (start_token)WHERE d.dispatched_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 6 HOUR) AND TIMESTAMP_ADD(d.dispatched_at, INTERVAL d.grace_minutes MINUTE) < CURRENT_TIMESTAMP() AND h.start_token IS NULL;
One returned row means "a promised start was never fulfilled" — PagerDuty territory.
What Heartbeat catches, and what it cannot
Heartbeat can catch:
A promised start with no report of finishing (failed start, crash mid-run)
Duration far beyond that agent's normal range
exit_code other than 0
attempt of 2 or more, meaning a retry happened
What it can never catch is the opening scenario: exit_code=0, normal duration, zero output. Layer 2 takes that over.
Layer 2 Output Trace — three hashes separate "did it change?" from "was it looking at the right world?"
Judging only by "did the output change" misses stale context, because an agent working from an old snapshot can still make a correct change by accident.
So I keep three hashes.
Hash
Who reads it
Role
reference_hash
Outside the agent (e.g. the Dispatcher)
The correct current value at run time
input_hash
The agent itself
The value the agent actually looked at
before_hash / after_hash
Outside the agent
State of the artifact before and after
If reference_hash and input_hash disagree, that is stale context — decidable regardless of whether the artifact changed.
For a nightly wallpaper-asset refresh, the targets could be these three:
Target
How to hash
How to read a change
Files added to a GCS bucket
SHA256 of gsutil ls -l output
Zero additions is a no-op candidate
Firestore releases/latest document
Normalise the fields, then SHA256
Unchanged means the update was skipped
AdMob ad unit eCPM floor settings
SHA256 of the API response
Identical means no update
The Python helper that records them:
# scripts/observability/output_trace.pyimport hashlibimport jsonfrom datetime import datetime, timezonefrom google.cloud import bigquerybq = bigquery.Client()def normalize(value) -> str: """Normalise dict / list / str into a string that does not depend on key order.""" return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))def hash_value(value) -> str: return hashlib.sha256(normalize(value).encode("utf-8")).hexdigest()def emit_output_trace(start_token: str, target: str, *, before, after, seen_input, reference): row = { "start_token": start_token, "target": target, "reference_hash": hash_value(reference), # read directly from outside "input_hash": hash_value(seen_input), # what the agent looked at "before_hash": hash_value(before), "after_hash": hash_value(after), "captured_at": datetime.now(timezone.utc).isoformat(), } row["changed"] = row["before_hash"] != row["after_hash"] row["stale_input"] = row["reference_hash"] != row["input_hash"] errors = bq.insert_rows_json( "PROJ.obs.output_trace", [row], row_ids=[f"{start_token}:{target}"] ) if errors: print("output_trace insert errors:", errors) # do not stop the agent return row
Telling a quiet day from a sick one — keep expectations in a table
How often a target should change in seven days differs wildly from target to target. Hard-coding thresholds in SQL means editing it every time a target is added. I keep the expected minimum and maximum in an expectation table and JOIN against it.
WITH last7 AS ( SELECT target, COUNTIF(changed) AS change_count, COUNT(*) AS runs FROM `PROJ.obs.output_trace` WHERE captured_at >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY) GROUP BY target)SELECT e.target, COALESCE(l.change_count, 0) AS change_count, COALESCE(l.runs, 0) AS runs, CASE WHEN COALESCE(l.change_count, 0) < e.min_changes_7d THEN 'WARN_underchange' WHEN l.change_count > e.max_changes_7d THEN 'WARN_overchange' ELSE 'OK' END AS statusFROM `PROJ.obs.expectation` AS eLEFT JOIN last7 AS l USING (target)ORDER BY status DESC;
Starting from the expectation table with a LEFT JOIN means a target with no Output Trace rows at all still surfaces as WARN_underchange. Aggregating from the run side would never show that kind of gap.
Anything above max_changes_7d is treated as over-updating — a runaway dependency bot or a double-started agent.
Layer 3 Decision Log — leave "why did it do nothing?" in tool calls
With two layers you can detect that something happened. What remains is why.
Antigravity's run log is natural-language and hard to grep later. So I wrap the agent's tool definitions one level and ship each tool call as one structured row to BigQuery. The key is tagging each tool as read or write. That tag alone is enough to spot a no-op loop.
// src/observability/decision_log.tsimport { createHash } from "node:crypto"; // enable nodejs_compat on Workerstype DecisionLog = { start_token: string; tool: string; // e.g. "read_file" side_effect: "read" | "write"; // the key to no-op loop detection arguments_hash: string; // SHA256 of arguments (never ship raw arguments) result_kind: "ok" | "empty" | "error"; // "empty" is a clue to no-op result_size_bytes: number; ts: string;};const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");declare function emitDecisionLog(log: DecisionLog): Promise<void>;export function withDecisionLog<TArgs, TRet>( toolName: string, sideEffect: "read" | "write", startToken: string, fn: (args: TArgs) => Promise<TRet>) { return async (args: TArgs): Promise<TRet> => { let kind: DecisionLog["result_kind"] = "ok"; let size = 0; try { const result = await fn(args); if (result == null || (Array.isArray(result) && result.length === 0)) { kind = "empty"; } size = new TextEncoder().encode(JSON.stringify(result ?? null)).length; return result; } catch (e) { kind = "error"; throw e; } finally { // Don't wait for the log; a failure must not affect the agent void emitDecisionLog({ start_token: startToken, tool: toolName, side_effect: sideEffect, arguments_hash: sha256(JSON.stringify(args)), result_kind: kind, result_size_bytes: size, ts: new Date().toISOString(), }).catch(() => {}); } };}
I log only arguments_hash to keep secrets out, which the pitfalls section returns to. And a run of calls with the same hash in a short window is, by itself, enough to raise a silent-retry suspicion.
Find runs with zero writes (no-op loop)
SELECT start_token, COUNT(*) AS total_calls, COUNTIF(side_effect = 'write') AS write_callsFROM `PROJ.obs.decision_log`WHERE ts >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)GROUP BY start_tokenHAVING total_calls > 0 AND write_calls = 0;
A run that only read is normal on a quiet day and a no-op loop otherwise. Which one it is gets decided when you read it together with the Layer 2 expectation. On its own I don't call it.
Checking the "empty ratio" every morning
As a daily health check I also watch the share of tool calls that came back empty.
SELECT h.agent_name, DATE(d.ts, "Asia/Tokyo") AS run_date, COUNT(*) AS total_calls, COUNTIF(d.result_kind = "empty") AS empty_calls, ROUND(COUNTIF(d.result_kind = "empty") / COUNT(*) * 100, 1) AS empty_pctFROM `PROJ.obs.decision_log` AS dJOIN `PROJ.obs.heartbeat` AS h USING (start_token)WHERE d.ts >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)GROUP BY h.agent_name, run_dateHAVING empty_pct >= 30ORDER BY empty_pct DESC;
The 30% is not a universal rule. It is a provisional starting line. Collect a week or two of data, learn that agent's normal empty ratio, then move the line to fit your own setup. Starting loose (say 50%) and tightening gradually saves you from false-positive fatigue.
On days the ratio spikes, I run a context reset — fresh clone of the repository and a cache wipe. That has worked well against stale-context failures.
The Alert Priority Matrix — Slack vs PagerDuty
Once all three layers emit signals, the next question is which ones are worth being woken for. I first sent everything to PagerDuty and was worn out within days. This is the split I run now.
Signal
Slack #ops (minor)
Slack #ops-alert (moderate)
PagerDuty (severe)
Heartbeat: promised start with no report
◯
Heartbeat: duration several times normal
◯
Heartbeat: exit_code other than 0
◯
Output Trace: stale_input is true
◯
Output Trace: consecutive no-ops
◯ (escalate after 3 days)
Output Trace: over-updating (runaway suspected)
◯
Decision Log: empty ratio over threshold
◯
Decision Log: consecutive errors
◯
In short, a no-op alone never rings at night. No-op can be a healthy day, so it collects in minor Slack first and moves up only if it persists. Since adding that step, false midnight calls have nearly disappeared.
Pitfalls — log volume, leaked secrets, and retention
Three traps I stepped into in the first weeks after adopting this.
Shipping raw payloads and losing sight of the bill
I started by sending the raw JSON result straight to BigQuery instead of result_size_bytes. A Cloud Billing alert arrived within days and I stopped it in a hurry.
My line now: BigQuery gets only size and kind; if the body is needed, keep it briefly in GCS with an Object Lifecycle rule. Most Layer 3 bloat comes from this one point.
Raw arguments, and an API key in the log
During a stretch when I shipped arguments as-is instead of arguments_hash, an external API's request header ended up in the log. I deleted the rows and reissued the key, so it was contained, but I learned how easily secrets slip into an observability pipeline.
Always put a hash step in between. If you truly must keep raw arguments, separate them into a dedicated table and tighten IAM — that is the minimum line.
Retention left unset, and logs piling up
I had not set a table expiration in BigQuery, so logs accumulated without limit. My defaults now keep Heartbeat longer and Decision Log shorter — the finer the granularity, the shorter the retention.
ALTER TABLE `PROJ.obs.decision_log`SET OPTIONS ( partition_expiration_days = 14, description = "Decision logs: short retention (raw payloads live in GCS)");
Partition expiration assumes the table is date-partitioned. Create it with PARTITION BY DATE(ts).
A Minimal Starting Path — one layer at a time, in order
Here is the minimum to put into your own agent starting tomorrow. Stacking one layer at a time ends up faster than building everything in one day.
Build only dispatch and Heartbeat (half a day). Two BigQuery tables, one emitHeartbeat function, and one Dispatcher that issues start_token
Wire a single missed-start query to Slack (30 minutes). No complex rules
Run for a week, then add Output Trace for one target. Decide the expectation values from that week's actuals
Add Decision Log one to two weeks later. Start the empty-ratio threshold loose
Connect to PagerDuty only the signals that Slack taught you are worth waking up for
Build all three at once and false positives pile up until you stop reading the alerts. A week of Heartbeat alone gives you a feel for how long each agent usually takes and how often it succeeds. I think the thresholds for Layers 2 and 3 can only be set once you have that feel.
Observability starts with learning the ordinary sound of your own setup, before adding layers. Please try wiring in just the Heartbeat today.
If this helps your operations, I would be glad. May there be a few more mornings when you wake up without dreading the overnight notifications.
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.