Skip to content

feat(perf): turn log records how busy the model server was - #5285

Merged
kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/perf-turn-trace
Oct 19, 2026
Merged

kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/perf-turn-trace

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

The turn log said how long each model call took but not how much of that the model server spent computing, so "is GAIA keeping the backend busy?" had no answer. With GAIA_TURN_LOG set, every local model call now records the server's own prefill, decode and cache-reuse figures, plus the time GAIA spent before the request reached the server. Each turn reports its server compute, its non-model time, what filled the gaps between model calls, and a fingerprint of the system prompt, so a cache-breaking prompt change is named rather than guessed.

First readings on Gemma-4-E4B (Strix Halo, idle GPU): a warm "hello" is 3.4–3.9 s, of which 0.45 s is non-model time. Between model calls GAIA's own work costs under 30 ms; the rest of the gap is tool I/O. The seconds go to the server, and much of that to re-reading prompts it should have kept cached. Those fixes follow in separate PRs.

  • util/perf_turns.py drives /v1/gaia/query and samples the llama.cpp server behind Lemonade (/slots busy time and idle gaps, /metrics, per-process GPU use on Windows). It waits for an idle GPU before each session and flags runs where the model reloaded or another client sent requests.
  • The sidecar serves the last records at GET /v1/gaia/debug/turns while recording is on. The route is off the published contract, and the capability matrix now skips routes hidden from the schema.
  • The TUI gains --pprof <loopback host:port> for startup and render profiles.

Test plan

  • python -m pytest tests/unit/test_turn_metrics_spans.py tests/unit/test_turn_metrics.py tests/unit/test_turn_metrics_wire.py hub/agents/gaia/python/tests/test_server_query.py hub/agents/gaia/python/tests/test_capability_matrix.py -q
  • cd tui && go test ./internal/cli/ -run Pprof
  • With GAIA_TURN_LOG=turns.jsonl, start the sidecar and send one query. Its record has llm_calls[].server.compute_s, totals.non_model_s, gaps and prompt.system_sha, and GET /v1/gaia/debug/turns returns it.
  • Without GAIA_TURN_LOG, /v1/gaia/debug/turns answers 404 and no record file is written.
🔍 Captured output (Gemma-4-E4B, sidecar from this branch, query "hello")

GET /v1/gaia/debug/turns?limit=1 with GAIA_TURN_LOG set, trimmed to the new fields:

{
  "schema": "gaia.turn/1", "total_s": 4.112, "steps": 1,
  "totals": {
    "llm_s": 3.911, "overhead_s": 0.201,
    "server_compute_s": 3.608, "non_model_s": 0.504,
    "input_tokens_cached_server": 19335,
    "client_waits_s": {"lease_wait_s": 0.0, "lock_wait_s": 0.0, "ensure_loaded_s": 0.0171}
  },
  "gaps": [],
  "llm_calls": [{
    "step": 1, "wall_s": 3.9109,
    "server": {"prompt_n": 45, "prompt_ms": 1074.886, "cache_n": 19335,
               "predicted_n": 85, "predicted_ms": 2532.745, "compute_s": 3.6076},
    "client": {"lease_wait_s": 0.0, "lock_wait_s": 0.0, "ensure_loaded_s": 0.0171}
  }],
  "prompt": {"system_sha": "6f7d0ea7ac22", "system_tokens": 5843, "tool_schema_tokens": 14499,
             "tools_sent": 95, "fragments": {"get_memory_system_prompt": 1722, "get_skill_catalog_system_prompt": 5786, "...": "..."}}
}

Without GAIA_TURN_LOG: the route answers HTTP 404 {"detail":"Turn recording is off. Set GAIA_TURN_LOG=<path> before starting the agent to record turns."} and a query writes no record file.

TUI:

$ gaia-tui --pprof 127.0.0.1:0 version
pprof → http://127.0.0.1:49696/debug/pprof/
$ gaia-tui --pprof 0.0.0.0:6060 version
Error: --pprof "0.0.0.0:6060": only a loopback address is allowed (127.0.0.1, ::1 or localhost)

