Skip to content

fix(agents): restore token and cost tracking for Cursor CLI sessions - #192

Closed
Hitin wants to merge 8 commits into
AixleHQ:developfrom
Hitin:feature/cursor-usage-tracking
Closed

Hitin wants to merge 8 commits into
AixleHQ:developfrom
Hitin:feature/cursor-usage-tracking

Conversation

@Hitin

@Hitin Hitin commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

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_at is denormalised and written only by the sync_expires_at callback, which fires on a config_data write. The only routine writer of config_data is a token refresh, and refresh_due filters where.not(expires_at: nil). So a credential created before its adapter learned to read token_expires_at is in a closed loop: never selected by the sweep → never refreshed → never written → still NULL. NULL then reads as "never expires" everywhere (refresh_due, refresh_if_expiring!, not_expired, connection_status), so nothing complains. A stored accessToken with exp = 2026-07-31 was 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 the expires_at sync, 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, which TerminalSession#sync_usage copies from the session's UsageStatistic on the finish/fail transition — after before_cleanup has run. So an empty cell means no UsageStatistic row was written at all.

CursorCliAdapter#collect_usage builds 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 two RunSSE turns, on deployed code:

                       turn 1              turn 2
request  (mitmproxy)   06:13:24.043        06:14:17.087
headers  (node logger) +77 ms              +284 ms
stream end (mitmproxy) +13.30 s            +21.45 s

event = request + 301 ms = headers + 224 ms = stream end - 13.0 s

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. So lo is 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:98 exports NODE_OPTIONS --require /opt/mitm/http2-logger.js unconditionally, so the in-process JS logger and the proxy each see every call. A live proxied RunSSE leaves four lines in the log, not two:

13:56:58.833  request   node-http-logger   rid=null
13:56:58.936  request   mitmproxy          rid=c42d6692-…
13:57:02.136  response  node-http-logger   rid=null       ← response HEADERS
13:57:31.760  response  mitmproxy          rid=null       ← stream END

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) makes response_ms the end of the turn. This is a consistency fix, not the correlation fix: +1 s past the headers already contains a +301 ms event. 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_models refreshes and retries on 401; the usage call just returned nil. Compounding it, before_cleanup collected 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.
windows is sorted by start_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_models guards with return [] if data["code"].present?. The usage call had no such guard, so such a body parsed cleanly, usageEventsDisplay was missing, || [] produced an empty array, and a failed call was stamped no_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_windows skips node-http-logger response entries, mirroring what the request side has always done, so response_ms comes 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-logger tags its entries http2-logger and puts x-request-id on both sides, so they keep pairing by rid.
  • match_windows_to_api matches against the RPC's in-flight span, [request_ts, response_ts + 1s], correct whichever logger produced the response entry.
  • fetch_filtered_events refreshes the credential once on 401/403 and retries, mirroring fetch_available_models; collect_usage resolves the credential rather than a bare token so it can. It also returns nil (→ api_error) when the 200 body carries a Connect code.
  • AgentSessionStrategy#before_cleanup and WorkflowStepStrategy#before_cleanup persist refreshed credentials before collecting usage, through one #persist_credentials_then_collect_usage on the parent, so the reason for the order is stated once instead of once per strategy.
  • The API query end bound is the maximum response_ms across all windows.
  • AgentCredential.expiry_unknown + #backfill_expires_at! derive the missing expiry from the token already stored, breaking the loop above. Written with update_column: the value comes from the stored credential material, so going through sync_expires_at would 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.
  • The refresh sweep resolves those rows before selecting what is due — that is the backfill. Affected rows heal on the first tick after deploy and are self-sustaining afterwards, so no one-off task has to be remembered. What stays NULL after 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).
  • A full page from GetFilteredUsageEvents (pageSize: 200, and the endpoint filters by date only — i.e. across the whole Cursor account) now records page_truncated alongside the counts. An undercount wearing a recorded status is harder to catch than an empty cell. Pagination itself is left alone.
  • Every exit path 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 "the agent spent nothing" is distinguishable from "the meter broke" without re-running the session. The UI keeps showing — for a genuine zero (formatTokens/formatCost already do).

Known trade-off

Widening a window to the RPC's in-flight span means that while a long RunSSE is 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 own UsageStatistic, so the same spend is counted twice in any rollup over cost_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 hi back to the response headers is a live option — with lo anchored 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 of event.timestamp - request_ms over more sessions should come first. If Cursor's usageEventsDisplay ever exposes the originating request id, exact matching on x-request-id removes the ambiguity entirely.

What this PR does not fix

persist_refreshed_credentials does not pick up a token obtained by an interactive device login inside the container: it reads ~/.config/cursor/auth.json and ~/.cursor/auth.json, and after a browser login the CLI appears to leave the old blob there, so the early credential.config_data == config_data return 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:

  • A credential whose refresh token has also aged out cannot be recovered server-side; the sweep will now say so (status: error, refresh_error) and the profile will show it as expired, instead of the row sitting active behind 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.rb
  • New coverage: build_rpc_windows takes response_ms from 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 as api_error, not no_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.
  • Caveat on one new test: collect_usage matches an event billed while a streamed RunSSE was still open places 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.
  • Two existing assertions were corrected rather than added to. The regression test previously gave the mitm response entry an x-request-id; real entries never carry one, because mitm_logger.py:135 serialises dict(resp.headers) and x-request-id is 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-id asserted 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.
  • Credential lifecycle: expiry_unknown selects only refreshable rows with no expiry (an API-key credential's NULL is the truth and is left alone); backfill_expires_at! persists the derived expiry, leaves a known one untouched, returns nil for an opaque token, and keeps both the stored blob and the cached model list intact; a backfilled row becomes visible to refresh_due; refresh_if_expiring! resolves the expiry and tops the token up; the sweep reports what it resolved (backfilled:) and puts the row under refresh_due.
  • Truncation: a full page is recorded as page_truncated, a short page is not.
  • Two review points from the previous round are addressed in the tests rather than the code. The cleanup-ordering test asserted a call sequence; it now asserts the outcome the order exists for — which token usage collection actually read (docs/testing.md §6). And the end-to-end fixture in FakeRuntime::MITM_LOGS used the legacy two-entry HTTP/2 Run layout, 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 mitmproxy RunSSE layout, and it goes red if lo = request_ms is reverted.
  • Diagnostics: coverage completed with no_api_events (the other half of the Connect-error distinction) and error (the only path that both records a diagnostic and re-raises).
  • Regression: the pre-existing correlation tests, the Codex/Grok/Claude usage tests and the rest of the strategy suite are unchanged. Claude Code, Gemini, Codex and Grok never call a provider API at cleanup, so their usage paths are untouched; the credential change is type-agnostic by design and covered for claude_code (expiry already known → no-op) as well as cursor_cli.

Test run

Verified by dispatching this repository's own CI workflow in the fork (workflow_dispatch), which runs the same be_check_all / fe_check_all jobs through docker-compose.ci.yml:

  • 34339564841 on 604e3766 — green. Backend: rails-test, rubocop, brakeman, system-test, vite-build all [OK]. Frontend: eslint, typescript, fsd, fe-test all [OK]. Secret Scan OK.
  • 34338745505 on da170515 — one failure, in a new test rather than in the code it covers: backfill_expires_at! keeps … its model cache read through Rails.cache while the test env's store is :null_store, so it could not tell an intact cache from a busted one. 604e3766 points it at a MemoryStore, as the two neighbouring invalidation tests already do.

Not covered: coverage floors. ci.yml passes run-coverage: 1 only for push events, so a dispatched run measures nothing and COVERAGE_MIN was not enforced.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

All contributors have signed the CLA. Thank you!
Posted by the CLA Assistant Lite bot.

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]>
@aixle-com
aixle-com Bot force-pushed the feature/cursor-usage-tracking branch from 05b0566 to 5457d5f Compare September 4, 2026 07:33
@alex-astafyev
alex-astafyev marked this pull request as draft September 4, 2026 07:48
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]>

@Hitin Hitin left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

aixle-developer-agent added 4 commits September 7, 2026 14:11
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"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 assert response_headers_iso.
  • build_rpc_windows pairs mitm RunSSE when response omits x-request-id (the captured-log fixture) — assert 2026-05-21T19:43:57.033Z (headers) instead of 19:44:02.435065Z (stream end).
  • collect_usage matches an event billed while a streamed RunSSE was still open — rename to collect_usage attributes an event billed at the start of a streamed RunSSE; move the event from request_ms + 120_000 to request_ms + 301; change expected_end from stream_end_iso + 1_000 to response_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 assert 19:32:31.000Z for windows.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 Hitin left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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_cleanup that still keeps credentials ahead of usage;
  • it stays green if the reason for the order disappears — e.g. if collect_usage stopped 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"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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-code guard was added to make. collect_usage records api_error for a Connect error returned with HTTP 200 pins the failure side; nothing pins that a genuine {"usageEventsDisplay": []} still lands on no_api_events. If a future change made fetch_filtered_events return nil for 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 RPCs already stubs exactly that empty body — a one-line assert_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_usage swallows the exception, so the metadata stamp is the only durable record that collection blew up, and record_usage_diagnostic's own rescue means 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

aixle-developer-agent and others added 2 commits September 9, 2026 10:05
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants