Notes from a 2 AM On-Call: docker-android MCP Loops and a Dead Prompt Cache A developer running an Android UI-crawl agent inside budtmo/docker-android traced a 2 AM on-call failure to two compounding bugs: full uiautomator XML dumps of 28k–40k tokens overflowing a 32k-context model, and a prompt cache that never hit (cached_tokens=0 across 47 steps). Truncated completions caused the agent to lose its visited-screen set and re-open Help screens, stacking adb calls until the container was OOMKilled at its 4Gi limit. The fix filters the accessibility tree to clickable or focusable nodes with non-empty text, dedupes and sorts them for byte-stable output, hard-caps the suffix, and keeps a static system message as the cache key. 02:17:41Z step=47 prompt tokens=184220 cached tokens=0 finish reason=length 02:17:41Z adb: device 'emulator-5554' offline 02:18:06Z mcp websocket close code=1006 02:18:09Z docker: container docker-android OOMKilled exit 137, memory limit 4Gi That was the page. A crawl indexing in-app help screens from our Android client, running inside budtmo/docker-android, had looked fine for twenty minutes. Token spend was not on the dashboard. By the time the emulator died, that one job was already past the daily cap on the relay. We drive the emulator from an agent talking to the MCP server that ships with the image. noVNC on 6080 is only so a human can watch. The agent uses adb on 5555. Each step dumped the UI with uiautomator dump , read the XML, and sent the whole file to the model with the tool schema and the action history. The model pinned for this job accepts 32k context. Step 12 was the first finish reason=length . The truncated completion lost the tail of the visited-screen set, so the next action opened Help again. The loop re-dumped the same hierarchy, appended another copy to history, and truncated harder. adb shell calls stacked faster than adbd reaped them. Screencap temps and logcat filled the 4Gi limit. Exit 137 is the container dying. The cause was a prompt that could not stay inside its window, and an agent that treats truncation as a reason to keep clicking. The MCP-plus-emulator notes we started from all do the same thing: dump the full accessibility tree, paste it into the user message, let the model decide. On a five-step demo that works. The dump is small and history is short. This job is not a demo. It walks every Help destination and stores the visible strings for a RAG corpus. Chunking and embedding happen later, offline. A real window dump.xml from this app is 1.1–1.6 MB, about 28k–40k tokens, and most of that is the status bar, nav chrome, and WebView nodes with empty text. One pass is wasteful. The retry loop is the failure: uncached prefix plus dump plus history exceeds 32k, and a truncated agent does not stop. It forgets which node it already pressed. None of those notes mention prompt caching. The system text, the tool JSON, and the output contract were identical on every step and were billed as fresh input 47 times. cached tokens=0 all night. The context builder drops the raw dump. It keeps nodes that are clickable or focusable and that have non-empty text or content-desc . It dedupes on resource-id , bounds, and text, then sorts by that key so an unchanged screen is the same bytes. The suffix is hard-capped. node count is in the payload so the model can see a cut list instead of discovering the cut via finish reason=length . Calls go through the same OpenAI-compatible relay as the rest of the RAG stack, https://b-lost.com/v1 , so a cache hit on this prefix behaves like a cache hit on our other cached prefixes. The system message is the cache key. It does not change between steps. python import hashlib, os, xml.etree.ElementTree as ET from openai import OpenAI client = OpenAI base url="https://b-lost.com/v1", api key=os.environ "RELAY API KEY" , PREFIX = "You operate one Android emulator via the tools provided. " "Return one JSON object with keys action, target id, done. " "Do not repeat a target id listed under visited." def nodes from dump xml bytes: bytes, limit: int = 80 - list dict : root = ET.fromstring xml bytes seen, out = set , for n in root.iter "node" : text = n.attrib.get "text" or n.attrib.get "content-desc" or "" .strip live = n.attrib.get "clickable" == "true" or n.attrib.get "focusable" == "true" if not text or not live: continue key = n.attrib.get "resource-id", "" , n.attrib.get "bounds", "" , text if key in seen: continue seen.add key out.append { "id": hashlib.sha1 "|".join key .encode .hexdigest :12 , "rid": key 0 , "text": text :120 , } out.sort key=lambda r: r "rid" , r "text" return out :limit def step xml bytes: bytes, visited: list str , step index: int : nodes = nodes from dump xml bytes suffix = {"nodes": nodes, "visited": visited -30: , "node count": len nodes } blob = str suffix if len blob // 4 1800: raise RuntimeError f"suffix over budget: ~{len blob // 4} tokens" resp = client.chat.completions.create model=os.environ "AGENT MODEL" , temperature=0, messages= {"role": "system", "content": PREFIX}, {"role": "user", "content": blob}, , usage = resp.usage details = getattr usage, "prompt tokens details", None cached = getattr details, "cached tokens", 0 if details else 0 if step index 0 and cached == 0: raise RuntimeError f"cache miss on warm step: prompt={usage.prompt tokens}" return resp.choices 0 .message Get the bytes with adb connect localhost:5555 , then adb exec-out uiautomator dump /dev/tty or dump to /sdcard/window dump.xml and adb exec-out cat it . Pass those bytes to step . Do not base64 a screencap into this message. Pixels, if a later step needs them, are a separate call with a separate budget. Same 40-screen crawl, same model, same image, 4Gi limit: | | before | after | |---|---|---| | median prompt tokens / step | 39,400 | 6,050 | | cached tokens / step after step 1 | 0 | 4,780 | | steps with finish reason=length | 29 / 40 | 0 / 40 | | uncached tokens, full job | ~1.58M | ~56k | | emulator result | exit 137 at step 47 | crawl finished | | TTFT, prefix-heavy step, via https://b-lost.com/v1 https://b-lost.com/v1 | 740 ms cold | 410 ms cache hit | The 330 ms TTFT gap is the cache read on the ~4.8k prefix, not a faster emulator. The OOM stopped once the agent quit re-dumping screens it had already stored. The 4Gi limit stays. The OOM killer is no longer the loop detector. Chunking stays on the stored strings, after the loop. Putting chunk boundaries into the live prompt added a third copy of the same text and made the prefix unstable, which is a cache miss on every step. If cached tokens is 0 on any step after the first, or the variable suffix estimates over 1,800 tokens, the worker exits non-zero before it touches adb again. A raw window dump.xml is never a prompt argument.