Skip to content

fix(agent): report session-cumulative total_turns in completion logs - #728

Merged
edenreich merged 3 commits into
mainfrom
fix/727-total-turns-session
Jul 2, 2026
Merged

edenreich merged 3 commits into
mainfrom
fix/727-total-turns-session

Conversation

@edenreich

@edenreich edenreich commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The total_turns field in the agent completion logs always read 1 in normal back-and-forth chat. It was sourced from the per-request AgentContext.Turns, which is rebuilt from 0 for every user message, so it could only ever reflect the current message's model-round count — never the conversation's running total. On top of that it was emitted three times per completion (two of them microseconds apart). Pure observability bug; nothing keys off the value.

Fix

Log total_turns once, at the turn-complete boundary in processEvents ("agent reached Idle state - turn complete"), sourced from the session-cumulative AgentServiceImpl.sessionTurns — an atomic.Int64 already maintained right alongside Turns, previously read only for reminder cadence. The two redundant completing.go copies are dropped (the "finalizing" trace keeps queue_empty; the duplicate "completed successfully" line is removed).

Observability only — AgentContext.Turns, MaxTurns, and the ctx.Turns >= ctx.MaxTurns limiter are untouched. Also drops a stale inline comment on ApprovalDelivery.

Test

No log-observer harness exists in the repo (tests default to zap.NewNop()) and no behaviour branches on the value, so no new log-assertion test is warranted. agent_reminder_emission_test.go already asserts the session-vs-per-request counter distinction this fix relies on, and TestHandleCompletingState covers the completing-state path.

go build ./..., golangci-lint (0 issues), and full go test ./... all pass.

Closes #727

total_turns was sourced from the per-request AgentContext.Turns, which is
rebuilt from 0 for every user message, so it always read 1 in normal
back-and-forth chat. Repoint it to the session-cumulative sessionTurns
counter, and log the per-request model-round count separately as run_turns.

Observability only: AgentContext.Turns, MaxTurns, and the turn limiter are
unchanged.

Closes #727
@edenreich
edenreich requested a review from a team as a code owner July 2, 2026 15:35
edenreich added 2 commits July 2, 2026 17:46
Follow-up to PR review:
- total_turns was emitted three times per completion (completing-state
  entry and success, plus the idle-reached event loop); log it once at the
  turn-complete boundary, reading sessionTurns directly.
- Drop run_turns: outside a tool-call loop it is always 1, so it only added
  noise.
- The StateContext.SessionTurns accessor added earlier in this PR is now
  unused; remove it.
The "system reminder injected" debug log carried the per-request
agentCtx.Turns as "turn", which is 1 for every normal chat message
(it only climbs inside a tool loop). session_turn already carries the
meaningful cumulative count, so drop the noisy field.

ReminderQuery.Turn (used to gate reminders) and the TUI debug-stream
event are unchanged.
@edenreich

Copy link
Copy Markdown
Contributor Author

@claude Can you review this? any leftovers? missing cleanups? use /go /go-spec-reviewer

@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @edenreich's task in 7m 42s —— View job


Review: PR #728 - total_turns completion-log fix

Verdict: LGTM. Correct, well-scoped, and idiomatic. Pure observability fix - AgentContext.Turns, MaxTurns, and the ctx.Turns >= ctx.MaxTurns limiter are all untouched, so there's no behavioural risk. Ran /go, /go-spec-reviewer (independent reviewer subagent), plus a local build + test.

  • Read changed files & surrounding context
  • Verify sessionTurns vs Turns semantics
  • Check for leftovers / missing cleanups
  • Run /go idiomatic review
  • Run /go-spec-reviewer on the change intent
  • Post review

What I verified

  • Root cause is real. AgentContext.Turns starts at 0 per EventDrivenAgent (rebuilt each user message) and is ++'d in startStreaming, so a single-turn reply never passes 1. sessionTurns (atomic.Int64 on the long-lived AgentServiceImpl) is incremented on the very next line (agent_streaming.go:20-21) and is genuinely session-cumulative - the correct source for a "total".
  • Concurrency-safe. sessionTurns.Add(1) runs in the background streaming goroutine; sessionTurns.Load() runs on the processEvents loop. atomic.Int64 makes each access race-free, and the read is guaranteed current by happens-before: the loop only reaches StateIdle after receiving the stream-completed event the goroutine sends after the Add.
  • Emitted exactly once now. rg total_turns returns a single hit (agent_event_driven.go:255); both completing.go copies are gone and the "finalizing" trace correctly keeps queue_empty. 3 → 1.
  • Naming is accurate. total_turns now genuinely means session-cumulative. Every other turn log site (streaming_llm.go, post_stream.go, checking_queue.go, post_tool_execution.go) uses turn/turns/current_turn for the per-request value - none mislabel a per-request turn as "total".
  • Build + tests green. go build ./internal/agent/... clean; go test ./internal/agent/... passes.

