Skip to content

[ENG-401] fix: token queue should respect sub queues while calling serve next - #3708

Open
nandkishorr wants to merge 11 commits into
developfrom
ENG-401-token-queue-should-respect-sub-queues-while-calling-serve-next
Open

[ENG-401] fix: token queue should respect sub queues while calling serve next#3708
nandkishorr wants to merge 11 commits into
developfrom
ENG-401-token-queue-should-respect-sub-queues-while-calling-serve-next

Conversation

@nandkishorr

@nandkishorr nandkishorr commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Proposed Changes

  • Added proper token calling in the sub_queue
  • Added proper validation and current token clearing on token update
  • Testcases pending !

Associated Issue

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

Only PR's with test cases included and passing lint and test pipelines will be reviewed

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Summary by CodeRabbit

  • New Features

    • Added a new set-next endpoint for sub-queues to atomically pick the earliest available token, set it as the current token, and transition it into progress.
  • Bug Fixes

    • Strengthened token update validation to block sub-queue changes when a current token exists and to require “set-next” when status is IN_PROGRESS.
    • Improved compatibility checks and current-token clearing when moving away from IN_PROGRESS.
    • Tightened next-token selection to only consider unassigned tokens and refined persistence to update only required fields.
  • Tests

    • Updated token API tests to use CREATED payloads and expect CREATED responses.

@nandkishorr nandkishorr self-assigned this Jul 10, 2026
@nandkishorr
nandkishorr requested a review from a team as a code owner July 10, 2026 10:11
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 40774899-0775-405b-8058-05c8d8dd5002

📥 Commits

Reviewing files that changed from the base of the PR and between 421ab2a and d506c2c.

📒 Files selected for processing (3)
  • care/emr/api/viewsets/scheduling/token.py
  • care/emr/api/viewsets/scheduling/token_queue.py
  • care/emr/api/viewsets/scheduling/token_sub_queue.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • care/emr/api/viewsets/scheduling/token_queue.py
  • care/emr/api/viewsets/scheduling/token_sub_queue.py
  • care/emr/api/viewsets/scheduling/token.py

📝 Walkthrough

Walkthrough

Token and sub-queue scheduling now enforce stricter assignment and status rules. A new sub-queue endpoint advances CREATED tokens atomically, while queue selection excludes already-assigned tokens. Update tests now use CREATED.

Changes

Token queue consistency

Layer / File(s) Summary
Token validation and state enforcement
care/emr/api/viewsets/scheduling/token.py, care/emr/tests/test_token_api.py
Token updates validate sub-queue conflicts, restrict invalid IN_PROGRESS assignments, clear current-token references, require CREATED for set_next, and update related test expectations.
Sub-queue next-token transition
care/emr/api/viewsets/scheduling/token_sub_queue.py
Adds a locked, atomic endpoint that selects a CREATED token, sets the sub-queue’s current token, assigns the token, and transitions it to IN_PROGRESS.
Unassigned next-token selection
care/emr/api/viewsets/scheduling/token_queue.py
Next-token selection now considers only CREATED tokens without a sub-queue and raises when none are found.

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

Possibly related PRs

Suggested labels: waiting-for-review, Tests

Suggested reviewers: praffq

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: token queue serving now respects sub-queues.
Description check ✅ Passed The description covers Proposed Changes, Associated Issue, and Merge Checklist, with only minor gaps like the missing issue link and pending tests.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ENG-401-token-queue-should-respect-sub-queues-while-calling-serve-next

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

Comment @coderabbitai help to get the list of available commands.

@nandkishorr nandkishorr changed the title [ENG-401] fix : token queue should respect sub queues while calling serve next [ENG-401] fix: token queue should respect sub queues while calling serve next Jul 10, 2026
@greptile-apps

greptile-apps Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes sub-queue token calling by routing set_next through a proper sub-queue lock, filtering set_next_token_to_subqueue to only unassigned tokens, and blocking direct IN_PROGRESS transitions via the update endpoint. A new set_next_token endpoint is added to TokenSubQueueViewSet so a sub-queue can auto-advance its own CREATED tokens.

  • token.pyset_next now acquires sub_queue:next_token:{id} lock and sets obj.sub_queue; validate_data blocks update-to-IN_PROGRESS when sub_queue is provided; perform_update clears current_token on status change out of IN_PROGRESS or sub-queue swap.
  • token_queue.pyset_next_token_to_subqueue now filters sub_queue__isnull=True so it only picks tokens not yet claimed by any sub-queue; save() calls converted to update_fields.
  • token_sub_queue.py — new set_next_token action picks the earliest CREATED token already assigned to the sub-queue, sets it IN_PROGRESS, and records it as current_token under the sub_queue:next_token:{id} advisory lock.

Confidence Score: 3/5

The update endpoint now incorrectly rejects field edits on already-IN_PROGRESS tokens when the payload includes the current sub_queue and status, and the new set_next/set_next_token endpoints read their key objects outside the lock without re-fetching inside, leaving concurrent overwrites of current_token possible.

The validate_data guard introduced in this PR blocks any update to an already-IN_PROGRESS token that includes both sub_queue and status=IN_PROGRESS in the payload — a regression that will affect clients sending full object representations. Additionally, both set_next (token.py) and set_next_token (token_sub_queue.py) snapshot their objects before acquiring the advisory lock, so an existing current_token on the sub_queue can be silently overwritten.

care/emr/api/viewsets/scheduling/token.py (validate_data guard, set_next snapshot) and care/emr/api/viewsets/scheduling/token_sub_queue.py (set_next_token snapshot and missing current_token guard)

Important Files Changed

Filename Overview
care/emr/api/viewsets/scheduling/token.py validate_data now blocks all updates with sub_queue+IN_PROGRESS regardless of whether the token is already IN_PROGRESS (regression); set_next fetches both obj and sub_queue outside the lock with no re-fetch or current_token guard inside the transaction
care/emr/api/viewsets/scheduling/token_sub_queue.py New set_next_token endpoint added with correct lock key matching token.set_next, but obj is fetched before the lock with no re-fetch or select_for_update inside, and no guard prevents overwriting an existing current_token
care/emr/api/viewsets/scheduling/token_queue.py set_next_token_to_subqueue now correctly filters sub_queue__isnull=True and uses update_fields; exists()+first() double-query cleaned up; lock key still differs from set_next_token, allowing cross-endpoint races
care/emr/tests/test_token_api.py Existing tests updated to send CREATED (not IN_PROGRESS) in update payloads; no new test coverage for set_next_token endpoint or set_next status-guard behaviour

Reviews (9): Last reviewed commit: "Merge branch 'ENG-401-token-queue-should..." | Re-trigger Greptile

Comment thread care/emr/api/viewsets/scheduling/token.py
Comment thread care/emr/api/viewsets/scheduling/token_queue.py Outdated
Comment thread care/emr/api/viewsets/scheduling/token.py Outdated
@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 45.94595% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.73%. Comparing base (2f438e5) to head (bea5877).

Files with missing lines Patch % Lines
...are/emr/api/viewsets/scheduling/token_sub_queue.py 35.00% 13 Missing ⚠️
care/emr/api/viewsets/scheduling/token.py 53.33% 4 Missing and 3 partials ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #3708      +/-   ##
===========================================
- Coverage    79.79%   79.73%   -0.07%     
===========================================
  Files          479      479              
  Lines        23116    23140      +24     
  Branches      2409     2412       +3     
===========================================
+ Hits         18446    18451       +5     
- Misses        4066     4082      +16     
- Partials       604      607       +3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
care/emr/tests/test_token_api.py (1)

278-292: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Missing test coverage for new sub-queue validation and clearing behavior.

The status change from IN_PROGRESS to CREATED is correct — the new perform_update logic (lines 113-120 in token.py) would block assigning a sub_queue while transitioning to IN_PROGRESS. However, the new behavior itself is entirely untested:

  1. Sub_queue change during IN_PROGRESS is blocked — no test verifies that updating a token to IN_PROGRESS while changing its sub_queue returns 400 with "Use set_next endpoint to change the sub queue of a token".
  2. Current_token conflict on IN_PROGRESS with same sub_queue — no test verifies that setting IN_PROGRESS with an existing sub_queue that has a different current_token returns 400 with "Sub Queue already has a current token".
  3. Current_token clearing on status transition away from IN_PROGRESS — no test verifies that updating a token from IN_PROGRESS to FULFILLED/CANCELLED clears the sub_queue's current_token.
  4. Next-token prioritization (token_queue.py lines 235-238) — no test verifies that set_next_token_to_subqueue prefers tokens already assigned to the requested sub_queue over unassigned waiting tokens.

The existing tests (test_update_token_with_existing_current_token_in_subqueue, test_update_token_with_current_token_as_null_in_subqueue) cover the first validate_data block but none exercise the IN_PROGRESS-gated paths.

