fix(caching): keep-alive accounting writes through the agent's storage handle
Main's persistence interface makes the agent's store a storage handle with no queue_token_counts; the warmer's keep-alive accounting called it on agent._session_db directly and silently lost every refresh's usage. It now goes through turn_usage.queue_usage, which takes the handle's usage repository (and the worker store otherwise) with the session id and surface the keep-alive captured when it was scheduled.
This commit is contained in:
@@ -142,8 +142,8 @@ def _queue_token_counts(agent, fail_msg: str, *fail_extra: Any, counts: Callable
|
||||
try:
|
||||
if not agent._session_db_created:
|
||||
agent._ensure_db_session()
|
||||
from agent.turn_usage import _queue_usage
|
||||
_queue_usage(agent, **counts())
|
||||
from agent.turn_usage import queue_usage
|
||||
queue_usage(agent, **counts())
|
||||
except Exception as exc:
|
||||
logger.debug(fail_msg, agent.session_id, *fail_extra, exc)
|
||||
|
||||
|
||||
@@ -708,10 +708,10 @@ class PromptCacheWarmer:
|
||||
if getattr(agent, "_session_reset_epoch", 0) == b["reset_epoch"]:
|
||||
self._add_to_session_totals(canonical, amount)
|
||||
clock = self._fold_clock(run, canonical, sent_at, message)
|
||||
db = getattr(agent, "_session_db", None)
|
||||
if db is not None and b["session_id"]:
|
||||
db.queue_token_counts(
|
||||
b["session_id"], source=b["source"],
|
||||
if getattr(agent, "_session_db", None) is not None and b["session_id"]:
|
||||
from agent.turn_usage import queue_usage
|
||||
queue_usage(
|
||||
agent, b["session_id"], b["source"],
|
||||
input_tokens=canonical.input_tokens, output_tokens=canonical.output_tokens,
|
||||
cache_read_tokens=canonical.cache_read_tokens,
|
||||
cache_write_tokens=canonical.cache_write_tokens,
|
||||
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, List
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from agent.image_token_cost import calibrate_from_usage
|
||||
from agent.usage_anchor import capture_usage_anchor, set_usage_anchor
|
||||
@@ -51,20 +51,24 @@ def cache_clock_column(event: Any) -> dict[str, str]:
|
||||
return {"prompt_cache_clock": event_to_json(event)}
|
||||
|
||||
|
||||
def _queue_usage(agent: Any, **counts: Any) -> None:
|
||||
"""Enqueue one API call's accounting (``queue_token_counts`` keywords) on the agent's store."""
|
||||
def queue_usage(agent: Any, session_id: Any = None, source: Optional[str] = None, **counts: Any) -> None:
|
||||
"""Enqueue one API call's accounting (``queue_token_counts`` keywords) on the agent's store: through its
|
||||
storage interface handle when it has one, else on its own store (a worker's ``RuntimeSessionStore``).
|
||||
*session_id* / *source* default to the agent's current session and surface (a cache keep-alive passes
|
||||
the ones it captured when it was scheduled)."""
|
||||
from agent.agent_init_session import agent_interface
|
||||
session_id = agent.session_id if session_id is None else session_id
|
||||
source = agent_session_source(agent) if source is None else source
|
||||
store = agent_interface(agent)
|
||||
if store is None:
|
||||
agent._session_db.queue_token_counts(agent.session_id, source=agent_session_source(agent), **counts)
|
||||
agent._session_db.queue_token_counts(session_id, source=source, **counts)
|
||||
return
|
||||
from persistence.conversation.usage import BillingRoute, TokenCounts, UsageDelta
|
||||
tokens = TokenCounts(**{key: counts.pop(key, 0) for key in (
|
||||
"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens")})
|
||||
route = {key: counts.pop(key, None) for key in ("model", "billing_provider", "billing_base_url", "billing_mode")}
|
||||
delta = UsageDelta(tokens=tokens, route=BillingRoute(**route) if route["model"] else None,
|
||||
source=agent_session_source(agent), **counts)
|
||||
store.usage.queue_usage(agent.session_id, delta)
|
||||
delta = UsageDelta(tokens=tokens, route=BillingRoute(**route) if route["model"] else None, source=source, **counts)
|
||||
store.usage.queue_usage(session_id, delta)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -327,7 +331,7 @@ def record_response_usage(
|
||||
# _ensure_db_session() may fail, and UPDATE on a missing row affects 0 rows.
|
||||
if not agent._session_db_created:
|
||||
agent._ensure_db_session()
|
||||
_queue_usage(
|
||||
queue_usage(
|
||||
agent,
|
||||
input_tokens=canonical_usage.input_tokens,
|
||||
output_tokens=canonical_usage.output_tokens,
|
||||
|
||||
@@ -69,7 +69,7 @@ def commit_local_session(holder, *, epoch, receipt, client_request, created_sour
|
||||
# Auxiliary usage inserts created_source='unknown' when it creates the row
|
||||
# (record_auxiliary_usage carries no surface). The creator upsert repairs
|
||||
# 'unknown', but this DO NOTHING insert does not, so the surface is stamped here.
|
||||
# The agent's own accounting passes its surface (turn_usage._agent_session_source)
|
||||
# The agent's own accounting passes its surface (turn_usage.agent_session_source)
|
||||
# and is not that writer. gui's in-process agent is desktop; a managed worker
|
||||
# creates with the policy label gui.
|
||||
created = created_source or None
|
||||
|
||||
@@ -70,7 +70,7 @@ def _worker_usage(holder, conn, session_id, payload, *, auxiliary=False):
|
||||
)
|
||||
source = None
|
||||
if not auxiliary:
|
||||
# ``source`` is the worker platform (turn_usage._agent_session_source). A Desktop
|
||||
# ``source`` is the worker platform (turn_usage.agent_session_source). A Desktop
|
||||
# managed worker passes ``gui``; created_surface maps that to ``desktop``. The row
|
||||
# is usually stamped at admission. A compression child can still be NULL (or an
|
||||
# auxiliary-usage ``unknown``), and this worker never create_session's it, so fill
|
||||
|
||||
@@ -75,7 +75,7 @@ def retirement_candidates_in_text(*texts) -> set:
|
||||
basename (the form every store recorded before prune originals), a prune original by its
|
||||
``cache/pruned/<name>`` reference."""
|
||||
spill = SPILLOVER_SUBDIR + "/"
|
||||
return {ref[len(spill):] if ref.startswith(spill) else ref for ref in archive_refs_in_text(*texts)}
|
||||
return {ref.removeprefix(spill) for ref in archive_refs_in_text(*texts)}
|
||||
|
||||
|
||||
def spillover_names_in_text(*texts) -> set:
|
||||
|
||||
Reference in New Issue
Block a user