Skip to content

Commit dd2c7d4

Browse files
fix(analytics): deduplicate streaming message.id turn tool counts and wire serial-turn coaching into coach()
1 parent 4d86f79 commit dd2c7d4

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

‎runtime/analytics.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,8 @@ def parse_claude_transcript(path: Path, *, records=None, resume: dict | None = N
224224
run_idx = state.setdefault("run_idx", {})
225225
usage_by_id = state.setdefault("usage_by_id", {})
226226
usage_no_id = state.setdefault("usage_no_id", [])
227+
turn_tools_by_id = state.setdefault("turn_tools_by_id", {})
228+
turn_tools_no_id = state.setdefault("turn_tools_no_id", [])
227229
for rec in _iter_jsonl(path) if records is None else records:
228230
ts = _ts(rec.get("timestamp"))
229231
if ts:
@@ -300,7 +302,11 @@ def parse_claude_transcript(path: Path, *, records=None, resume: dict | None = N
300302
run_idx[tool_id] = len(st.shell_runs)
301303
st.shell_runs.append([ts, _private_key(cmd, resume), False])
302304
if turn_tools > 0:
303-
st.turn_tool_counts.append(turn_tools)
305+
t_msg_id = _private_key(str(msg.get("id") or ""), resume)
306+
if t_msg_id:
307+
turn_tools_by_id[t_msg_id] = turn_tools_by_id.get(t_msg_id, 0) + turn_tools
308+
else:
309+
turn_tools_no_id.append(turn_tools)
304310
elif rec.get("type") == "user":
305311
if isinstance(content, str):
306312
if not content.startswith("<"):
@@ -329,6 +335,7 @@ def parse_claude_transcript(path: Path, *, records=None, resume: dict | None = N
329335
tool = tool_names.get(tool_id, "tool")
330336
st.errors.append(f"{tool}: {_short(text, 120)}")
331337
st.request_usage = [*usage_no_id, *usage_by_id.values()]
338+
st.turn_tool_counts = [*turn_tools_no_id, *(c for c in turn_tools_by_id.values() if c > 0)]
332339
st.turns = st.input_tokens = st.cache_read = st.cache_write = st.cache_write_1h = st.output_tokens = st.peak_context = 0
333340
for _, _, inp, cr, cw, cw1h, out in st.request_usage:
334341
st.turns += 1
@@ -912,6 +919,9 @@ def coach(host: str, days: float = 7.0, env: dict[str, str] | None = None) -> st
912919
big = sum(s.big_results for s in sessions)
913920
if big:
914921
tips.append(f"{big} tool result(s) exceeded {_BIG_RESULT_CHARS // 1000}K chars. Prefer `execute_filtered` with an intent, or pipe through head/grep.")
922+
serial = sum(s.serial_single_tool_turns for s in sessions)
923+
if serial >= 3:
924+
tips.append(f"{serial} consecutive single-tool turn(s) detected. Batch independent searches, reads, and edits in one turn to cut round-trips (N).")
915925
peak = [s for s in sessions if s.host == "claude" and s.peak_context > 0.85 * context_window(s)]
916926
if peak:
917927
tips.append(f"{len(peak)} session(s) ran near the context limit. Start fresh sessions per task, or delegate broad searches to subagents.")

‎tests/test_nonhuman_improvements.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,36 @@ def test_turn_efficiency_and_billed_cost_breakdown(tmp_path: Path) -> None:
106106
assert bd["token_mix"]["thinking"] == 100
107107

108108

109+
def test_streaming_msg_id_merges_turn_tool_counts(tmp_path: Path) -> None:
110+
transcript = tmp_path / "stream.jsonl"
111+
# Two streaming chunks for the same message.id with 1 tool_use each => 1 batched turn of 2 calls, 0 serial turns.
112+
records = [
113+
{
114+
"type": "assistant",
115+
"timestamp": "2026-01-01T00:00:01Z",
116+
"message": {
117+
"id": "m-stream",
118+
"usage": {"input_tokens": 10, "output_tokens": 5},
119+
"content": [{"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": "a.py"}}],
120+
},
121+
},
122+
{
123+
"type": "assistant",
124+
"timestamp": "2026-01-01T00:00:01Z",
125+
"message": {
126+
"id": "m-stream",
127+
"usage": {"input_tokens": 10, "output_tokens": 10},
128+
"content": [{"type": "tool_use", "id": "t2", "name": "Read", "input": {"file_path": "b.py"}}],
129+
},
130+
},
131+
]
132+
transcript.write_text("\n".join(json.dumps(r) for r in records) + "\n", encoding="utf-8")
133+
st = analytics.parse_claude_transcript(transcript)
134+
assert st.turns == 1
135+
assert st.turn_tool_counts == [2]
136+
assert st.serial_single_tool_turns == 0
137+
138+
109139
def test_bootstrap_holdout_verify_gates() -> None:
110140
good = analytics.bootstrap_holdout_verify(
111141
[0.75, 0.80, 0.78, 0.82, 0.79],

0 commit comments

Comments
 (0)