Would you like me to generate the missing test cases?

Also applies to: 314-328

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/tests/test_token_api.py` around lines 278 - 292, The token API tests
lack coverage for the new sub-queue validation and current-token lifecycle
behavior. Add focused tests around the existing update-token test cases and
`perform_update` covering: rejecting an IN_PROGRESS update that changes
sub_queue with the specified 400 message; rejecting IN_PROGRESS when the
sub_queue has a different current_token; clearing current_token when
transitioning from IN_PROGRESS to FULFILLED or CANCELLED; and verifying
`set_next_token_to_subqueue` prioritizes tokens already assigned to the
requested sub_queue over unassigned waiting tokens.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@care/emr/tests/test_token_api.py`:
- Around line 278-292: The token API tests lack coverage for the new sub-queue
validation and current-token lifecycle behavior. Add focused tests around the
existing update-token test cases and `perform_update` covering: rejecting an
IN_PROGRESS update that changes sub_queue with the specified 400 message;
rejecting IN_PROGRESS when the sub_queue has a different current_token; clearing
current_token when transitioning from IN_PROGRESS to FULFILLED or CANCELLED; and
verifying `set_next_token_to_subqueue` prioritizes tokens already assigned to
the requested sub_queue over unassigned waiting tokens.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4955bd10-01bf-440e-9009-38445ca4c38a

📥 Commits

Reviewing files that changed from the base of the PR and between e26a3c6 and a7ace39.

📒 Files selected for processing (3)
  • care/emr/api/viewsets/scheduling/token.py
  • care/emr/api/viewsets/scheduling/token_queue.py
  • care/emr/tests/test_token_api.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
care/emr/api/viewsets/scheduling/token.py (2)

107-115: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Add the resource guard here too. This branch only catches sub-queue swaps, so a token with no existing sub-queue can still attach one from the wrong resource. Match the create path and reject instance.sub_queue.resource != obj.queue.resource before the current transition check.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/api/viewsets/scheduling/token.py` around lines 107 - 115, Update the
validation logic containing the existing sub-queue transition check to also
guard the target queue’s resource: reject when obj.sub_queue exists and
obj.sub_queue.resource differs from obj.queue.resource, before evaluating the
current instance transition condition. Keep the existing mismatch check for
sub-queue swaps so both creation-like attachments and transitions enforce
resource consistency.

201-213: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Lock the sub-queue row in set_next. transaction.atomic() doesn’t serialize concurrent calls here, so two requests can both pass the current_token check and one will quietly overwrite the other. Use select_for_update() on TokenSubQueue like the create path does.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/api/viewsets/scheduling/token.py` around lines 201 - 213, Update
set_next to retrieve the TokenSubQueue through select_for_update() before
checking or assigning current_token, matching the locking approach used by the
create path; keep the lookup inside the existing transaction.atomic() block so
concurrent calls serialize safely.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@care/emr/api/viewsets/scheduling/token.py`:
- Around line 107-115: Update the validation logic containing the existing
sub-queue transition check to also guard the target queue’s resource: reject
when obj.sub_queue exists and obj.sub_queue.resource differs from
obj.queue.resource, before evaluating the current instance transition condition.
Keep the existing mismatch check for sub-queue swaps so both creation-like
attachments and transitions enforce resource consistency.
- Around line 201-213: Update set_next to retrieve the TokenSubQueue through
select_for_update() before checking or assigning current_token, matching the
locking approach used by the create path; keep the lookup inside the existing
transaction.atomic() block so concurrent calls serialize safely.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: cedfac83-4a0d-49cd-8098-4162ab0c84d8

📥 Commits

Reviewing files that changed from the base of the PR and between a7ace39 and 140b0b1.

📒 Files selected for processing (1)
  • care/emr/api/viewsets/scheduling/token.py

Comment thread care/emr/api/viewsets/scheduling/token.py Outdated
@nandkishorr
nandkishorr force-pushed the ENG-401-token-queue-should-respect-sub-queues-while-calling-serve-next branch from d82319b to 5ada8a3 Compare July 10, 2026 13:41
Comment thread care/emr/api/viewsets/scheduling/token.py
@nandkishorr
nandkishorr force-pushed the ENG-401-token-queue-should-respect-sub-queues-while-calling-serve-next branch from 5ada8a3 to b21fa4a Compare July 10, 2026 13:47
Comment thread care/emr/api/viewsets/scheduling/token.py Outdated
Comment thread care/emr/api/viewsets/scheduling/token_sub_queue.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
care/emr/api/viewsets/scheduling/token.py (3)

199-200: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Error message doesn't match the actual condition.

The check rejects any non-CREATED status (FULFILLED, CANCELLED, ENTERED_IN_ERROR), but the message says "Token in serving state cannot be set next," implying only IN_PROGRESS is rejected.

✏️ Proposed fix
-        raise ValidationError("Token in serving state cannot be set next")
+        raise ValidationError("Token must be in CREATED state to set next")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/api/viewsets/scheduling/token.py` around lines 199 - 200, Update the
validation in the token status transition logic to use an error message that
accurately describes rejection of every status other than CREATED, rather than
referring only to the serving state. Keep the existing condition and
ValidationError behavior unchanged.

