Repository navigation
fix: chat user token quota #7814
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| # coding=utf-8 | ||
| from types import SimpleNamespace | ||
| from unittest.mock import Mock, patch | ||
|
|
||
| from django.test import SimpleTestCase | ||
|
|
||
| from chat.serializers.chat import ChatSerializers | ||
| from common.exception.app_exception import AppApiException | ||
| from system_manage.models.chat_user_token_quota import ChatUserTokenQuota, QuotaType | ||
|
|
||
|
|
||
| class ChatUserQuotaAvailabilityTests(SimpleTestCase): | ||
| def test_exhausted_periodic_quota_is_rejected_before_workflow_runs(self): | ||
| """配额已用尽时,对话在开始前就被拒绝,不会触发工作流生成内容。""" | ||
| exhausted = SimpleNamespace( | ||
| quota_type=QuotaType.PERIODIC, | ||
| token_limit=10, | ||
| used_tokens=10, | ||
| period_end=None, | ||
| check_and_reset=lambda: None, | ||
| ) | ||
|
|
||
| data = { | ||
| "chat_id": "0b1d5a02-6f5b-4d1e-9a4e-6a3c1a1a1a1a", | ||
| "chat_user_id": "user-1", | ||
| "chat_user_type": "CHAT_USER", | ||
| "application_id": "0b1d5a02-6f5b-4d1e-9a4e-6a3c1a1a1a1b", | ||
| "debug": False, | ||
| "ip_address": "127.0.0.1", | ||
| "source": {"type": "ONLINE"}, | ||
| } | ||
| instance = {"message": {"content": "hi"}, "stream": False} | ||
|
|
||
| with ( | ||
| patch.object(ChatUserTokenQuota.objects, "filter", return_value=SimpleNamespace(first=lambda: exhausted)), | ||
| patch.object(ChatSerializers, "get_application", return_value=object()), | ||
| patch.object(ChatSerializers, "is_valid_chat"), | ||
| patch.object(ChatSerializers, "is_valid_intraday_access_num"), | ||
| patch.object(ChatSerializers, "chat_work_flow") as workflow, | ||
| ): | ||
| serializer = ChatSerializers(data=data) | ||
| with self.assertRaises(AppApiException): | ||
| serializer.chat(instance) | ||
| workflow.assert_not_called() | ||
|
|
||
| def test_available_quota_lets_workflow_run(self): | ||
| """配额未用尽时,前置校验不拦截,正常进入工作流。""" | ||
| available = SimpleNamespace( | ||
| quota_type=QuotaType.PERIODIC, | ||
| token_limit=10, | ||
| used_tokens=1, | ||
| period_end=None, | ||
| check_and_reset=lambda: None, | ||
| ) | ||
|
|
||
| data = { | ||
| "chat_id": "0b1d5a02-6f5b-4d1e-9a4e-6a3c1a1a1a1a", | ||
| "chat_user_id": "user-1", | ||
| "chat_user_type": "CHAT_USER", | ||
| "application_id": "0b1d5a02-6f5b-4d1e-9a4e-6a3c1a1a1a1b", | ||
| "debug": False, | ||
| "ip_address": "127.0.0.1", | ||
| "source": {"type": "ONLINE"}, | ||
| } | ||
| instance = {"message": {"content": "hi"}, "stream": False} | ||
|
|
||
| with ( | ||
| patch.object(ChatUserTokenQuota.objects, "filter", return_value=SimpleNamespace(first=lambda: available)), | ||
| patch.object(ChatSerializers, "get_application", return_value=object()), | ||
| patch.object(ChatSerializers, "is_valid_chat"), | ||
| patch.object(ChatSerializers, "is_valid_intraday_access_num"), | ||
| patch.object(ChatSerializers, "chat_work_flow", return_value="ok") as workflow, | ||
| ): | ||
| serializer = ChatSerializers(data=data) | ||
| self.assertEqual(serializer.chat(instance), "ok") | ||
| workflow.assert_called_once() | ||
|
|
||
| def test_check_available_over_limit_raises(self): | ||
| """预校验:当前周期已用满则抛异常。""" | ||
| quota = SimpleNamespace( | ||
| quota_type=QuotaType.PERIODIC, | ||
| token_limit=10, | ||
| used_tokens=10, | ||
| period_end=None, | ||
| check_and_reset=lambda: None, | ||
| ) | ||
|
|
||
| with patch.object(ChatUserTokenQuota.objects, "filter", return_value=SimpleNamespace(first=lambda: quota)): | ||
| with self.assertRaises(AppApiException): | ||
| ChatUserTokenQuota.check_available("user-1") | ||
|
|
||
| def test_check_available_within_limit_passes(self): | ||
| """预校验:未用满时不拦截。""" | ||
| quota = SimpleNamespace( | ||
| quota_type=QuotaType.PERIODIC, | ||
| token_limit=10, | ||
| used_tokens=1, | ||
| period_end=None, | ||
| check_and_reset=lambda: None, | ||
| ) | ||
|
|
||
| with patch.object(ChatUserTokenQuota.objects, "filter", return_value=SimpleNamespace(first=lambda: quota)): | ||
| ChatUserTokenQuota.check_available("user-1") | ||
|
|
||
| def test_recording_over_limit_does_not_raise(self): | ||
| """记录实际用量时即使超出上限也不抛异常,并如实累计,保证对话记录能落库。""" | ||
| quota = SimpleNamespace( | ||
| quota_type=QuotaType.PERIODIC, | ||
| token_limit=10, | ||
| used_tokens=9, | ||
| total_tokens=0, | ||
| period_end=None, | ||
| check_and_reset=lambda: None, | ||
| save=Mock(), | ||
| ) | ||
|
|
||
| with patch.object(ChatUserTokenQuota.objects, "filter", return_value=SimpleNamespace(first=lambda: quota)): | ||
| ChatUserTokenQuota.consume("user-1", 5) | ||
|
|
||
| self.assertEqual(quota.used_tokens, 14) | ||
| self.assertEqual(quota.total_tokens, 5) | ||
| quota.save.assert_called_once_with(update_fields=["used_tokens", "total_tokens"]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,6 +12,7 @@ | |
| from common.mixins.app_model_mixin import AppModelMixin | ||
| from dateutil.relativedelta import relativedelta | ||
| from django.utils import timezone | ||
| from django.utils.translation import gettext_lazy as _ | ||
|
|
||
|
|
||
| class QuotaType(models.TextChoices): | ||
|
|
@@ -68,26 +69,35 @@ def check_and_reset(self): | |
|
|
||
| @classmethod | ||
| def consume(cls, user_id, amount): | ||
| """记录本次实际 Token 消耗:累计 used_tokens/total_tokens。 | ||
| 即使超出上限也不抛异常,配额拦截交给对话前的 check_available,保证对话记录能正常落库。 | ||
| """ | ||
| if amount <= 0: | ||
| return | ||
| quota = cls.objects.filter(user_id=user_id).first() | ||
| if quota is None: | ||
| # 所有消费用户都创建统计行,匿名用户也累计使用量 | ||
| quota, _ = cls.objects.get_or_create( | ||
| quota, _created = cls.objects.get_or_create( | ||
| user_id=user_id, | ||
| defaults={"quota_type": QuotaType.UNLIMITED}, | ||
| ) | ||
| quota.check_and_reset() | ||
| # 记录实际使用量:即使超出上限也如实累计,拦截交给下次对话前的 check_available | ||
| quota.used_tokens += amount | ||
| quota.total_tokens += amount | ||
| quota.save(update_fields=["used_tokens", "total_tokens"]) | ||
|
|
||
| @classmethod | ||
| def check_available(cls, user_id): | ||
| """对话前预校验:当前周期配额已用满或超限则抛 AppApiException,不写库。""" | ||
| quota = cls.objects.filter(user_id=user_id).first() | ||
| if quota is None: | ||
| return | ||
| if quota.quota_type == QuotaType.UNLIMITED: | ||
| # 不限额:只累计使用量,不校验上限 | ||
| quota.used_tokens += amount | ||
| quota.total_tokens += amount | ||
| quota.save(update_fields=["used_tokens", "total_tokens"]) | ||
| return | ||
| quota.check_and_reset() | ||
| if quota.used_tokens + amount > quota.token_limit: | ||
| if quota.token_limit is not None and quota.used_tokens >= quota.token_limit: | ||
| raise AppApiException( | ||
| 500, _("The token quota for the current period has been exhausted. Please contact the administrator.") | ||
| 500, | ||
| _("The token quota for the current period has been exhausted. Please contact the administrator."), | ||
| ) | ||
| quota.used_tokens += amount | ||
| quota.total_tokens += amount | ||
| quota.save(update_fields=["used_tokens", "total_tokens"]) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here is an analysis of the code changes, highlighting potential issues and optimization suggestions: 1. Logic Change & Behavioral Shift
2. Potential Race Conditions (Concurrency)
3. Redundant Database Queries
4. Error Handling in
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here is the review of the provided code diff, covering potential issues, logic errors, and optimization suggestions.
1. Critical Logic Bug in Error Handling (Status Mismatch)
Location: In the new
exceptblock withinon_complete:Issue: You are sending a Failure content (
FailureContent) but setting the status toStatus.SUCCESS.FailureContentis likely paired with a failure status (or at least a consistent status). If this block is meant to handle exceptions during post-processing, the status should reflect the failure (e.g.,Status.FAILURE).Suggestion: Check what
FailureContentexpects for status. Usually, it should be a failure state.2. Resource Leakage / Duplicate Notification
Location: Inside the
try...exceptblock.Issue: If an exception occurs after the database updates (
update_chat_record, etc.) but beforeresult_queue.put(("done", None)), theexceptblock triggers.try/exceptblock, the code unconditionally executes:exceptblock ran), the system still tells the client "Done" viaproduce_done. The client might receive both the error message and then a "done" signal, depending on how queues are consumed.exceptblock sends a failure signal to the message queue, doesproduce_doneoverwrite it or send another message? Typically,produce_donesignifies normal termination. If an error occurred, you should probablyraisethe exception after logging/sending error info, or structure the flow soproduce_doneis only called on success.Suggestion: If the exception is handled by sending an error message, you should stop execution. Add a
returnstatement at the end of theexceptblock or re-raise the error.(Note: If
on_completeis a callback thread function, re-raising might kill the thread silently. Ensure the error propagation strategy matches your architecture.)3. Security & Validation: Token Quota Check
Location:
ChatUserTokenQuota.check_available(self.data.get("chat_user_id"))inchat(self, ...)method.Issue:
self.data.get("chat_user_id")could returnNoneif the key is missing. Depending oncheck_availableimplementation, this might throw anAttributeError(if it tries.idor similar on None) or silently pass (if it treats None as valid).is_valid_chat()before checking the quota. Ifis_valid_chatvalidates user existence, fetchingself.data["chat_user_id"]directly (assuming it exists) or retrieving the validated user object would be safer than relying on dictionary access which might be untrusted input.Suggestion:
4. Performance: N+1 Query / Redundant DB Fetch
Location:
on_completefunction.Issue:
You fetch the
ChatRecordfrom the database again insideon_complete, even though this workflow likely started with this record.on_completeis triggered asynchronously or in a separate context, this is necessary.wf_manage.start_time. Ifwf_manageholds references to original records, consider passing the old details or record ID more efficiently to avoid a fresh DB round-trip in the callback path, which is critical for latency in high-throughput systems.Model.objects.filter(id=id).first()is fine, but ifchat_record_idis a primary key, ensure you're not bypassing caching layers or using inefficient ORMs.5. Data Consistency: Message Deduplication
Location:
Issue:
chat_record.messagesor the newmessagesdoes not have an"id"key,m.get("id")returnsNone.Nonein the dictionary comprehension, effectively discarding all but one random message that lacks an ID.Suggestion: Verify that all messages always have unique IDs. If not, fallback to UUID generation for missing ones to prevent data loss.
6. Code Style & Readability
except Exception as eis very broad. It catches things likeCtrl+Csignals (though less likely in threads) orSystemExit. Consider catching specific exceptions expected from DB operations or serialization errors.Status.SUCCESSinside aFailureContentcontainer is highly suspicious. This is a code smell indicating a copy-paste error.Summary of Recommended Actions
Status.SUCCESSto appropriate failure status in theexceptblock'sFailureContent.produce_doneisn't sent after an unrecovered error inon_complete, or clarify the protocol.NoneinChatUserTokenQuota.check_available.