Skip to content

fix(dashboard): stop quota data writes from delaying request completion - #8538

Open
oldnicke wants to merge 1 commit into
QuantumNous:mainfrom
oldnicke:fix/quota-data-save-lock-8536
Open

oldnicke wants to merge 1 commit into
QuantumNous:mainfrom
oldnicke:fix/quota-data-save-lock-8536

Conversation

@oldnicke

@oldnicke oldnicke commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #8536

Request summary

Summary

SaveQuotaDataCache held CacheQuotaDataLock for every quota_data query and write. RecordConsumeLog calls LogQuotaData, which needs the same lock, so a slow quota_data write delayed the end of the HTTP request after settlement.

SaveQuotaDataCache now holds the cache lock only to swap the pending map for an empty one. It writes the snapshot without that lock. A separate quotaDataSaveLock keeps the periodic save and the shutdown save from writing at the same time.

 SaveQuotaDataCache
+  quotaDataSaveLock.Lock
   CacheQuotaDataLock.Lock
+  pending = CacheQuotaData; CacheQuotaData = new map
+  CacheQuotaDataLock.Unlock
-  for each CacheQuotaData row: query / increase / create quota_data
+  for each pending row: query / increase / create quota_data
-  CacheQuotaData = new map
-  CacheQuotaDataLock.Unlock

If a request calls LogQuotaData during a save, the entry goes into the new map and the next save writes it. The save does not drop or double count that entry. The upsert logic and the quota_data schema are unchanged.

Evidence

The new test TestLogQuotaDataDoesNotWaitForQuotaDataWrite in model/usedata_flow_test.go holds the only SQLite connection in an open transaction. This makes SaveQuotaDataCache block on its first quota_data query. The test then calls LogQuotaData and expects it to return. After the transaction ends, the test checks that the next save writes count = 2, quota = 150, token_used = 80.

  • Before: go test ./model -run TestLogQuotaDataDoesNotWaitForQuotaDataWrite -count=1 -v fails with save never took its snapshot while the database was busy. The save held CacheQuotaDataLock for the full 1003 ms query.
  • After: the same command passes. go test ./model -run TestLogQuotaData -race -count=1 passes. go test ./model -count=1 passes. go vet ./model reports nothing.

The change adds no SQL, schema, or migration, so it has no database dialect impact.

…on (QuantumNous#8536)

SaveQuotaDataCache held CacheQuotaDataLock while writing every cached row to
quota_data, so RecordConsumeLog waited behind a slow database write before the
HTTP response could finish. Take the pending snapshot under the cache lock and
write it outside, serialized by a separate save lock. Entries logged during the
write stay in the cache and land in the next flush.
@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

SaveQuotaDataCache now detaches the quota data cache before database writes. This lets LogQuotaData update the new cache while a save is in progress. A test checks that both entries are persisted.

Changes

Quota cache persistence

Layer / File(s) Summary
Detach cache and persist snapshot
model/usedata.go, model/usedata_flow_test.go
SaveQuotaDataCache serializes saves, swaps in an empty cache under CacheQuotaDataLock, and writes the detached snapshot without holding that lock. The completion log reports the snapshot size. The test checks that concurrent logging completes during a blocked save and that both entries are persisted.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant LogQuotaData
  participant CacheQuotaDataLock
  participant SaveQuotaDataCache
  participant Database
  SaveQuotaDataCache->>CacheQuotaDataLock: Swap shared cache for empty map
  SaveQuotaDataCache->>Database: Persist detached snapshot
  LogQuotaData->>CacheQuotaDataLock: Merge entry into new cache
  LogQuotaData-->>SaveQuotaDataCache: Complete while database write continues
Loading

Suggested reviewers: calcium-ion

Merge Risk: Minimal · up to 6578d

Logging quota data no longer waits for the database write during a save, and entries logged during a save are kept for the next flush. No concrete merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: quota data writes no longer delay request completion. The PR swaps the pending quota-data map under CacheQuotaDataLock and writes the snapshot without holding that loc…
Linked Issues check Passed [#8536] The core coding requirement is that a completed request must not wait on a slow quota_data write. At the reviewed head, SaveQuotaDataCache (model/usedata.go) holds CacheQuotaDataLock only to s…
Out of Scope Changes check Passed The whole-PR diff against the merge base touches model/usedata.go (save locking and snapshot swap, plus a log line that now uses len(pending)) and model/usedata_flow_test.go (the regression test). Bot…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: quota data writes no longer delay request completion. The PR swaps the pending quota-data map under CacheQuotaDataLock and writes the snapshot without holding that lock, which matches the title's fix(dashboard) scope. The title is specific and uses a conventional commit prefix. It does not describe anything absent from the changeset.

Full details: Linked Issues check

Explanation

[#8536] The core coding requirement is that a completed request must not wait on a slow quota_data write. At the reviewed head, SaveQuotaDataCache (model/usedata.go) holds CacheQuotaDataLock only to swap CacheQuotaData for an empty map. It then writes the detached snapshot without that lock. LogQuotaData, which RecordConsumeLog calls on the request path, contends only for the brief swap. A new quotaDataSaveLock serializes periodic and shutdown saves, and it is not on the request path. The regression test TestLogQuotaDataDoesNotWaitForQuotaDataWrite (model/usedata_flow_test.go) covers the case where quota_data writes are slow. The issue's 'suggested direction' asks for a recomputation design from logs with a delayed dashboard. The PR does not implement that design. The issue presents it as guidance, not as a required acceptance criterion, and the PR description says it does not claim that design. The PR keeps the cache/upsert approach and meets the 'do not synchronously wait on the stats cache in the request path' and 'add a regression test' points. Residual gap: the issue asks that stats task failure not affect requests. The change does not alter that behavior, because LogQuotaData does not depend on DB write results. Evidence was taken from the PR diff of model/usedata.go and the summary of the test file. I did not run the tests.

Full details: Out of Scope Changes check

Explanation

The whole-PR diff against the merge base touches model/usedata.go (save locking and snapshot swap, plus a log line that now uses len(pending)) and model/usedata_flow_test.go (the regression test). Both changes serve the linked issue #8536 objective of keeping quota_data writes off the request completion path. The PR adds no SQL, schema, or migration changes. No unrelated changes were identified in the reviewed diff. The test file was reviewed through its summary only, not through its full diff.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit watched the cache unbind,
While records moved to stores.
New entries hopped into the map,
As saves went on their course.
Two tallies joined in one row,
Then carrots filled the burrows.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 60e59047-8824-4e49-be2f-05d4899c8fa4
Commits

Reviewing files that changed from the base of the PR and between 5911c8c and 6578dc6.

Files selected for processing: 2

  • model/usedata.go
  • model/usedata_flow_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

This branch has not been deployed

No deployments
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.

[Bug] 上游响应完成后,New-API 仍可能延迟关闭客户端连接

1 participant