Why Agent Loops Run Away and How Step Budgets Stop Them
Why tool-calling agents loop until something kills them, the quadratic token cost of every extra step, and how step budgets and loop detectors stop it.
50 in-depth guides with playable labs on agents and protocols, LLM internals, inference serving and production RAG.
Every guide in this series pairs a deep, production-focused article with an interactive lab you can play right on the page. Each lab is a small deterministic simulation with missions: start from a broken setup, change the controls, and earn up to three stars by meeting a target the way an engineer would in production.
The labs are synthetic teaching models. Their numbers are calculated estimates that make a mechanism visible; they are not benchmarks of any real model, GPU or service.
Agent loops, tools, memory, MCP, A2A and the controls that keep autonomous systems bounded.
Why tool-calling agents loop until something kills them, the quadratic token cost of every extra step, and how step budgets and loop detectors stop it.
Why agent retries and re-plans repeat refunds and emails, how idempotency keys deduplicate them, and how to choose the key, the scope and the retention.
What to drop, summarise or pin when a long-running agent fills its context window, with the cost arithmetic and the failure modes of each strategy.
Why MCP sessions break behind load balancers, what revision 2026-07-28 changed in Streamable HTTP, and how keep-alives and idempotency stop lost calls.
How hidden instructions in MCP tool descriptions hijack agents, and how scanning, hash pinning, taint policies, routing and confirmations stop them.
How MCP authorization uses OAuth 2.1, resource indicators and audience checks so a token for one server cannot open another, with lifetime and scope maths.
How A2A tasks fail in production when streams drop, webhooks miss or agents restart, and how SubscribeToTask, retries and reconciliation recover them.
When splitting an agent into a supervisor and specialists, or a swarm of peers, beats one agent: the arithmetic of tool count, handoffs, tokens and latency.
Why agents pick the wrong tool once the catalog reaches hundreds, what every definition costs per call, and how retrieval and grouping route each request.
Why long-term agent memory goes stale, wrong or poisoned, and how write gates, reconciliation, decay and provenance keep it accurate over months.
Why gating every agent tool call fails twice: reviewers fatigue and queues grow. How to size, tier and time out approval gates with the actual arithmetic.
Why pass@k flatters agents that fail users, how pass^k and trajectory grading measure reliability, and how many tasks and trials an honest eval needs.
Tokenizers, attention, sampling, preference training, quantization and calibration, from the inside.
Why the same message can cost several times more tokens in Hindi or in nested code, how byte-level BPE merges decide it, and what to measure before you budget.
Why the KV cache, not the weights, caps concurrency, how grouped-query attention cuts it 4x or more, and what conversion and FP8 cost in quality.
Why RoPE models break just past their trained context, how interpolation, NTK scaling and YaRN remap angles, and what each costs in quality and compute.
How temperature, top-k, top-p, min-p and repetition penalties change the next-token distribution, which failure each one fixes, and what each one breaks.
How MoE routers pick experts, why capacity factors drop tokens, how load balancing works, and what imbalance costs in latency and quality when serving.
How JSON schema mode turns a grammar into per-token masks, what the masks cost in latency, and why valid JSON can still contain invented values.
How thinking-token budgets trade accuracy for cost and latency, where extra reasoning stops paying, and when routing or majority voting beats a bigger budget.
How RLHF with PPO, DPO and GRPO turn preferences into gradients, what beta and group size really control, and how reward hacking shows up.
What LoRA rank, alpha and target modules really control, the parameter and memory arithmetic, and how to pick settings that learn without overfitting.
Why INT4 weights work for most layers but break a few: the rounding arithmetic, outliers, group size, zero points and activation-aware scaling.
How to split a training budget between parameters and tokens with Chinchilla-style scaling laws, and when serving cost or a data wall should change it.
How to turn token logprobs into confidence you can act on: reliability diagrams, ECE, temperature and Platt scaling, abstention thresholds and drift.
Batching, KV cache, scheduling, autoscaling, routing and caching for production LLM serving.
Why request-level batching strands GPU slots behind the longest sequence, how iteration-level scheduling fixes it, and the per-token latency it costs.
Why reserving KV cache for the maximum length wastes most GPU memory, how block tables page it like an OS, and how to pick block size and memory.
How a radix tree lets an LLM server reuse KV for shared prompt prefixes, why one timestamp can zero the hit rate, and how routing keeps hits.
Why vLLM evicts running requests when KV blocks run out, what swap and recompute cost, and how to size memory and admission to avoid preemption storms.
When separate prefill and decode GPU pools beat colocated serving: interference, KV transfer bandwidth, the pool ratio and goodput per GPU.
Why one long prompt can pause every stream on a GPU, how chunked prefill bounds each step, and how to pick the token budget from the roofline.
How to turn GPU memory, model shape, KV dtype and tensor parallelism into a KV token budget, concurrent sequences and users per GPU, with worked numbers.
Why tokens per second and mean latency hide unhappy users, how to define TTFT and TPOT SLOs, and how to measure goodput: requests that meet both.
GPU utilization reads 100% at a tenth of an LLM server's capacity. Learn which signals to autoscale on, how much headroom cold starts need, and why.
Most LLM queries do not need your largest model. Learn the cost, accuracy and latency arithmetic of cascades and routers, and how each fails in production.
Request limits let one long-context tenant starve everyone. Learn token buckets, max_tokens reservation, bucket sizing, fair queueing and priority lanes.
When a model outgrows one GPU you can split layers or split matrices. Learn the memory, latency and communication arithmetic that decides between TP and PP.
How semantic caches decide a hit, why one cosine threshold trades LLM cost against wrong answers, and how to calibrate, scope and invalidate safely.
Chunking, vector indexes, hybrid retrieval, reranking, freshness, permissions and RAG evaluation.
Fixed, recursive, semantic and late chunking compared on the numbers that matter: answers split, recall@k, context tokens per query and index size.
How HNSW layers, M, efConstruction and efSearch set recall, latency and memory, why filters and deletes break it, and how to tune it.
Why dense retrieval misses codes and rare terms, how reciprocal rank fusion with BM25 recovers them, and how to tune k, weights and list depth.
How deep a cross-encoder should rerank: the recall ceiling, diminishing nDCG gains, per-pair GPU cost and the queueing that makes p95 explode.
How int8, int4 and binary embeddings cut vector index memory by 4x to 32x, why recall drops, and how calibration and rescoring win it back.
Why raw user queries miss in RAG, how condensing, multi-query and HyDE fix them, and how rewrites break exact IDs, add latency and drift.
A stage-by-stage method for tracing wrong RAG answers to coverage gaps, retrieval misses, prompt truncation or generation errors, with the arithmetic.
How post-filtering, filtered HNSW, pre-filter scans and query planners enforce document ACLs in RAG, why recall collapses, and how revocations leak.
How RAG indexes go stale, why deletes become tombstones that slow search, and how change capture, chunk IDs and compaction keep answers current.
Why answers buried mid-prompt get ignored, how to order, dedupe and pack retrieved chunks under a token budget, and how to test position effects in production.
Why one vector search cannot answer bridge questions, how iterative retrieval and decomposition chain hops, and the latency, cost and error compounding each adds.
Why a citation marker proves nothing until checked, how claim-level entailment verification works, and how to trade unsupported claims against recall and cost.
Where time goes in a RAG request, why p95 is not the sum of stage medians, and how rewrite, rerank depth, prompt size and hedging move time to first token.
Views are my own and do not represent any employer, past or present.