Raven icon indicating copy to clipboard operation
Raven copied to clipboard

perf(rpc): stream usage telemetry once per settings report

Open loading2332 opened this issue 1 month ago • 0 comments

Problem

settings.usage reads and parses each daily telemetry file twice: once for model calls, then again for tool calls. Both passes materialize the complete file with read_text().splitlines(). The report supports up to 90 days, so reopening the Usage page repeats work proportional to the selected telemetry volume on the RPC event loop.

The second pass also catches errors around the whole file rather than around each record. A malformed JSON line, null, or an array stops the tool tally for that day, even though later valid model records still count in the first pass.

Evidence

Reproduced against current upstream main on macOS with Python 3.12, calling the real settings_usage handler with an isolated telemetry directory and no providers or running gateway:

  • One synthetic daily file with 100,000 model rows and 100,000 tool rows: 43,200,000 bytes.
  • Each report opens that file twice.
  • Median of three warm runs: 0.685 seconds.
  • Peak Python allocations during a separate tracemalloc run: 141.96 MiB. This is not process RSS or a production measurement.
  • Two valid tool rows separated by not-json, null, or []: expected tool total 2, observed 1 in each case.

The relevant code is settings_usage in raven/rpc/methods/console.py. raven/token_wise/usage_tracker.py already has a tolerant read_usage_rows reader used by session and delegated-usage reports, but it currently materializes a list as well.

Minimal reproduction of the undercount

Run from a checkout with its Python dependencies installed:

uv run python - <<'PY'
import asyncio
import json
import tempfile
from datetime import date
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch

from raven.rpc.methods.console import settings_usage

with tempfile.TemporaryDirectory() as directory:
    home = Path(directory)
    telemetry = home / "telemetry"
    telemetry.mkdir()
    row = json.dumps({
        "_type": "tool_call", "schema_version": 2, "name": "exec",
        "session_key": "tui:example", "root_session_key": "tui:example",
    })
    (telemetry / f"usage-{date.today().isoformat()}.jsonl").write_text(
        row + "\nnot-json\n" + row + "\n", encoding="utf-8"
    )
    with patch("raven.config.loader.raven_home", return_value=home), patch(
        "raven.config.loader.load_config",
        return_value=SimpleNamespace(workspace_path=home / "workspace"),
    ):
        report = asyncio.run(settings_usage({"days": 1}))
    print(report["tools"])  # total is 1; both valid records should count.
PY

Proposed change

Stream parsed telemetry rows through the existing reader and aggregate model and tool calls in one pass. Keep the response schema, date range, root-session attribution, unknown-cost accounting, and session-title behavior. Skip malformed/non-object records independently for both tallies. No cache or new on-disk index is needed.

Verify identical full responses for valid data, one file scan per day, incremental reading, malformed-record recovery, missing files, and the existing session/delegation consumers. Measure the same synthetic workload before and after; transcript-title scanning and asynchronous offloading are outside this change.

loading2332 avatar Oct 20 '26 07:10 loading2332