On "any leftovers?" - the one that looks like a leftover isn't

injectDueReminders drops "turn" from the logger.Debug line, but the adjacent streamevent.EmitDebugMessage a few lines below (agent_utils.go:879-884) still emits "turn". That's intentional and correct to leave: the stream-event schema deliberately carries both per-request turn and cumulative session_turn as distinct fields, and TestInjectDueReminders_AppendsHiddenMessageAndEmits (agent_reminder_emission_test.go:69-70) asserts both. Trimming the human-facing log while keeping the machine-readable event schema intact is the right split. Good call not touching it.

Minor / optional (non-blocking)

  1. ApprovalDelivery comment removal (agent_event_driven.go:138). The deleted comment was the only inline explanation of why brokerAttached is hardcoded false. The reason is structural: EventDrivenAgent is only ever built from the in-process RunWithStream (chat) path, never headless, so no IPC broker exists here - contrast the headless path in cmd/agent.go:918, which passes s.requireApproval. The invariant is documented at the type level, so this is fine, but a one-liner stating the structural "why" would save the next reader a hop. Fix this →
  2. sessionTurns doc (agent.go:41-47) is written entirely from the reminder-cadence angle but now has a second consumer (the total_turns log). The description of the value is still accurate; a half-sentence noting the completion log reads it too would keep a future reminders refactor from overlooking the dependency.

Neither blocks merge. Nice, tight cleanup.
· fix/727-total-turns-session

@edenreich
edenreich merged commit 0d8fb08 into main Jul 2, 2026
1 check passed
@edenreich
edenreich deleted the fix/727-total-turns-session branch July 2, 2026 17:05
inference-gateway-releaser Bot added a commit that referenced this pull request Jul 3, 2026
## [0.128.0](v0.127.0...v0.128.0) (2026-07-03)

### 🚀 Features

* **chat:** make status indicators selectable with /tools and /a2a views ([#732](#732)) ([6882de0](6882de0)), closes [#717](#717) [#717](#717)

### 🐛 Bug Fixes

* **agent:** drop redundant Idle transition that errored on every run ([#726](#726)) ([469ec64](469ec64)), closes [#722](#722) [#725](#725)
* **agent:** report session-cumulative total_turns in completion logs ([#728](#728)) ([0d8fb08](0d8fb08)), closes [#727](#727)
* **a2a:** route active A2A reads and HasPending through the job supervisor ([#693](#693)) ([#721](#721)) ([dcd0670](dcd0670)), closes [#718](#718) [#719](#719) [#720](#720)
* **keybindings:** stop "unknown keybinding action" log flood ([#724](#724)) ([c828426](c828426)), closes [#714](#714) [#722](#722)
* **a2a:** unify background-job liveness, clear, and cancel on the supervisor contract ([#730](#730)) ([eb37fd0](eb37fd0)), closes [#693](#693) [#720](#720) [#718](#718) [#719](#719)
* **logging:** use structured key/value form at misused call sites ([#729](#729)) ([cd96028](cd96028)), closes [#722](#722) [#724](#724) [#724](#724) [#723](#723)
* **tools:** wait for pipe readers before reaping detached bash shells ([#716](#716)) ([e1d0d84](e1d0d84)), closes [#696](#696)

### ⚡ Performance Improvements

* **tui:** cache per-entry rendering and keep the Update loop responsive ([#731](#731)) ([8c9db0d](8c9db0d))

### 📚 Documentation

* **a2a:** add SKILL.md documentation for Agent2Agent protocol ([defcd57](defcd57))

### 🔧 Build System

* **deps:** bump golang.org/x/net from 0.47.0 to 0.55.0 in /examples/mcp/mcp-server ([#715](#715)) ([990803b](990803b))

### 🧹 Maintenance

* **flox:** bump dev deps ([d0c8f6b](d0c8f6b))
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.128.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Jul 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Agent: "total_turns" log always reads 1 in chat (per-request counter, not session total)

1 participant