196-214: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Missing lock in set_next allows concurrent races on sub_queue.current_token.

The sibling endpoints token_queue.py:set_next_token_to_subqueue and token_sub_queue.py:set_next_token both wrap their current-token updates in Lock(...), but set_next only uses transaction.atomic(). Two concurrent calls setting different tokens as next for the same sub-queue will both succeed, with the last sub_queue.save() winning — the losing token is silently transitioned to IN_PROGRESS without being the current_token. The status check on line 199 is also outside any lock, creating a TOCTOU window.

🔒 Proposed fix: add lock and move status check inside it
     `@action`(detail=True, methods=["POST"])
     def set_next(self, request, *args, **kwargs):
         obj = self.get_object()
-        if obj.status != TokenStatusOptions.CREATED.value:
-            raise ValidationError("Token in serving state cannot be set next")
         request_obj = SetCurrentTokenRequest(**request.data)
         queue = obj.queue
         self.authorize_update(None, obj)
-        with transaction.atomic():
+        sub_queue = get_object_or_404(
+            TokenSubQueue,
+            external_id=request_obj.sub_queue,
+            resource=queue.resource,
+        )
+        with Lock(f"sub_queue:current_token:{sub_queue.id}"), transaction.atomic():
+            obj.refresh_from_db()
+            if obj.status != TokenStatusOptions.CREATED.value:
+                raise ValidationError("Token must be in CREATED state to set next")
             sub_queue = get_object_or_404(
                 TokenSubQueue,
                 external_id=request_obj.sub_queue,
                 resource=queue.resource,
             )
             sub_queue.current_token = obj
-            sub_queue.save()
+            sub_queue.save(update_fields=["current_token", "modified_date"])
             obj.status = TokenStatusOptions.IN_PROGRESS.value
             obj.sub_queue = sub_queue
-            obj.save()
+            obj.save(update_fields=["status", "sub_queue", "modified_date"])
         return Response(self.get_retrieve_pydantic_model().serialize(obj).to_json())
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/api/viewsets/scheduling/token.py` around lines 196 - 214, Update
set_next to wrap the transaction in the same Lock(...) mechanism used by
token_queue.py:set_next_token_to_subqueue and token_sub_queue.py:set_next_token,
locking the target sub_queue before modifying it. Move the obj.status validation
inside the lock/transaction so the check and current_token update are atomic,
preventing concurrent requests from transitioning a losing token to IN_PROGRESS.

84-93: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Compare sub-queue objects consistently instance.sub_queue is a TokenSubQueue object here, so comparing it to model_obj.sub_queue.external_id will always trip the "Sub Queue already has a current token" guard on unchanged updates. Compare against model_obj.sub_queue (or instance.sub_queue.external_id) instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/api/viewsets/scheduling/token.py` around lines 84 - 93, Update the
sub-queue comparison in the token validation logic to compare like-for-like
values: use model_obj.sub_queue against the TokenSubQueue object in
instance.sub_queue, or compare both external IDs. Preserve the existing
existing_current check and ValidationError behavior for genuinely different
sub-queues.
🧹 Nitpick comments (2)
care/emr/api/viewsets/scheduling/token_queue.py (1)

240-244: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer save(update_fields=[...]) over bare save().

