Repository navigation
fix(usage): retain reset history and unify accounting - #131667
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs real behavior proof before merge. Reviewed August 28, 2026, 5:44 AM ET / 09:44 UTC. ClawSweeper reviewWhat this changesThe PR restructures Gateway and Control UI usage reporting so reset-session history remains visible and cost/token totals share one accounting path. Merge readiness⛔ Blocked until stronger real behavior proof is added - 2 items remain The patch appears correct and remains necessary: current main can suppress discovered reset history when the new current session is empty, while the branch retains that history through ownership-aware selection and loading. Priority: P2 Review scores
Verification
Live VerificationCommand: Result: FAIL (failed) — step 1 Assertions:
How this fits togetherGateway usage reporting combines stored session metadata with discovered JSONL and SQLite history, then returns rows and totals to the Control UI. Reset lineage and per-agent ownership must remain intact through selection, loading, and aggregation. flowchart LR
A[Stored sessions] --> C[Usage session selection]
B[Discovered JSONL and SQLite history] --> C
D[Reset lineage] --> C
C --> E[Per-agent source loading]
E --> F[Shared usage aggregation]
F --> G[Gateway usage response]
F --> H[Control UI usage view]
Before merge
Agent review detailsSecurityNone. PR surfaceSource -266, Tests +571, Docs +1, Other -3. Total +303 across 25 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Merge the focused ownership-aware selection and shared aggregation repair after normal maintainer validation. Do we have a high-confidence way to reproduce the issue? Yes—current-main selection suppresses a discovered historical member whenever its family identity is stored, even when the reset current transcript is empty and no replacement row is emitted. Is this the best way to solve the issue? Yes—the repair makes selection retain the discovered concrete source and centralizes aggregation, matching the owner boundary instead of compensating in the UI. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against a1782855a25a. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles) |
Keep family selection within the recorded agent and assign each instance once. Carry discovered SQLite or JSONL sources into batched loading, including empty current sessions and history encountered before a current artifact. Share Gateway and Control UI aggregation and total arithmetic, use canonical pricing for detail logs, and invalidate both result caches on config changes. Split calendar, cache, selection, and loading owners out of the usage handler. Add failing-before regressions for reset history, overlapping families, mixed sources, config replacement, missing-price exports, and log pricing.
Make batched loading own its minimal input contract and import shared accounting types from the leaf definition instead of the runtime barrel. Remove obsolete current-JSONL fixture setup to keep the existing usage test within its line cap. Verified both CI failures locally: zero Madge cycles and passing core lint with the CI tsconfig. No runtime behavior or public protocol changes.
The shared usage contracts now import their canonical leaf definitions. Remove the six obsolete internal-barrel type re-exports left by that ownership repair.
9ed1b40 to
878b2f0
Compare
|
Maintainer follow-up completed. The canonical selection owner assigns each The initial CI run 33155908560 caught type-import cycles and a two-line test-cap overrun. Commit Validation: 230 focused tests passed; 50 affected tests passed again after the CI repair. Exact commands included: OPENCLAW_VITEST_MAX_WORKERS=1 node scripts/run-vitest.mjs src/gateway/server-methods/usage.sessions-usage-owner-attribution.integration.test.ts src/gateway/server-methods/usage.sessions-usage.test.ts src/gateway/server-methods/usage.sessions-usage-owner-attribution.test.ts src/shared/usage-aggregates.test.ts
node --import ./scripts/tsx.mjs scripts/check-madge-import-cycles.ts
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/gateway/server-methods/usage.sessions-usage.test.ts src/gateway/server-methods/usage-session-selection.ts src/gateway/server-methods/usage-session-loading.ts src/shared/usage-types.ts
pnpm buildThe full local build preceded the final family-source adjustments; final-head hosted CI provides the final build gate. Testbox 33152724369 proved baseline failure and candidate 2/2 real Gateway/Chromium behavior; Testbox 33155330886 recorded the final reset flow, 1/1 passing after installing its missing Playwright FFmpeg recorder. Inspected before/after images and video are in the PR body. These are real Gateway/browser runs with synthetic transcript state, not a live provider or Telegram-account send. ClawSweeper's completed review has no actionable correctness/security findings. Its latest Rank-up request asks for after-fix real behavior proof; the successful final-head hosted browser job below supplies it. Its sandbox could not run docs listing or independent autoreview; CI run 33157421585 passed every lane except an unchanged Chat disclosure fixture, which timed out on both attempts. Main had already fixed the same race in #131622: choose a still-mounted pending message after native pointer cancellation, deliver that exact request, and retain the reader-anchor, row-growth, adjacency, and unmount/remount checks. Rebasing onto Refreshed real-flow proof on head Final-head CI attempt 1 also hit an unrelated startup timeout in Final CI: run 33159536134, attempt 2 is completed / success on The latest ClawSweeper re-review on this exact head failed before either case ran: |
|
Merged via squash.
|
…ream openclaw#131667 Upstream b576bb4 (openclaw#131667) removed mergeUsageLatency / mergeUsageDailyLatency / buildUsageAggregateTail from src/shared/usage-aggregates.ts. The fork-owned ui/src/ui usage-metrics view still consumes them, so keep the bodies verbatim in ui/src/ui/views/usage-aggregate-helpers.ts instead of re-grafting exports into src/shared (which would recreate merge=ours drift). Fixes the ui:build MISSING_EXPORT break and the 3 tsgo:test:ui errors from proof ea34c00.
* fix(usage): retain reset history and unify accounting Keep family selection within the recorded agent and assign each instance once. Carry discovered SQLite or JSONL sources into batched loading, including empty current sessions and history encountered before a current artifact. Share Gateway and Control UI aggregation and total arithmetic, use canonical pricing for detail logs, and invalidate both result caches on config changes. Split calendar, cache, selection, and loading owners out of the usage handler. Add failing-before regressions for reset history, overlapping families, mixed sources, config replacement, missing-price exports, and log pricing. * refactor(usage): keep accounting type imports acyclic Make batched loading own its minimal input contract and import shared accounting types from the leaf definition instead of the runtime barrel. Remove obsolete current-JSONL fixture setup to keep the existing usage test within its line cap. Verified both CI failures locally: zero Madge cycles and passing core lint with the CI tsconfig. No runtime behavior or public protocol changes. * refactor(usage): remove unused accounting type re-exports The shared usage contracts now import their canonical leaf definitions. Remove the six obsolete internal-barrel type re-exports left by that ownership repair.
Follow-up to #128803 (preserving agent ownership for matching session IDs).
What Problem This Solves
Fixes an issue where the Usage page loses a session's historical usage immediately after reset, before the new instance has a transcript. The same accounting flow also had drift between aggregate totals, filtered UI exports, and conversation details: fleet configuration changes could reuse old totals, filtered results dropped missing-price attribution, and detail logs could disagree with the canonical pricing rules.
Why This Change Was Made
Session selection now owns the agent-scoped current/history join and passes selected instances to batched loading. Historical discovery selects its recorded canonical family even when its current transcript is empty. Each instance is assigned once: a direct current owner takes precedence over historical references, and unresolved historical aliases remain independent instances. Discovery supplies the actual SQLite or retained JSONL source to loading; storage is not guessed from the current instance. Independent agents with identical session IDs remain independent. No lineage is inferred beyond the stored family IDs.
The Gateway and Control UI now share one pure accumulator and canonical total arithmetic. Conversation logs reuse the same token, timestamp, and price parser as summaries and charts. Calendar resolution, bounded result caching, session selection, and batched loading have separate owners; the old duplicate paths and two oversized-file exemptions are removed. Both result caches require configuration identity.
No configuration options, protocol shape, database schema, persistence semantics, dependencies, or provider runtime behavior change. Existing file-backed transcript artifacts remain readable. Equal-cost model/provider rows now use the Gateway's token-count tie-breaker consistently in filtered UI results.
User Impact
Historical lineage remains visible after reset. Fleet changes invalidate aggregate cost results. Filtering and JSON exports retain which models have missing prices. Detail logs agree with summary pricing, including tiered rates, unknown pricing, and explicitly provider-billed zero cost.
Real-state regressions retain 30 historical tokens plus 100 from another agent reusing an ID. A retained direct run owns its 10 tokens separately, leaving 20 in the reset family and 130 overall; mixed JSONL/SQLite history also retains all 130.
Evidence
Before-fix reproductions on the pinned Vitest 4.1.11 fail at the actual boundaries: stale fleet totals; three missing-price UI aggregate/export assertions; four log-pricing cases; and a real SQLite reset family omitted from the Gateway response. Candidate tests cover the same cases, sibling archive behavior, cache refresh/eviction, aliases, date/time-zone boundaries, weighted latency, and pre-limit aggregates.
Validation: 99 Gateway usage tests, 73 accounting/pricing tests, and 58 Control UI tests passed (230 total). The full build and Control UI asset/performance gates passed before the final family-source adjustments; those adjustments passed the Gateway selection tests and type checks. Exact-head CI validates the final build before merge. Independent Codex review is clean (no actionable P0–P2 findings); repository changed checks, final Gateway type checks, and formatting passed. Initial CI run33155908560 caught two type-import cycles and a test file two lines over its cap. The follow-up removes the import cycles at their type owners and deletes obsolete fixture setup, with no exemptions. Both failed checks pass locally, all50 affected tests pass, and the repair also has clean independent review. Run33156849140 then identified six unused type re-exports left in the former barrel; those are removed. Production/full-tree/script unused-export scans and core typecheck now pass, with another clean independent review of that type-only deletion.
Real Gateway + Chromium proof ran on Blacksmith Testbox
tbx_01m13nb58x9hbrfedxjwnytnvb(workflow lease). The original baselinebccb649077f086a4935c8f2473b7a72656f1d5a1fails the reset case because the named row is absent. The usage behavior candidate passes both owner/reset cases (2/2); the reset case completed in 1.85 seconds. The lease was stopped after proof. Local browser attempts stalled during startup under shared host load; the clean Testbox run used the normal timeouts, without relaxing assertions. This exercises a real Gateway and browser with synthetic stored transcripts, not a live model or Telegram account.Usage behavior candidate browser recording: the reset case passed on Testbox
tbx_01m13qm07s8bqv13qmyk4vydxv(workflow lease). Recording adds only PlaywrightrecordVideoto the existing test context; assertions and product source are unchanged. The first recording attempt lacked Playwright FFmpeg; installing that recorder dependency on the disposable box fixed the setup failure. The video was inspected before upload, and the lease was stopped.usage-refactor-proof.mp4
Production: 266 fewer lines after accounting for the extracted modules; tests: +571 lines; tooling/docs: -2 lines. The 1,640-line handler is now 388 lines. No oversized-file baseline is increased; two exemptions are removed.
Focused proof commands
The browser command ran through the repository Crabbox wrapper on the Testbox above. Regression tests were demonstrated failing before each owner-boundary repair, not only added after the fix.
The separate conflicting-scope request validation issue #125268 already has PR #125269; this follow-up does not duplicate that RPC contract change.
CI run 33157421585 passed every lane except the unchanged Chat disclosure scrolling test, which timed out on both attempts. Current main had already fixed that same test race in #131622 by binding deferred recovery to a still-mounted row. This branch was rebased onto
4ec40f190d4580dad0c5d4dc5d111400ef12a60cto reuse that landed fix;git range-diffconfirms all three usage commits are patch-identical. Final head878b2f0a036ed1579f5c0989977e818523ea5706receives fresh CI. The screenshots/video above precede the mechanical type cleanup and rebase; final-head CI supplies the refreshed build and browser gates.Refreshed real-flow proof on head
878b2f0a036ed1579f5c0989977e818523ea5706: the hosted Gateway/Chromium job passed both owner/reset cases, 2/2, in 25.96 seconds total; the empty-current reset case itself took 2.04 seconds. This addresses the latest ClawSweeper Rank-up request for after-fix proof. Its attempt expired while waiting 30 seconds for terminal output and showed only Vitest startup, without a failing product assertion. The completed hosted run and inspected Testbox recording provide the missing terminal and browser evidence. The inherited Chat disclosure shard also passes on this head.The latest ClawSweeper re-review on this exact head failed before either case ran:
/usr/bin/chromium-browseraborted duringbrowserType.launch(SIGABRT; both cases skipped). That is browser setup failure, not a failed usage assertion. The final-head hosted Gateway/Chromium job linked above completed both cases successfully, and the inspected recording remains attached. This supplies the requested real-flow evidence without weakening the product tests or treating the failed sandbox run as a pass.