2048 with AI suggestions

Single-player 2048 with an optional AI coach (LLM via Ollama or Expectimax), Auto Play, and local ops (Phoenix traces + Prometheus / Grafana).

1. Stack

Client

Vite + React. Board rules local; suggest over HTTP.

API

FastAPI. LLM via Ollama, or depth-limited expectimax.

Traces

OTLP → Phoenix on the host (optional collector).

Metrics

GET /metrics → Prometheus → Grafana (Compose profile).

2. Topology

Same-origin proxy to the API. Prometheus scrapes the API; Grafana only talks to Prometheus. Phoenix receives OTLP from the API.

flowchart LR
  UI[Client] --> Proxy[Vite / nginx]
  Proxy -->|/suggest · /client-events| API[FastAPI]
  API -->|LLM| Ollama
  API -->|OTLP| Phoenix
  Prom[Prometheus] -->|scrape /metrics| API
  Grafana --> Prom
          

3. Client

Board starts with a random count of 2s (1–16); hard win at 2048. Pick mode → AI (or Auto Play) → hint + Play. Stop during Thinking aborts the in-flight suggest. Auto Play retries on capacity-busy 429 and model fallback; stops on spend-cap 429.

2048 UI with an Expectimax suggestion comparing the other directions to Up, and Play Up
Live UI: Expectimax hint comparing other directions and confirm via Play.

4. Suggest path

Order: validate → spend ceiling → capacity gate → legality → mode. Invalid bodies do not consume either gate. Two distinct 429s per mode: spend (too many suggestions / X-Suggest-Limit: spend) vs capacity (model busy / X-Suggest-Limit: capacity). Disconnect returns 499 and refunds the spend token / frees the in-flight slot.

flowchart TD
  In[board + mode] --> V{valid?}
  V -->|no| X422[422]
  V -->|yes| S{spend ceiling}
  S -->|over| X429s["429 spend"]
  S -->|ok| C{mode capacity?}
  C -->|full| X429c["429 capacity + refund spend"]
  C -->|ok| L{legal moves?}
  L -->|none| X409[409]
  L -->|yes| M{mode}
  M -->|expectimax| EX[search + scores]
  M -->|llm| LLM[Ollama + retries]
  EX --> OK[SuggestResponse]
  LLM --> OK
  EX -->|disconnect| C499[499 + refund]
  LLM -->|disconnect| C499
          

5. Cancel

Client aborts the fetch on Stop / move / New Game / mode change. Server watches disconnect on /suggest, cancels that run only, responds 499. The UI stays silent; the browser beacons cancel so Grafana can see abandons.

sequenceDiagram
  participant UI
  participant API
  participant LLM as Ollama
  UI->>API: POST /suggest
  API->>LLM: chat
  UI-->>API: abort / disconnect
  API-->>LLM: cancel
  API-->>UI: 499
  UI->>API: POST /client-events cancel
  Note over UI: silent — no failure hint
          
  • Abort stays silent in the UI (no “AI could not suggest”).
  • Beacon outcome is cancel, not fail; GenAI scrape can show cancelled when an Ollama attempt had already opened.
  • Token-matched abort still ends Auto Play so the loop cannot stall.
  • Spend token + in-flight slot release on cancel; siblings keep their own slots.

6. Ops split

Same topics (latency, failures) can appear in both places — the systems answer different questions and do not replace each other.

flowchart TB
  subgraph phoenix [Phoenix — one request]
    Q1["Why did *this* suggest fail?"]
    A1["Prompt · retries · span tree"]
    Q1 --> A1
  end
  subgraph grafana [Grafana — over time]
    Q2["Is fallback or 429 rising?"]
    A2["Rates · p50/p95 · token burn"]
    Q2 --> A2
  end
          
  • Phoenix — push OTLP traces; high-cardinality forensics (prompt text, TTFT on the span).
  • Prometheus / Grafana — pull GET /metrics; low-cardinality aggregates.
  • HTTP 200 can still be model fallback — API status ≠ LLM outcome.

7. Phoenix

No browser OTel SDK. The client sends a hand-rolled W3C traceparent on POST /suggest; FastAPI continues that trace into the suggest / LLM spans.

flowchart TB
  UI["Client creates traceparent"] --> HTTP["POST /suggest span"]
  HTTP --> SUG["suggest span
board · mode · result"] SUG -->|"llm mode only"| LLM["ollama chat span
prompt · completion · tokens"] SUG -->|"expectimax"| EX["no ollama chat span"] LLM --> EV["span events: TTFT · generation done"]
  • Open a suggest in Phoenix → one tree: HTTP → suggest → optional ollama chat.
  • On ollama chat → prompt/completion, model name, token counts, ERROR on bad JSON / illegal move / transport fail.
  • Retries → multiple ollama chat children under the same suggest.
  • Not traced — /health, /metrics, /client-events (scrape noise).
  • Host collector only (not in Compose). Opt in with EXPORT_TRACES=true when Phoenix runs.
UI screenshot — Phoenix span tree + detail
Phoenix Traces view with POST /suggest expanded to suggest and ollama chat
Trace list / tree: expand POST /suggest → suggest → ollama chat.
Phoenix span detail for POST /suggest showing tree, Input board JSON, and Output move
Open a root POST /suggest: tree on the left; Input (board + mode) and Output (move + reason) on the right. Click ollama chat for prompt / completion / tokens.

8. Metrics (Grafana)

Always-on scrape at GET /metrics. Compose --profile metrics runs Prometheus + a provisioned GenAI ops dashboard. Client outcomes come from thin /client-events beacons (not Phoenix): fail / rate_limit (spend) / model_busy (capacity) / cancel.

flowchart LR
  API["API /metrics"] --> Prom[Prometheus]
  Prom --> Graf[Grafana]
  UI[Client] -->|fail · rate_limit · model_busy · cancel| CE[/client-events/]
  CE --> API
          

What each chart answers (same order as the dashboard rows)

API

POST /suggest by status

Are we getting 200, or 429 / 422 / 409 / 499?

Suggest by source

Is the coach returning llm, expectimax, or fallback?

POST /suggest latency

Wall-time p50 / p95 for /suggest under load.

In-flight HTTP requests

Overlapping POSTs right now (usually 0; spikes = multi-tab / slow LLM).

Suggest limit rejects

Capacity-busy vs spend-cap 429 volume (suggest_limit_reject_total).

Client

Client suggest outcomes

Browser beacons: fail vs spend rate_limit vs capacity model_busy vs cancel.

LLM

LLM request success rate

Share of Ollama attempts that succeed (cancelled excluded).

LLM requests by outcome

Success vs error / timeout / cancelled over time.

LLM errors by type

Which failure modes dominate when the model path breaks?

LLM call duration

Model-call p50 / p95 (not the full HTTP /suggest time).

Token usage rate by type

Prompt vs completion token burn over time.

  • Stale-token ignores do not beacon; aborts beacon cancel, not fail.
  • Process-wide rate limit on /client-events bounds beacon volume independently of suggest buckets.
UI screenshot — Grafana GenAI ops (API / Client / LLM)
Grafana GenAI ops — 4-panel API reference capture showing status, source, latency, and in-flight
API — earlier 4-panel reference capture (status / source / latency / in-flight; in-flight stays flat for short Expectimax and spikes on slow LLM calls). The current provisioned row adds a 5th Suggest limit rejects (capacity vs spend) panel beside in-flight.
Grafana GenAI ops — Client suggest outcomes capture during a rate-limit burst showing active fail and rate_limit series
Client — rate-limit burst capture showing active fail and spend rate_limit series (sum by (outcome) (rate(client_suggest_outcome_total[5m])) > 0 hides zero-rate outcomes until capacity model_busy or cancel fire).
Grafana GenAI ops — LLM row: success, outcome, errors, duration, tokens
LLM — success / outcome / errors / duration / tokens. Errors-by-type stays empty when the model path is clean.

9. What to verify

  1. Board / win — new game deals 1–16 opening 2s; reaching 2048 is a hard win.
  2. Expectimax without Ollama — board + AI works; health stays ok.
  3. LLM + Phoenix — host Ollama + collector; open one trace: HTTP → suggest → ollama chat (prompt visible).
  4. Cancel — Auto Play → Stop while Thinking; silent UI; server 499; Client cancel (and LLM cancelled when an attempt opened).
  5. Spend vs capacity — spend 429 stops Auto Play; capacity model busy retries; Grafana reject reasons split.
  6. Metrics — Compose --profile metrics; panels move; scrape contract is GET /metrics.
  7. Beacons — fail / spend / busy / cancel increment Client row; stale ignore does not.

Phoenix is host-side (not Compose). Board + Expectimax alone is enough for a fast product pass; full ops needs Ollama + collector + metrics profile. For deeper automated proof without reading code (unit, HTTP contract, disconnect cancel, image smokes, and opt-in pytest --load), see the verification checklist in docs/agents/server.md.