The turn log said how long each model call took, but not how much of that the
server spent computing, so "is GAIA keeping the backend busy?" had no answer.
With GAIA_TURN_LOG set, each local model call now carries llama.cpp's own
prefill/decode time and cache reuse (from the stream's timings) and the time
GAIA spent before the request reached the server: model-slot lease, request
lock, status probe, stats fetch. Each turn reports server compute, non-model
time, named spans (memory recall, post-init upkeep, eviction, tool logging)
and what filled the gaps between model calls; work after the answer is a
second gaia.turn_post/1 line.

- gaia.utils.perf_trace: thread-local hooks the LLM client reports into,
  one attribute read when recording is off.
- The flagship sidecar serves the last records at GET /v1/gaia/debug/turns
  while recording is on (off the published contract; hidden routes no longer
  count in the capability matrix).
- util/perf_turns.py drives /v1/gaia/query and samples the llama.cpp server
  (/slots, /metrics, per-process GPU utilization on Windows).
- The TUI gains --pprof <loopback host:port>.
- Memory's tool-history logging failures log a warning instead of debug.
… fragment

A changed system prompt between two turns of one chat makes Gemma-4 re-read the
whole prompt; the record now carries its hash and each mixin fragment's size,
so the fragment that changed is named instead of guessed.
@github-actions github-actions Bot added documentation Documentation changes chat Chat SDK changes llm LLM backend changes tests Test changes performance Performance-critical changes agents tui Go terminal UI (gaia-tui) sidecar Agent sidecar contract / harness labels Oct 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

With GAIA_TURN_LOG set, the turn log now splits each turn into time the model server spent computing and everything else (lock and lease waits, memory recall, tool gaps). It also adds a dev-only route that returns recent records, a loopback-only --pprof flag for the TUI, and a script that samples the llama.cpp server. With recording off, every new hook does nothing, the debug route answers 404, and the route sits behind the existing caller token. I found nothing blocking. The two suggestions below are small gaps in what gets measured or tested.

  • The new timings for the lock, the lease and the model-status check are only tested by feeding numbers into the recorder by hand. No test runs the real client path, so if those timings stopped landing on the model call, no test would fail.
  • The per-fragment prompt sizes can list a fragment the agent filtered out of its final prompt, so the sizes can add up to more than the prompt that was actually sent.

Real-world evidence

N/A: no evidence bundle was produced for this run. The changed surfaces are a dev-only HTTP route, a dev-only TUI flag and a measurement script, all opt-in. The PR description reports Strix Halo timings but doesn't paste a captured /v1/gaia/debug/turns response, so this verdict rests on static review and the unit tests in the diff.

🔍 Technical details

Issues found

🟢 The client-side wait wiring has no test (src/gaia/llm/lemonade_client.py:5958-5965, :6008-6012)
tests/unit/test_turn_metrics_spans.py calls perf_trace.note_wait directly. Nothing exercises _model_slot_lease / _ensure_model_loaded under an active recorder. Ordering is what makes these numbers real: _recorder_begin runs before the client call (sdk.py:615), and the lease is taken on the consuming thread (lemonade_client.py:4157), so today they do land on the open call. A small test that activates a recorder, opens a call and enters client._model_slot_lease(model) with a stub lock/lease, then asserts that lease_wait_s/lock_wait_s appear under client, would pin it. A nested lease (4157 → 6007) also books a second lease_wait_s of about 0 s. That's harmless, but worth knowing when you read the sums.

🟢 prompt.fragments can include filtered-out fragments (src/gaia/agents/base/agent.py:2703-2706)
_mixin_prompt_origins is built before a subclass override filters the list. The docstring example drops the SD fragment, and the lookup is by text, applied after the filter. Sizing straight from the dict therefore counts fragments that never reached the prompt. Restrict it to fragments present in the composed prompt:

                prompt_fragments={
                    origin: len(text)
                    for text, origin in (self._mixin_prompt_origins or {}).items()
                    if text in system_prompt
                },

(Use whatever local holds the composed prompt here, since TurnRecorder already receives it as system_prompt.)

🟢 /debug/turns returns every session's records
RECENT_TURNS is process-global, so any holder of the caller token sees other sessions' queries. That's fine for a single-user sidecar with recording turned on deliberately. A one-line note in dev.mdx would stop someone from enabling it on a shared box without knowing.

Strengths

  • The code fails loudly on bad data. server_compute_s / non_model_s are left out unless every call reported timings, and a test pins that.
  • Recorders are scoped per thread. Background extraction and tool threads can't book their requests as the turn's, and that is tested too. The nested-turn hand-back also restores the outer recorder.
  • The PR fixes an existing violation while it's in the area: the tool_history failure in memory.py moved from debug to warning with the tool name.
  • --pprof refuses non-loopback addresses and logs to stderr, so it can't corrupt the TUI's screen.

kovtcharov and others added 3 commits October 18, 2026 01:40
…path

- The prompt fingerprint uses SHA-256; Bandit blocks SHA-1 (B324).
- A test now drives LemonadeClient._model_slot_lease and _ensure_model_loaded
  under an active recorder, with another request holding the lock, so the
  lock, lease and status-probe waits are proven to land on the open call
  rather than only when fed in by hand.
- prompt.fragments counts only fragments present in the prompt that was sent.
- dev.mdx says /debug/turns returns every session's records.
- test_wait_tools patched the global time.sleep, so on Windows the rotating log
  handler's lock-retry sleep was counted as a nap and the "already stopped"
  test failed intermittently; the fixture now patches only the tool's clock.
# Conflicts:
#	src/gaia/agents/base/memory.py
# Conflicts:
#	hub/agents/gaia/python/tests/test_server_query.py
#	src/gaia/llm/lemonade_client.py
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

With GAIA_TURN_LOG set, the turn log now records the model server's own prefill, decode and cache-reuse time, plus the waits GAIA adds before a request reaches it. That answers "is GAIA keeping the backend busy?" with numbers. When the variable is unset, everything new does nothing: no recorder is created, the hooks return immediately, and the debug route answers 404. I found no correctness bugs. The recorder is attached per thread and released in the turn's finally, so it can't leak into the next turn, and background or tool threads never get booked as the turn's own calls.

Before merge:

  • Paste one real record. The description gives measured timings but no sample of the new output. Paste one GET /v1/gaia/debug/turns response, or a turns.jsonl line showing server, non_model_s and gaps, plus the --pprof startup line, and tick the test plan.
  • Two small text fixes. One docs sentence is missing a word, and the perf script's docstring promises a foreign flag it never writes.

Real-world evidence

N/A: no evidence-bundle.md was produced for this run. My verdict on the new debug route, the turn-log fields and the TUI --pprof flag rests on reading the code and the unit tests alone. Nothing was run against a live sidecar here.

🔍 Technical details

🟡 No pasted output for the new route or flag (PR description)
The PR adds an HTTP route (/v1/gaia/debug/turns) and a CLI flag (gaia-tui --pprof). The "first readings" paragraph shows a run happened, but there is no request/response or record excerpt, and every test-plan box is unchecked. Paste the output of test-plan item 3 (one record plus the 404 when recording is off) and the pprof → http://… stderr line. This needs no code change.

🟢 Missing word (docs/reference/dev.mdx, "Is GAIA keeping the model server busy?")

caller token, so keep turn recording on only on a machine you use alone.

🟢 The docstring promises a foreign flag the script never sets (util/perf_turns.py:17-19)
The module docstring says a turn whose request count moved more than its own calls is "flagged foreign". The record only stores the raw lemonade_requests delta. Either compute the flag next to backend_reloaded:

"foreign": bool(agent) and req_delta > agent["llm_calls"],

or reword the docstring to say the delta is recorded for the reader to compare.

Checked and fine

  • _flush_post_turn_record runs in Agent.process_query's finally. A turn that raises still restores the outer recorder and writes its gaia.turn_post/1 line, and parked _pre_turn_spans are cleared on both the MemoryMixin entry and the exit.
  • http_open_s is booked on the stream worker thread through the recorder captured on the turn's thread, so per-thread routing still holds.
  • /debug/turns inherits the router-level require_caller_token. The capability-matrix skip for include_in_schema=False has its own test.
  • The memory.py tool-log failure moves from debug to warning, which matches the fail-loudly rule.

Strengths

  • server_compute_s and non_model_s are left out unless every call reported server timings. A partial sum would overstate GAIA's share, and the code and a test both say so.
  • The client-wait test drives the real _model_slot_lease and _ensure_model_loaded path with an actually held lock, instead of feeding numbers to the recorder by hand.
  • The --pprof flag refuses any non-loopback address, which keeps heap profiles off the network, and that refusal is tested.

# Conflicts:
#	src/gaia/llm/lemonade_client.py
- Each perf_turns record now sets `foreign` when Lemonade served more
  requests during the turn than the agent's own model calls, so a run
  that shared the server with another client is marked. It is null when
  the sidecar returned no turn record to compare with.
- dev.mdx: restore the missing word in the shared-machine warning.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 71e3287 Oct 19, 2026
72 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/perf-turn-trace branch October 19, 2026 20:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents chat Chat SDK changes documentation Documentation changes llm LLM backend changes performance Performance-critical changes sidecar Agent sidecar contract / harness tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants