Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(costs): the Spend section stops freezing the whole app

rubenluetke10-beepa8ee99eae236
diff --git a/jarvis/ui/web/costs_routes.py b/jarvis/ui/web/costs_routes.py
index 996fe34069..4f490edcf4 100644
--- a/jarvis/ui/web/costs_routes.py
+++ b/jarvis/ui/web/costs_routes.py
@@ -44,6 +44,11 @@ _FALLBACK_EUR_PER_USD = 0.92
_DAY_MS = 24 * 60 * 60 * 1000
+#: Grain the open end of a range snaps to, so the panels of one page load share
+#: an entry-cache key. Matches ``_EntryCache._TTL_S`` — a finer grain would
+#: expire the key before the cache does and defeat the point.
+_RANGE_GRAIN_MS = 15_000
+
# ---------------------------------------------------------------------------
# Response models
@@ -245,10 +250,21 @@ class _EntryCache:
def __init__(self) -> None:
self._lock = threading.Lock()
+ # Held for the read itself, so the four panels of one page load share
+ # a single pass over the stores instead of racing each other through
+ # it. The handlers run in the threadpool, so without this a page open
+ # is four concurrent reads of the same rows off the same disk.
+ self._compute_lock = threading.Lock()
self._key: tuple[Any, ...] | None = None
self._entries: list[CostEntry] = []
self._at = 0.0
+ def _fresh(self, key: tuple[Any, ...]) -> list[CostEntry] | None:
+ with self._lock:
+ if self._key == key and (time.monotonic() - self._at) < self._TTL_S:
+ return self._entries
+ return None
+
def get(self, sources: CostSources, since_ms: int, until_ms: int) -> list[CostEntry]:
key = (
str(sources.sessions_db),
@@ -256,23 +272,30 @@ class _EntryCache:
since_ms,
until_ms,
)
- now = time.monotonic()
- with self._lock:
- if self._key == key and (now - self._at) < self._TTL_S:
- return self._entries
- # The coding-CLI source pre-aggregates, so it has to know the grain
- # the report will draw at before it reads a row.
+ hit = self._fresh(key)
+ if hit is not None:
+ return hit
+ with self._compute_lock:
+ # Someone may have filled it while we queued for the read.
+ hit = self._fresh(key)
+ if hit is not None:
+ return hit
+ # The coding-CLI source pre-aggregates, so it has to know the grain
+ # the report will draw at before it reads a row.
+ entries = collect_entries(
+ sources,
+ since_ms=since_ms,
+ until_ms=until_ms,
+ bucket_ms=bucket_ms_for(since_ms, until_ms),
+ )
+ with self._lock:
+ self._key = key
+ self._entries = entries
+ self._at = time.monotonic()
+ # Armed only after the read: the scanner walks the same gigabytes this
+ # request just read, and starting it first makes the page wait behind
+ # its own background job.
_refresher.nudge(sources.cli_index_dir)
- entries = collect_entries(
- sources,
- since_ms=since_ms,
- until_ms=until_ms,
- bucket_ms=bucket_ms_for(since_ms, until_ms),
- )
- with self._lock:
- self._key = key
- self._entries = entries
- self._at = now
return entries
@@ -305,7 +328,12 @@ class _IndexRefresher:
"""
_MIN_GAP_S = 60.0
- _CATCH_UP_GAP_S = 3.0
+ # A three-second gap after a twenty-second read is an 87 % duty cycle: on a
+ # machine whose transcripts outgrow one catch-up pass the scanner never
+ # leaves this mode, and it holds the disk the whole app reads from. Equal
+ # gap and budget halve that while still reading far faster than transcripts
+ # are written; the badge keeps saying how much is left.
+ _CATCH_UP_GAP_S = 20.0
_BUDGET_S = 20.0
def __init__(self) -> None:
@@ -355,9 +383,13 @@ _refresher = _IndexRefresher()
class _IndexStatusCache:
"""``index_state`` walks the transcript folders (a few thousand ``stat``
calls); the summary is polled every 30 s and re-requested on every filter
- click, so the walk is shared for a short while rather than repeated."""
+ click, so the walk is shared for a short while rather than repeated.
+
+ The TTL outlives that poll on purpose. At ten seconds against a thirty-second
+ poll it expired before every request, so each one paid for the full walk —
+ the badge costing more than the numbers it sits beside."""
- _TTL_S = 10.0
+ _TTL_S = 45.0
def __init__(self) -> None:
self._lock = threading.Lock()
@@ -447,8 +479,14 @@ def _range(days: int, since_ms: int | None, until_ms: int | None) -> tuple[int,
``days=0`` means "everything ever recorded" — the section is also a
lifetime ledger, not only a rolling window.
+
+ The open end is snapped to the entry cache's own grain. At millisecond
+ resolution every request carried a different "now" into the cache key, so
+ the cache could never hit and the four panels of one page each re-read the
+ stores. Only the end moves; the window keeps its exact width, so the chart
+ draws at the same grain either way.
"""
- now = int(time.time() * 1000)
+ now = int(time.time() * 1000) // _RANGE_GRAIN_MS * _RANGE_GRAIN_MS
end = until_ms if until_ms is not None else now
if since_ms is not None:
return since_ms, end
@@ -479,7 +517,7 @@ def _split(values: list[str] | None) -> set[str]:
@router.get("/summary", response_model=CostSummary, summary="Spend and token totals")
-async def get_summary(
+def get_summary(
request: Request,
days: Annotated[int, Query(ge=0, le=3650)] = 30,
since_ms: Annotated[int | None, Query(ge=0)] = None,
@@ -526,7 +564,7 @@ _DAY_TOP_PROVIDERS = 8
@router.get("/daily", response_model=DailyLedger, summary="One row per calendar day")
-async def get_daily(
+def get_daily(
request: Request,
days: Annotated[int, Query(ge=0, le=3650)] = 30,
since_ms: Annotated[int | None, Query(ge=0)] = None,
@@ -591,7 +629,7 @@ async def get_daily(
@router.get("/entries", response_model=EntriesPage, summary="Individual spend line items")
-async def get_entries(
+def get_entries(
request: Request,
days: Annotated[int, Query(ge=0, le=3650)] = 30,
since_ms: Annotated[int | None, Query(ge=0)] = None,
@@ -634,7 +672,7 @@ async def get_entries(
@router.get("/pricing", response_model=PricingResponse, summary="Rate card per model")
-async def get_pricing(
+def get_pricing(
request: Request,
days: Annotated[int, Query(ge=0, le=3650)] = 30,
) -> PricingResponse:
diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
index a5c2e37a25..5262e9c3e9 100644
--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
@@ -214,6 +214,7 @@ export interface CostPricing {
// Query state shared by the summary and the line items
// ---------------------------------------------------------------------------
+
export interface CostFilters {
/** Rolling window in days; `0` means everything ever recorded. */
days: number;
@@ -273,8 +274,14 @@ function toParams(f: CostFilters): URLSearchParams {
return params;
}
-async function getJson<T>(url: string): Promise<T> {
- const res = await fetch(url);
+/**
+ * React Query hands every queryFn an `AbortSignal`; forwarding it is what makes
+ * leaving the section actually stop the work. These reads are the most
+ * expensive in the app, so an abandoned one left running keeps a server thread
+ * busy on an answer nobody will look at.
+ */
+async function getJson<T>(url: string, signal?: AbortSignal): Promise<T> {
+ const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
return (await res.json()) as T;
}
@@ -287,11 +294,17 @@ export function useCostSummary(filters: CostFilters) {
const params = toParams(filters);
return useQuery({
queryKey: ["costs", "summary", params.toString()],
- queryFn: () => getJson<CostSummary>(`/api/costs/summary?${params.toString()}`),
- // Spend only moves when a turn finishes; a slow poll keeps an open
- // section current without re-reading three SQLite files every second.
- refetchInterval: 30_000,
+ queryFn: ({ signal }) => getJson<CostSummary>(`/api/costs/summary?${params.toString()}`, signal),
+ // Spend only moves when a turn finishes, and this is the most expensive
+ // read in the app. At thirty seconds a slow answer was still in flight
+ // when the next poll fired, so the section spent its whole life queueing
+ // behind itself.
+ refetchInterval: 120_000,
staleTime: 10_000,
+ // Without this a filter click empties every table on the page while the
+ // new numbers are fetched. Both sibling queries already keep the old
+ // rows on screen; the summary is what the eye is actually on.
+ placeholderData: (prev) => prev,
});
}
@@ -306,8 +319,12 @@ export function useCostDaily(filters: CostFilters) {
const params = toParams(filters);
return useQuery({
queryKey: ["costs", "daily", params.toString()],
- queryFn: () => getJson<CostDailyLedger>(`/api/costs/daily?${params.toString()}`),
- refetchInterval: 30_000,
+ queryFn: ({ signal }) =>
+ getJson<CostDailyLedger>(`/api/costs/daily?${params.toString()}`, signal),
+ // No poll of its own: this is the same underlying data as the summary,
+ // re-read whenever the filters change. Two independent polls over the
+ // two heaviest endpoints meant the section refetched everything twice
+ // per cycle for numbers that move only when a turn ends.
staleTime: 10_000,
placeholderData: (prev) => prev,
});
@@ -325,7 +342,8 @@ export function useCostEntries(
params.set("offset", String(offset));
return useQuery({
queryKey: ["costs", "entries", params.toString()],
- queryFn: () => getJson<CostEntriesPage>(`/api/costs/entries?${params.toString()}`),
+ queryFn: ({ signal }) =>
+ getJson<CostEntriesPage>(`/api/costs/entries?${params.toString()}`, signal),
staleTime: 10_000,
placeholderData: (prev) => prev,
});
@@ -334,7 +352,7 @@ export function useCostEntries(
export function useCostPricing(days: number, enabled: boolean) {
return useQuery({
queryKey: ["costs", "pricing", days],
- queryFn: () => getJson<CostPricing>(`/api/costs/pricing?days=${days}`),
+ queryFn: ({ signal }) => getJson<CostPricing>(`/api/costs/pricing?days=${days}`, signal),
enabled,
staleTime: 5 * 60_000,
});
diff --git a/tests/unit/ui/web/test_costs_routes.py b/tests/unit/ui/web/test_costs_routes.py
index 2b3ee8b72b..bb124d0448 100644
--- a/tests/unit/ui/web/test_costs_routes.py
+++ b/tests/unit/ui/web/test_costs_routes.py
@@ -251,3 +251,57 @@ def test_summary_says_whether_the_cli_index_is_still_counting(client: TestClient
assert isinstance(index["complete"], bool)
assert index["files_indexed"] + index["files_pending"] == index["files_known"]
assert index["complete"] == (index["files_pending"] == 0)
+
+
+# ---------------------------------------------------------------------------
+# The section is a read model over live databases, so how OFTEN it re-reads
+# them is part of its contract: the four panels of one page load, and the poll
+# that follows, must cost one pass over the stores rather than one each.
+# ---------------------------------------------------------------------------
+
+
+def test_one_page_load_reads_the_stores_once(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """All four panels share a cache entry.
+
+ The open end of a range used to carry a millisecond timestamp into the
+ cache key, so two requests a millisecond apart never agreed on one and the
+ cache could not hit. The section then re-read every store four times per
+ page and again on every poll — the section's whole cost, paid four times.
+ """
+ from jarvis.ui.web import costs_routes
+
+ reads = 0
+ real = costs_routes.collect_entries
+
+ def counting(*args: object, **kwargs: object) -> object:
+ nonlocal reads
+ reads += 1
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(costs_routes, "collect_entries", counting)
+ costs_routes._cache._key = None # noqa: SLF001 — a cold section, as on open
+
+ for panel in ("summary", "daily", "entries"):
+ assert client.get(f"/api/costs/{panel}?days=30").status_code == 200
+
+ assert reads == 1, f"one page load re-read the stores {reads} times"
+
+
+def test_an_explicit_window_is_reported_exactly(client: TestClient) -> None:
+ """Snapping the open end must not move a window the caller pinned.
+
+ The daily drill-down asks for one exact day. Rounding its bounds would
+ silently redraw a different day than the one that was clicked.
+ """
+ since = NOW_MS - 86_400_000
+ body = client.get(f"/api/costs/summary?since_ms={since}&until_ms={NOW_MS}").json()
+ assert body["since_ms"] == since
+ assert body["until_ms"] == NOW_MS
+
+
+def test_a_rolling_window_keeps_its_exact_width(client: TestClient) -> None:
+ """Snapping moves the end, never the width — the chart's grain depends on it."""
+ body = client.get("/api/costs/summary?days=30").json()
+ assert body["until_ms"] - body["since_ms"] == 30 * 24 * 60 * 60 * 1000