Repository navigation
Conversation
|
All contributors have signed the CLA. Thank you! |
Completed Cursor CLI sessions showed `-` for Tokens and Cost. Usage is collected at cleanup by correlating AgentService RPCs from the MITM log with billing events from Cursor's Dashboard API, and three defects on that path each end it with no UsageStatistic — so `TerminalSession#sync_usage` has nothing to copy into the columns the sessions list renders. Correlation window anchored on the wrong end of the RPC. A window was [response_ts, response_ts + 1s], which assumes the response entry is written when the response HEADERS arrive. That holds for http2-logger and node-http-logger, which fire on the `response` event; it does not hold for mitmproxy, whose addon streams the body and writes its entry when the stream ENDS — minutes later for an agent turn. `useHttp1ForAgent` routes AgentService/RunSSE through the proxy, so a session whose response entries came only from mitmproxy had every billing event fall before its window. The window is now the RPC's in-flight span, [request_ts, response_ts + 1s], which is correct for either logger since a billing event cannot predate its request. No refresh on a 401 from the Dashboard API. Cursor access tokens are short-lived JWTs and this call runs at cleanup — the far end of the session, when the token stored at launch is most likely to have aged out. Every other Cursor call in the adapter refreshes and retries; this one returned nil. It now refreshes once and retries, and cleanup persists the container's rotated credential BEFORE collecting usage rather than after, so the call authenticates with the freshest token the session produced. API query end bound taken from the last window by request time. `windows` is sorted by request, so with overlapping RPCs the last to start is not the last to finish and the final billing event fell outside the query. Use the maximum response across all windows. Every exit path now stamps `metadata.usage_collection.status` on the session (recorded / no_mitm_log / no_rpc_windows / no_access_token / api_error / no_api_events / no_matching_events / error), so an empty Tokens cell can be told apart from a dropped meter without re-running the session. Signed-off-by: Artem Petrov <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
05b0566 to
5457d5f
Compare
The cleanup reorder in 5457d5f (persist refreshed credentials BEFORE collecting usage) makes the cursor_cli agent_session cases of ContainerWorkflowIntegrationTest reach Cursor's dashboard API for real, and nothing answered it: 4 errors, all `WebMock::NetConnectNotAllowedError: POST .../GetFilteredUsageEvents`. The test never got that far before because the credential it creates comes from the `:agent_credential` factory, whose config_data is `{api_key, theme}` — no accessToken, so `#collect_usage` bailed out one step earlier. With credentials persisted first, FakeRuntime's auth.json supplies a real token and its MITM log supplies a completed AgentService run, so the correlation call fires. The `rescue StandardError` around usage collection does not catch it, because WebMock's error descends from Exception on purpose. Answer the call from the shared support module, next to the Traefik stub, rather than inline in the feature test: the reply carries one billing event stamped inside the window the request itself asks for, so it does not depend on the fixture's load-time wall-clock. Then assert the outcome instead of merely surviving it — the cursor_cli agent_session cases now check that a UsageStatistic was written from `cursor_api`, that `metadata.usage_collection.status` is `recorded`, and that `#sync_usage` copied tokens and cost onto the columns the sessions list renders. That is the regression in palad-ai/palad-app#584, covered end to end at the integration layer. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Artem Petrov <[email protected]>
There was a problem hiding this comment.
Review of the Cursor usage-tracking restore.
Correction (2026-09-09): the mechanism claimed in the original text of this summary was wrong, and it is retracted — see r3965345675, and 17f586e for the corrected in-source rationale.
There is no mitmproxy-only log shape: start-mitm.sh:98 loads http2-logger.js into the agent unconditionally, so every proxied RPC leaves four entries, not two. And the billing event is stamped at the start of the turn, not at its end — measured on deployed code at event = request + 301 ms = response headers + 224 ms = stream end - 13.0 s. So the bound that broke correlation is lo, anchored on the response headers, and anchoring it on the request is the fix. Ending the window at the stream end is not load-bearing for matching; its measurable effect is to widen each window from ~1 s to 13-22 s, which is the double-count trade-off tracked in r3948627440 and in the Known trade-off section of the description.
The defect that actually produced the symptom reported in palad-ai/palad-app#584 was not in this code path at all: an AgentCredential whose expires_at was NULL was invisible to the refresh sweep, so a June access token was still being used in September and the Dashboard API call failed authentication. Reconnecting the credential restored tokens and cost on deployed develop with no part of this PR applied. See Root cause and What this PR does not fix in the description.
Still accurate from the original review: the before_cleanup reorder is safe for the other runtimes — collect_usage is a no-op in BaseAdapter, and the Codex/Grok implementations never touch the credential. Diagnostics per exit path are the right shape for this bug, and they are the piece that turns a silent zero into a one-field diagnosis next time.
No blocking findings.
Review of PR AixleHQ#192 against a live MITM capture showed the previous change moved the boundary that was not broken. Every agent RPC is logged twice, because start-mitm.sh loads http2-logger.js into the agent unconditionally: a proxied RunSSE leaves four lines, not two. The node-http-logger response entry fires on response HEADERS, claimed the pending request id and shifted it off the pending list, so mitmproxy's stream-end entry found nothing to pair with and its timestamp was discarded on every RPC. response_ms was therefore always the headers time. On a 258-second session that left a window 1141 ms wide and the dashboard query came back empty — the regression this PR set out to fix survived it. Skip node-http-logger on the response side, mirroring what the request side has always done. Its entries carry no headers at all, so they can never register a request id and could only ever overwrite a timestamp; a proxy-less session produced zero windows before this change and still does, so nothing was serving as a fallback. The legacy HTTP/2 path is untouched: http2-logger tags its entries http2-logger and puts x-request-id on both sides. Also guard fetch_filtered_events against a Connect error returned with an HTTP 200, the way fetch_available_models already does. Without it such a body parses cleanly, usageEventsDisplay is missing, and a failed call was reported as no_api_events — "nothing was billed" — which is the exact ambiguity the diagnostic exists to remove. The regression test fixture gave the mitm response entry an x-request-id, which real entries never have (mitm_logger.py serialises the RESPONSE headers), and omitted the node-http-logger entries entirely; it encoded a log shape that does not occur, which is why it passed. It now uses the real four-entry layout, and the captured-log test asserts the stream-end timestamp instead of the headers one.
A live measurement on deployed code (two RunSSE turns) puts the billing
event at request + 301 ms — the start of the turn, not the end:
event = request + 301 ms = response headers + 224 ms = stream end - 13.0 s
So `lo`, anchored on the response headers, is the bound that broke
correlation, and anchoring it on the request is the fix. Ending the window
at the stream end instead of the headers is not load-bearing for matching;
its effect is to widen each window from ~1 s to the turn's duration, which
makes the concurrent-session double-count noted in review likelier.
Comments only — no behaviour change. Retracts the explanation in
AixleHQ#192 (comment), per
AixleHQ#192 (comment).
| assign_response_timestamp!(responses, pending_by_path, path, ts) | ||
| next | ||
| end | ||
| next if source == "node-http-logger" |
There was a problem hiding this comment.
[Recommendation] Source: the live measurement in r3965345675, plus r3948627440. Not blocking.
This line is the one change in the PR that was made on a premise since retracted, and reverting it is worth considering before merge:
when "response"
if source == "node-http-logger"
assign_response_timestamp!(responses, pending_by_path, path, ts)
next
end
if rid.present?It buys no additional match. The billing event is stamped at request + 301 ms; hi at response headers + 1 s already contains it, and did so on both measured turns (headers at +77 ms and +284 ms). What extending hi to the stream end does is widen every window from ~1 s to the turn's duration — 13.3 s and 21.5 s on the session measured.
Width is what decides the double count in r3948627440: while one RPC is in flight, an event billed to a concurrent session on the same Cursor account lands inside this session's window too, and each session writes its own UsageStatistic, so the same spend appears twice in a rollup. Concurrent sessions on one account are routine here, so a turn-wide window makes that the common case rather than the corner one. An inflated cost_cents is silent and reproducible, which is worse to chase than an empty cell.
lo = request_ms from 5457d5f stays untouched — that is the bound that actually broke correlation.
The residual risk runs the other way and should be written into the comment rather than left implicit: +301 ms is a single measured billing event. If Cursor ever stamps a bill nearer the end of a turn, a headers-anchored hi misses it. The spread of event.timestamp - request_ms over more sessions is what would justify moving this bound again — which is the same evidence the current comment already asks for.
Four test edits follow from the revert. Listing them because missing one turns CI red rather than failing loudly in review:
build_rpc_windows takes response_ms from the stream end, not the response headers— rename and invert to assertresponse_headers_iso.build_rpc_windows pairs mitm RunSSE when response omits x-request-id(the captured-log fixture) — assert2026-05-21T19:43:57.033Z(headers) instead of19:44:02.435065Z(stream end).collect_usage matches an event billed while a streamed RunSSE was still open— rename tocollect_usage attributes an event billed at the start of a streamed RunSSE; move the event fromrequest_ms + 120_000torequest_ms + 301; changeexpected_endfromstream_end_iso + 1_000toresponse_headers_iso + 1_000. Keep the four-entry log fixture, it is the realistic part.build_rpc_windows pairs consecutive streamed RPCs in FIFO order— the first window now closes on its node-logger headers entry, so assert19:32:31.000Zforwindows.first[:response_ms]. Note the FIFO path is then exercised only by the second RPC; worth a comment in the test.
Verified by inspection as unaffected: the two http2-logger correlation tests, collect_usage queries up to the latest response across overlapping RPCs, test/support/stub_support.rb (its event sits at window_start + 1 ms, inside a headers-anchored window), the container integration test (FakeRuntime's fixture is a unary http2-logger Run), and agent_session_strategy_test.rb.
Also worth updating if this is taken: the doc comments above build_rpc_windows and match_windows_to_api currently present the turn-wide window as the deliberate choice, so they would contradict the code.
Hitin
left a comment
There was a problem hiding this comment.
Review of the Cursor usage-tracking restore — cycle 4 (HEAD 17f586e, docs-only since 813b076).
Re-reviewed the whole diff against upstream/develop (19550ef), not just the last commit. Verified from source, rather than taken on trust, that every factual claim the code comments now make is accurate: start-mitm.sh:98 exports NODE_OPTIONS --require /opt/mitm/http2-logger.js unconditionally; http2-logger.js:126,136 writes node-http-logger entries with no headers block, so they can never register a request id (which is why skipping them on the response side is not a regression for a proxy-less session); mitm_logger.py:135 serialises dict(resp.headers), so a mitmproxy response entry genuinely cannot carry x-request-id; and generate_cli_config does force useHttp1ForAgent => true. The 17f586e rewrite of the build_rpc_windows / match_windows_to_api comments matches the retraction in r3965345675 — the stale explanation is gone.
Also confirmed the pieces the description depends on: AgentSessionStrategy#collect_usage wraps the adapter in rescue StandardError, so the new rescue … raise in collect_usage cannot break cleanup or leak the session lock (and WorkflowStepStrategy < AgentSessionStrategy, so it inherits the same guard); resolve_credential re-queries the row, so the before_cleanup reorder really does hand the freshly persisted token to the dashboard call; and TerminalSession#sync_usage uses partial update!, so the update_column(:metadata, …) writes are not clobbered on the finish transition. update_column(:metadata, …) read-modify-write is the established pattern here (AgentBaseStrategy#persist_vscode_token), so no remark on it.
No [Must] findings this cycle. The diagnostic statuses are the real product value and they are the right call. Four non-blocking remarks below, all in test coverage or observability; the open trade-off on window width is already tracked in r3966636609 and r3948627440 and is not repeated here.
Note that I could not execute the suite or RuboCop — this environment has no Ruby toolchain — so the coverage remarks come from reading the tests, not from a run.
| strategy.stubs(:collect_terminal_output).returns(0) | ||
|
|
||
| cleanup = sequence("cleanup") | ||
| strategy.expects(:persist_refreshed_credentials).in_sequence(cleanup) |
There was a problem hiding this comment.
[Recommendation] Source: project documentation — docs/testing.md §6 ("Assert observable behavior … never internal call graphs") and the §8 PR checklist item "Assertions state outcomes, not call sequences (R5, §6)".
This is the only in_sequence assertion in the file, and it pins a call graph rather than the guarantee the reorder exists for. Two consequences:
- it goes red on any harmless reshuffle of
before_cleanupthat still keeps credentials ahead of usage; - it stays green if the reason for the order disappears — e.g. if
collect_usagestopped reading the stored token at all, the sequence would still hold and the test would still pass while asserting nothing anyone cares about.
The observable outcome is available cheaply, because the whole point is which token is in the database when the dashboard call goes out. Something like: let persist_refreshed_credentials run against a real AgentCredential (or stub it to write a sentinel token), then have the collect_usage double read the row and assert what it saw —
seen = nil
strategy.stubs(:persist_refreshed_credentials).with { credential.update!(config_data: { "accessToken" => "rotated" }); true }
mock_adapter.stubs(:collect_usage).with { seen = credential.reload.config_data["accessToken"]; true }
strategy.before_cleanup(container_id: "abc123")
assert_equal "rotated", seen, "usage collection must see the token persisted this cleanup"That survives refactors that preserve the guarantee and fails on the one that breaks it.
I am deliberately not raising R1 ("never stub the class under test") here: strategy.stubs(...) is used in ~68 places in this file already, so the new test follows local convention and singling it out would be unfair. Only the call-sequence assertion is new to the file.
| end | ||
|
|
||
| # ========================================================================= | ||
| # collect_usage diagnostics — "no usage" vs "the meter broke" |
There was a problem hiding this comment.
[Recommendation] Source: the PR's own stated coverage ("each diagnostic status is recorded on its own exit path") and acceptance criterion 5 of the task — an empty cell must be distinguishable from a broken meter.
Six of the eight statuses in USAGE_DIAGNOSTIC_KEY's doc block are asserted here (recorded, no_mitm_log, no_rpc_windows, no_access_token, api_error, no_matching_events). Two are not, and both matter more than the ones that are:
-
no_api_events— this is the other half of the distinction the Connect-codeguard was added to make.collect_usage records api_error for a Connect error returned with HTTP 200pins the failure side; nothing pins that a genuine{"usageEventsDisplay": []}still lands onno_api_events. If a future change madefetch_filtered_eventsreturnnilfor an empty list, or[]for a transport failure, the suite would not notice, and the whole guard collapses back into the ambiguity it was written to remove.collect_usage queries up to the latest response across overlapping RPCsalready stubs exactly that empty body — a one-lineassert_equal "no_api_events", …there would close it, or a dedicated test alongside the others. -
error— the only exit path that both stamps a diagnostic and re-raises. That combination is new behaviour and is load-bearing:AgentSessionStrategy#collect_usageswallows the exception, so the metadata stamp is the only durable record that collection blew up, andrecord_usage_diagnostic's ownrescuemeans a silent regression here is invisible. Worth pinning both halves:
test "collect_usage records the error and re-raises when collection blows up" do
# … session + credential + a log with one completed run …
@adapter.stubs(:fetch_filtered_events).raises(ArgumentError, "boom")
assert_raises(ArgumentError) { @adapter.collect_usage(session, { "logs/http.log" => mitm_log }) }
diagnostic = session.reload.metadata["usage_collection"]
assert_equal "error", diagnostic["status"]
assert_match(/ArgumentError: boom/, diagnostic["message"])
end| # (stubbed above) — and it is the one agent where an ordering slip in | ||
| # #before_cleanup leaves the columns the sessions list renders empty on a run | ||
| # that plainly happened. Assert the whole path, not just that it did not raise. | ||
| def assert_cursor_usage_recorded(session) |
There was a problem hiding this comment.
[Recommendation] Source: existing repository code — CursorCliAdapter#generate_cli_config ("useHttp1ForAgent" => true) versus the fixture in test/support/fakes/fake_runtime.rb (MITM_LOGS["cursor_cli"]).
Adding this assertion is the right instinct — it is the only place the whole path (MITM log → dashboard call → UsageStatistic → terminal_sessions.total_tokens) is checked end to end, and its comment is correct that an ordering slip in #before_cleanup is exactly what it catches.
The problem is the log shape it runs on. MITM_LOGS["cursor_cli"] is two entries, both _source: "http2-logger", both carrying x-request-id, on /agent.v1.AgentService/Run — the legacy HTTP/2 layout. Production is the opposite: generate_cli_config forces useHttp1ForAgent => true, so every agent RPC goes over HTTP/1 through mitmproxy and produces the four-entry RunSSE shape (node-http-logger request, mitmproxy request with the rid, node-http-logger response headers, mitmproxy response at stream end) that this PR's build_rpc_windows change is entirely about.
So the new end-to-end guard exercises the rid-pairing branch and never the FIFO assign_response_timestamp! branch — i.e. it would not go red if the change under review were reverted or broken. The unit tests do cover the four-entry shape, but only against build_rpc_windows in isolation.
Suggestion: give MITM_LOGS["cursor_cli"] the production four-entry RunSSE layout (or add it as a second fixture keyed for this test). Since the stub in stub_cursor_usage_api already reads startDate back off the request rather than guessing at wall-clock, the assertions here should carry over unchanged. Worth checking the other cursor_cli integration combinations still pass, since assert_session_logs_collected reads the same fixture.
| nil | ||
| end | ||
|
|
||
| def request_filtered_events(access_token, time_window) |
There was a problem hiding this comment.
[Note] Source: general engineering best practices, applied to this PR's own design goal — every exit path should say what it managed to do.
Pre-existing, not introduced here, and not worth blocking on — but it is the one remaining way this collector can silently undercount, and the diagnostic added in this PR is the natural place to make it visible.
The query is a single page: page: 1, pageSize: API_PAGE_SIZE (200), with no follow-up request and no check on whether the answer was truncated. GetFilteredUsageEvents is scoped by date range only, not by session, and api_start/api_end now span the whole session, so the page budget is shared with every other run billed to the same Cursor account in that interval. A long session (one billing event per turn) or a few concurrent sessions can plausibly reach 200 events in the window; past that, some of this session's events are simply not in the reply, correlate_events matches fewer, and the row is written with a recorded status and a quietly low cost_cents. An understated bill that looks successful is harder to notice than the empty cell this PR set out to fix.
Cheapest useful step, without adding pagination: treat a full page as suspect and say so, e.g. stamp "page_truncated" => true in the recorded diagnostic when api_events.size == API_PAGE_SIZE, alongside the existing windows_count / api_count / matched_count. That turns a silent undercount into the same one-field diagnosis the api_error status now gives, and leaves real pagination as a follow-up if the flag ever fires.
Completed Cursor CLI runs showed a duration and an empty Tokens/Cost pair. The meter itself was fine: the credential it authenticates with was two months dead. AgentCredential#expires_at is the only place the app knows a token's lifetime, and it is written by a before_save that fires on a config_data change. The only routine writer of config_data is a refresh, and .refresh_due selects `where.not(expires_at: nil)` — so a row whose expiry was never derived (created before #token_expires_at landed for its agent type) can never acquire one: never selected, never refreshed, never written. NULL then reads as "never expires" everywhere, so nothing complains. The session still works, because the CLI in the container gets its own 401, runs a device login and carries on; only the server-side calls made with the STORED token break, and Cursor's usage dashboard is one of them. - AgentCredential.expiry_unknown + #backfill_expires_at! derive the expiry from the token already stored, via update_column so identical credential material is not re-encrypted and the model cache is not busted. - The refresh sweep resolves those rows before selecting what is due, which is the backfill: affected rows heal on the first tick after deploy and are then self-sustaining. - #refresh_if_expiring! resolves it too — the last point before a token is written into a container, and the only one for a credential the sweep has never seen. Also, from review of the cursor usage path: - A full page from the dashboard endpoint (which filters by date only, i.e. across the whole account) now records `page_truncated`. An undercount wearing a `recorded` status is harder to catch than an empty cell. - The credential/usage ordering invariant in cleanup lives in one place (#persist_credentials_then_collect_usage) instead of once per strategy, and is covered by what usage collection actually read rather than by a call sequence. - The end-to-end Cursor fixture uses the production four-entry mitmproxy RunSSE layout, so the columns the sessions list renders are checked against the log shape prod actually produces. - Diagnostic coverage completed with `no_api_events` and `error`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The test env's cache is :null_store, so `Rails.cache.read` came back nil and the assertion could not tell an intact cache from a busted one. Point it at a MemoryStore, as the two neighbouring invalidation tests already do.
Problem
Completed Cursor CLI sessions showed
-for Tokens and Cost even when the run finished normally (COMPLETED, duration present). Fixes #584.Root cause
Two independent defects produce the same empty cell, and they were untangled in that order.
What was observed in production: a credential stuck without an expiry
The sessions that prompted #584 were not losing the correlation — their Dashboard API call was failing authentication.
AgentCredential#expires_atis denormalised and written only by thesync_expires_atcallback, which fires on aconfig_datawrite. The only routine writer ofconfig_datais a token refresh, andrefresh_duefilterswhere.not(expires_at: nil). So a credential created before its adapter learned to readtoken_expires_atis in a closed loop: never selected by the sweep → never refreshed → never written → stillNULL.NULLthen reads as "never expires" everywhere (refresh_due,refresh_if_expiring!,not_expired,connection_status), so nothing complains. A storedaccessTokenwithexp = 2026-07-31was still being handed out on 2026-09-07.The failure is silent by construction, which is why it took two months to surface: the session itself looks healthy, because the CLI inside the container hits its own 401 and re-authenticates via device login, while the server-side usage call keeps using the dead token from the database. Reconnecting the credential by hand was enough to make tokens and cost record correctly on deployed
develop, with no part of this PR applied — which is what identified the row, rather than the code, as the thing that was broken.Radius: any credential of a refreshable type (
claude_code,codex,cursor_cli) that predates theexpires_atsync, not only Cursor. Cursor is where it shows, because Cursor is the runtime whose usage is collected by calling the provider with the stored token.What this PR fixes
Display and rollups were never the problem. The sessions list renders
terminal_sessions.total_tokens/cost_cents, whichTerminalSession#sync_usagecopies from the session'sUsageStatisticon thefinish/failtransition — afterbefore_cleanuphas run. So an empty cell means noUsageStatisticrow was written at all.CursorCliAdapter#collect_usagebuilds that row by correlating AgentService RPCs parsed out of the MITM log with billing events fetched from Cursor's Dashboard API. Four defects on that path each end it with no row:1. The correlation window could miss the moment the turn was billed (primary).
A window was
[response_ts, response_ts + 1s]— a one-second slot hung off the end of the RPC, anchored on the response headers. Cursor stamps the billing event at the start of the turn. Measured on a live session with twoRunSSEturns, on deployed code:With headers that prompt, the old window
[+77 ms, +1077 ms]still contained the event and that session recorded correctly. It breaks when the headers lag: in the capture that first exposed this the headers arrived 3.2 s after the request, the window was[+3.2 s, +4.2 s], and an event at +301 ms fell before it. Solois the broken bound, and anchoring it on the request removes the failure mode — a billing event cannot predate the request that caused it.Every agent RPC is also logged twice —
start-mitm.sh:98exportsNODE_OPTIONS --require /opt/mitm/http2-logger.jsunconditionally, so the in-process JS logger and the proxy each see every call. A live proxiedRunSSEleaves four lines in the log, not two:The node response entry claimed the pending rid and shifted it off
pending_by_path, so mitmproxy's stream-end entry found nothing to pair with. Skipping it (the request side has always skipped these) makesresponse_msthe end of the turn. This is a consistency fix, not the correlation fix:+1 spast the headers already contains a+301 msevent. Its measurable effect is to widen each window from ~1 s to the turn's duration — see the trade-off below.2. No refresh on a 401 from the Dashboard API.
Cursor access tokens are JWTs with an
exp— the adapter already reads it for the proactive refresh sweep. This call runs at cleanup, the far end of the session, when the token stored at launch is most likely to have aged out.fetch_available_modelsrefreshes and retries on 401; the usage call just returnednil. Compounding it,before_cleanupcollected usage before persisting the container's rotated credential, so it read a token the session had already replaced.3. The API query's end bound came from the last window by request time.
windowsis sorted bystart_ms; with overlapping RPCs the last to start is not the last to finish, so the final billing event could fall outside the queried range.4. A Connect error returned with an HTTP 200 was read as "nothing was billed".
The Connect protocol answers errors with a 200 and an error body — which is why
fetch_available_modelsguards withreturn [] if data["code"].present?. The usage call had no such guard, so such a body parsed cleanly,usageEventsDisplaywas missing,|| []produced an empty array, and a failed call was stampedno_api_events. That is exactly the reading the new diagnostic exists to make unambiguous — and it is the guard that would have turned the credential failure above into a one-field diagnosis instead of an investigation.Cursor-only — Claude Code and Gemini use OTLP telemetry, Codex and Grok parse the MITM log directly and never call a provider API at cleanup.
Changes
build_rpc_windowsskipsnode-http-loggerresponse entries, mirroring what the request side has always done, soresponse_mscomes from mitmproxy's stream-end entry and the window covers the whole turn. Nothing was relying on the node entry: it carries no headers at all (http2-logger.js:126,136), so it can never register a request id, and a proxy-less session produced zero windows before this change and still does. The legacy HTTP/2 path is untouched —http2-loggertags its entrieshttp2-loggerand putsx-request-idon both sides, so they keep pairing by rid.match_windows_to_apimatches against the RPC's in-flight span,[request_ts, response_ts + 1s], correct whichever logger produced the response entry.fetch_filtered_eventsrefreshes the credential once on 401/403 and retries, mirroringfetch_available_models;collect_usageresolves the credential rather than a bare token so it can. It also returnsnil(→api_error) when the 200 body carries a Connectcode.AgentSessionStrategy#before_cleanupandWorkflowStepStrategy#before_cleanuppersist refreshed credentials before collecting usage, through one#persist_credentials_then_collect_usageon the parent, so the reason for the order is stated once instead of once per strategy.response_msacross all windows.AgentCredential.expiry_unknown+#backfill_expires_at!derive the missing expiry from the token already stored, breaking the loop above. Written withupdate_column: the value comes from the stored credential material, so going throughsync_expires_atwould re-encrypt an identical blob and bust the model cache for no change. No-op when the expiry is known, when the token carries none, or when the type is not refreshable.NULLafter a pass is a credential whose token really has no expiry.#refresh_if_expiring!resolves it too: the last point before a token is written into a container, and the only one for a credential the sweep has never seen. A row whose token is already dead now gets a real refresh attempt there instead of being handed over as "never expires"; if the refresh fails without condemning the credential, launch behaviour is unchanged (warn, start on the token in hand).GetFilteredUsageEvents(pageSize: 200, and the endpoint filters by date only — i.e. across the whole Cursor account) now recordspage_truncatedalongside the counts. An undercount wearing arecordedstatus is harder to catch than an empty cell. Pagination itself is left alone.metadata.usage_collection.statuson the session —recorded,no_mitm_log,no_rpc_windows,no_access_token,api_error,no_api_events,no_matching_events,error— so "the agent spent nothing" is distinguishable from "the meter broke" without re-running the session. The UI keeps showing—for a genuine zero (formatTokens/formatCostalready do).Known trade-off
Widening a window to the RPC's in-flight span means that while a long
RunSSEis open, an event billed to a concurrent session on the same Cursor account can land inside this session's window — and each session writes its ownUsageStatistic, so the same spend is counted twice in any rollup overcost_cents. Ending the window at the stream end rather than the headers takes windows from ~1 s to 13–22 s on the measured session, which makes that case materially likelier than it was.The API query already spanned the whole session, so the two were never separable here; double-counting two concurrent sessions beats dropping the usage of both. Narrowing
hiback to the response headers is a live option — withloanchored on the request it would still have matched every event measured so far — but that rests on a single measured billing event, so the spread ofevent.timestamp - request_msover more sessions should come first. If Cursor'susageEventsDisplayever exposes the originating request id, exact matching onx-request-idremoves the ambiguity entirely.What this PR does not fix
persist_refreshed_credentialsdoes not pick up a token obtained by an interactive device login inside the container: it reads~/.config/cursor/auth.jsonand~/.cursor/auth.json, and after a browser login the CLI appears to leave the old blob there, so the earlycredential.config_data == config_datareturn wins. With the expiry resolved, that path is a fallback rather than part of the fix — the token is now refreshed server-side before it can die — so it is left for a follow-up.Two operational notes, not code:
status: error,refresh_error) and the profile will show it as expired, instead of the row sittingactivebehind a dead token. Those users re-authenticate once.metadata.usage_collection.status == "api_error"remains the early signal that a credential has gone bad again, instead of two months of silent zeros.How to test
docker compose exec -T web bin/rails test test/models/agent_credential_test.rb test/services/agents/cursor_cli_adapter_test.rb test/services/container_strategies/agent_session_strategy_test.rb test/temporal/activities/agent_credentials/refresh_expiring_tokens_activity_test.rb test/integration/container_workflow_integration_test.rbbuild_rpc_windowstakesresponse_msfrom the stream end on the real four-entry layout, and pairs consecutive streamed RPCs in FIFO order; an event billed two minutes into a stream is attributed end to end and the queried span runs to the stream end; a Connect error in a 200 is recorded asapi_error, notno_api_events; a 401 on the dashboard call is refreshed and retried; the query end bound follows the latest response across overlapping RPCs; each diagnostic status is recorded on its own exit path; cleanup persists credentials before collecting usage.collect_usage matches an event billed while a streamed RunSSE was still openplaces the event 120 s into a 180 s stream. It exercises the widened window, but the measured billing offset is +301 ms from the request, so that layout is not one production produces.x-request-id; real entries never carry one, becausemitm_logger.py:135serialisesdict(resp.headers)andx-request-idis a request header — and it omitted the node-http-logger entries entirely, so it encoded a log shape that does not occur, which is why it passed.build_rpc_windows pairs mitm RunSSE when response omits x-request-idasserted the node logger's headers timestamp (19:43:57.033); it now asserts mitmproxy's stream end (19:44:02.435), 5.4 s later on that captured short turn.expiry_unknownselects only refreshable rows with no expiry (an API-key credential'sNULLis the truth and is left alone);backfill_expires_at!persists the derived expiry, leaves a known one untouched, returnsnilfor an opaque token, and keeps both the stored blob and the cached model list intact; a backfilled row becomes visible torefresh_due;refresh_if_expiring!resolves the expiry and tops the token up; the sweep reports what it resolved (backfilled:) and puts the row underrefresh_due.page_truncated, a short page is not.docs/testing.md§6). And the end-to-end fixture inFakeRuntime::MITM_LOGSused the legacy two-entry HTTP/2Runlayout, so the only check on the columns the sessions list renders never touched the FIFO branch this PR is about; it is now the production four-entry mitmproxyRunSSElayout, and it goes red iflo = request_msis reverted.no_api_events(the other half of the Connect-error distinction) anderror(the only path that both records a diagnostic and re-raises).claude_code(expiry already known → no-op) as well ascursor_cli.Test run
Verified by dispatching this repository's own
CIworkflow in the fork (workflow_dispatch), which runs the samebe_check_all/fe_check_alljobs throughdocker-compose.ci.yml:34339564841on604e3766— green. Backend:rails-test,rubocop,brakeman,system-test,vite-buildall[OK]. Frontend:eslint,typescript,fsd,fe-testall[OK]. Secret Scan OK.34338745505onda170515— one failure, in a new test rather than in the code it covers:backfill_expires_at! keeps … its model cacheread throughRails.cachewhile the test env's store is:null_store, so it could not tell an intact cache from a busted one.604e3766points it at aMemoryStore, as the two neighbouring invalidation tests already do.Not covered: coverage floors.
ci.ymlpassesrun-coverage: 1only forpushevents, so a dispatched run measures nothing andCOVERAGE_MINwas not enforced.🤖 Generated with Claude Code