Same pattern as the other set-next endpoints — sub_queue.save() and next_token.save() write all fields. See consolidated comment.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/api/viewsets/scheduling/token_queue.py` around lines 240 - 244,
Update the set-next flow around sub_queue.current_token and next_token to use
save(update_fields=[...]) for both sub_queue and next_token, listing only the
fields modified immediately before each save. Preserve the existing assignment
and status/sub-queue updates.
care/emr/api/viewsets/scheduling/token.py (1)

210-214: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Bare save() in all three set-next endpoints should use update_fields. The shared root cause is that each set-next endpoint calls save() without restricting fields, while perform_update in token.py already demonstrates the save(update_fields=[...]) pattern. This risks overwriting concurrent modifications to unrelated fields.

  • care/emr/api/viewsets/scheduling/token.py#L210-L214: sub_queue.save(update_fields=["current_token", "modified_date"]) and obj.save(update_fields=["status", "sub_queue", "modified_date"])
  • care/emr/api/viewsets/scheduling/token_sub_queue.py#L144-L148: obj.save(update_fields=["current_token", "modified_date"]) and next_token.save(update_fields=["status", "sub_queue", "modified_date"])
  • care/emr/api/viewsets/scheduling/token_queue.py#L240-L244: sub_queue.save(update_fields=["current_token", "modified_date"]) and next_token.save(update_fields=["status", "sub_queue", "modified_date"])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@care/emr/api/viewsets/scheduling/token.py` around lines 210 - 214, Replace
the unrestricted saves in the set-next endpoints with targeted update_fields
saves: in care/emr/api/viewsets/scheduling/token.py lines 210-214, update
sub_queue.save to persist current_token and modified_date, and obj.save to
persist status, sub_queue, and modified_date; in
care/emr/api/viewsets/scheduling/token_sub_queue.py lines 144-148, update
obj.save to persist current_token and modified_date, and next_token.save to
persist status, sub_queue, and modified_date. Also apply the same targeted
fields in the set-next flow of care/emr/api/viewsets/scheduling/token_queue.py
lines 240-244 for sub_queue and next_token.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@care/emr/api/viewsets/scheduling/token.py`:
- Around line 199-200: Update the validation in the token status transition
logic to use an error message that accurately describes rejection of every
status other than CREATED, rather than referring only to the serving state. Keep
the existing condition and ValidationError behavior unchanged.
- Around line 196-214: Update set_next to wrap the transaction in the same
Lock(...) mechanism used by token_queue.py:set_next_token_to_subqueue and
token_sub_queue.py:set_next_token, locking the target sub_queue before modifying
it. Move the obj.status validation inside the lock/transaction so the check and
current_token update are atomic, preventing concurrent requests from
transitioning a losing token to IN_PROGRESS.
- Around line 84-93: Update the sub-queue comparison in the token validation
logic to compare like-for-like values: use model_obj.sub_queue against the
TokenSubQueue object in instance.sub_queue, or compare both external IDs.
Preserve the existing existing_current check and ValidationError behavior for
genuinely different sub-queues.

---

Nitpick comments:
In `@care/emr/api/viewsets/scheduling/token_queue.py`:
- Around line 240-244: Update the set-next flow around sub_queue.current_token
and next_token to use save(update_fields=[...]) for both sub_queue and
next_token, listing only the fields modified immediately before each save.
Preserve the existing assignment and status/sub-queue updates.

In `@care/emr/api/viewsets/scheduling/token.py`:
- Around line 210-214: Replace the unrestricted saves in the set-next endpoints
with targeted update_fields saves: in care/emr/api/viewsets/scheduling/token.py
lines 210-214, update sub_queue.save to persist current_token and modified_date,
and obj.save to persist status, sub_queue, and modified_date; in
care/emr/api/viewsets/scheduling/token_sub_queue.py lines 144-148, update
obj.save to persist current_token and modified_date, and next_token.save to
persist status, sub_queue, and modified_date. Also apply the same targeted
fields in the set-next flow of care/emr/api/viewsets/scheduling/token_queue.py
lines 240-244 for sub_queue and next_token.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 070bc2bb-0051-4f16-9416-4db03d8d3794

📥 Commits

Reviewing files that changed from the base of the PR and between d82319b and 421ab2a.

📒 Files selected for processing (4)
  • care/emr/api/viewsets/scheduling/token.py
  • care/emr/api/viewsets/scheduling/token_queue.py
  • care/emr/api/viewsets/scheduling/token_sub_queue.py
  • care/emr/tests/test_token_api.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • care/emr/tests/test_token_api.py

Comment thread care/emr/api/viewsets/scheduling/token_sub_queue.py Outdated
Comment thread care/emr/api/viewsets/scheduling/token_sub_queue.py
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.

1 participant