# Notes from a 2 AM On-Call: docker-android MCP Loops and a Dead Prompt Cache

> Source: <https://dev.to/jj657/notes-from-a-2-am-on-call-docker-android-mcp-loops-and-a-dead-prompt-cache-5dhj>
> Published: 2026-11-30 14:08:06+00:00

**Recommendation:** Filter accessibility-tree dumps to interactive, text-bearing nodes and sort them deterministically before sending, and keep the system prefix static so cached_tokens stays above zero.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>



```
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.
