Skip to content

AdvancedSQLiteSession.store_run_usage() records a phantom usage row for turn 0 when the current branch has no turn #4821

Closed

Description

@rioyu123

Summary

On an empty session, or on a branch whose turns were all popped, store_run_usage() inserts a turn_usage row for user_turn_number = 0. get_session_usage() then reports total_turns: 1 while get_items() is []. test_empty_session_operations and the method docstrings say usage is never recorded against a turn that has no rows.

Affected code (main @ 89c02c8), src/agents/extensions/memory/advanced_sqlite_session.py

  • store_run_usage (:618-655) calls _capture_current_turn (:657-686), which on a branch without turns returns user_turn_number = 0 (COALESCE(MAX(...), 0)) and turn_anchor = None (MIN(id) of no rows).
  • _update_turn_usage_internal (:1883-1970) only runs the removed-turn guard under if turn_anchor is not None:, so a None anchor skips the guard and the INSERT OR REPLACE lands.

Reproduction

from unittest.mock import MagicMock
from agents import RunResult, Usage
from agents.extensions.memory import AdvancedSQLiteSession

s = AdvancedSQLiteSession(session_id="x", create_tables=True)
r = MagicMock(spec=RunResult)
r.context_wrapper = MagicMock()
r.context_wrapper.usage = Usage(requests=1, input_tokens=10, output_tokens=5, total_tokens=15)
await s.store_run_usage(r)
print(await s.get_items())          # []
print(await s.get_session_usage())  # {'requests': 1, ..., 'total_turns': 1}   expected: None
print(await s.get_turn_usage())     # [{'user_turn_number': 0, ...}]           expected: []

The same happens after add_items followed by pop_item until the branch is empty. A later real turn plus store_run_usage(requests=2) then reports requests: 3, total_turns: 2 instead of requests: 2, total_turns: 1.

Root cause

A None anchor means "no turn on this branch", but _update_turn_usage_internal treats it as "no guard requested" and writes unconditionally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions