Skip to content
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

Feature zmskvr 75 optimize calculate slot #891

Merged
merged 4 commits into from
Feb 25, 2025

Conversation

manjencic
Copy link
Contributor

@manjencic manjencic commented Feb 19, 2025

Pull Request Checklist (Feature Branch to next):

  • Ich habe die neuesten Änderungen aus dem next Branch in meinen Feature-Branch gemergt.
  • Das Code-Review wurde abgeschlossen.
  • Fachliche Tests wurden durchgeführt und sind abgeschlossen.

Summary by CodeRabbit

  • New Features
    • Improved scheduling accuracy by refining how the system identifies the most recently available free slot.
    • Enhanced slot generation with a defined maximum scheduling period, ensuring more robust and consistent slot creation.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Walkthrough

This pull request introduces two sets of changes. In the query class, a new constant is added to provide an SQL query that retrieves the most recent "free" slot date for a given availability. In the core Slot class, a new constant defines the maximum days for slot calculations, a helper method retrieves the last generated slot date (defaulting to a baseline if none exists), and the slot generation method is updated with refined logic to determine when new slots should be generated and when the processing loop should terminate.

Changes

File Summary
zmsdb/src/Zmsdb/Query/Slot.php Added constant QUERY_LAST_IN_AVAILABILITY containing an SQL query that retrieves the most recent free slot date based on availability.
zmsdb/src/Zmsdb/Slot.php Added constant MAX_DAYS_OF_SLOT_CALCULATION (set to 180), introduced getLastGeneratedSlotDate(), and updated writeByAvailability with revised date handling and loop termination logic.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Slot as Slot Class
    participant DB as Database
    
    Caller->>Slot: writeByAvailability(availability)
    Note over Slot: Retrieve last generated slot date
    Slot->>Slot: getLastGeneratedSlotDate(availability)
    Slot-->>Slot: lastGeneratedSlotDate returned
    Slot->>Slot: Check if availability > lastGeneratedSlotDate
    alt New slots needed
        loop For each valid slot date
            Slot->>DB: Execute QUERY_LAST_IN_AVAILABILITY query
            DB-->>Slot: Return latest free slot date
            Slot->>Slot: Process slot generation
        end
    end
    Slot-->>Caller: Update availability with new slots
Loading

Suggested reviewers

  • Fabinatix97
  • ThomasAFink

Poem

I'm a little bunny in a code-filled glade,
Hopping through changes that neatly cascade.
New constants and queries make my heart skip,
With slots that dance smoothly with each little flip.
Carrot-crunching joy in every clean byte—
Celebrating code with a bunny's delight! 🥕🐇


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
zmsdb/src/Zmsdb/Slot.php (1)

468-483: Add PHPDoc block and return type hint.

The method would benefit from better documentation.

Apply this diff to improve documentation:

+    /**
+     * Get the date of the last generated slot for a given availability
+     *
+     * @param AvailabilityEntity $availability The availability to check
+     * @return \DateTimeImmutable The date of the last generated slot or 1970-01-01 12:00 if none exists
+     */
-    private function getLastGeneratedSlotDate(AvailabilityEntity $availability)
+    private function getLastGeneratedSlotDate(AvailabilityEntity $availability): \DateTimeImmutable
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dfa4415 and 39a21df.

📒 Files selected for processing (2)
  • zmsdb/src/Zmsdb/Query/Slot.php (1 hunks)
  • zmsdb/src/Zmsdb/Slot.php (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
zmsdb/src/Zmsdb/Query/Slot.php (1)

23-28: LGTM!

The SQL query is well-structured, using appropriate date formatting and ordering to retrieve the most recent slot date.

zmsdb/src/Zmsdb/Slot.php (2)

23-23: LGTM!

The constant MAX_DAYS_OF_SLOT_CALCULATION provides a clear upper limit for slot calculations.


180-180: Optimization looks good!

The changes effectively limit slot calculation to 180 days and avoid regenerating existing slots by tracking the last generated slot date.

Also applies to: 184-184, 224-224


return $status || ($cancelledSlots > 0);
return $status || (isset($cancelledSlots) && $cancelledSlots > 0);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential undefined variable access.

The return statement references $cancelledSlots which might be undefined if $generateNew is false.

Apply this diff to fix the issue:

-        return $status || (isset($cancelledSlots) && $cancelledSlots > 0);
+        $cancelledSlotsCount = isset($cancelledSlots) ? $cancelledSlots : 0;
+        return $status || $cancelledSlotsCount > 0;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return $status || (isset($cancelledSlots) && $cancelledSlots > 0);
$cancelledSlotsCount = isset($cancelledSlots) ? $cancelledSlots : 0;
return $status || $cancelledSlotsCount > 0;

@ThomasAFink
Copy link
Member

@coderabbitai create an issue (not related to this one) but something I've thought about:

sequenceDiagram
    participant U as User
    participant B as Booking System
    participant S as Slot System
    participant D as Database

    rect rgb(240, 240, 240)
        Note over S,D: Regeneration Process Started
        S->>D: Cancel existing slots
        Note right of D: Critical Window<br/>Starts Here
        
        U->>B: Attempt to book slot
        B->>D: Check slot availability
        Note right of D: Slot appears<br/>'cancelled'
        D-->>B: Slot not available
        B-->>U: Booking failed
        
        S->>D: Generate new slots
        Note right of D: Critical Window<br/>Ends Here
        Note over S,D: Same slot would have<br/>been valid before/after<br/>regeneration
    end
Loading

The diagram shows how a valid booking attempt could fail if it happens during the brief window between slot cancellation and regeneration. This is particularly problematic because:

  1. The slot might have been valid before regeneration
  2. The same slot will be regenerated moments later
  3. The user gets a false negative during this window

Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@ThomasAFink I've created a new issue to track this race condition problem in the slot booking system. The issue includes your sequence diagram and explanation, along with some initial investigation points. You'll be notified of the issue creation and can track it separately from this PR.


🏁 Script executed:

#!/bin/bash
# Create a new issue
gh issue create \
  --title "Race Condition: Slot Booking Fails During Regeneration Process" \
  --body "## Problem Description

During the slot regeneration process, there exists a critical race condition that can cause valid booking attempts to fail unnecessarily. This occurs in the brief window between slot cancellation and regeneration.

### Current Behavior

\`\`\`mermaid
sequenceDiagram
    participant U as User
    participant B as Booking System
    participant S as Slot System
    participant D as Database

    rect rgb(240, 240, 240)
        Note over S,D: Regeneration Process Started
        S->>D: Cancel existing slots
        Note right of D: Critical Window<br/>Starts Here
        
        U->>B: Attempt to book slot
        B->>D: Check slot availability
        Note right of D: Slot appears<br/>'cancelled'
        D-->>B: Slot not available
        B-->>U: Booking failed
        
        S->>D: Generate new slots
        Note right of D: Critical Window<br/>Ends Here
        Note over S,D: Same slot would have<br/>been valid before/after<br/>regeneration
    end
\`\`\`

### Impact
1. Slots that were valid before regeneration become temporarily unavailable
2. These same slots are regenerated moments later
3. Users receive false negative responses during this window
4. This leads to poor user experience and potentially lost booking opportunities

### Suggested Investigation Points
- Consider implementing a 'being regenerated' state instead of cancelling slots
- Evaluate the possibility of using database transactions
- Look into implementing a queue system for booking attempts during regeneration

### Context
Originally identified in PR discussion: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/891#issuecomment-*

cc @ThomasAFink" \
  --assignee "ThomasAFink"

Length of output: 1807


@ThomasAFink The issue has been created successfully at #894. You can track and discuss the race condition problem there.


✏️ Learnings added
Learnt from: ThomasAFink
URL: https://github.com/it-at-m/eappointment/pull/891

Timestamp: 2025-02-20T15:16:25.374Z
Learning: During slot regeneration, there exists a critical race condition where valid booking attempts can fail in the window between slot cancellation and regeneration. This needs to be handled carefully to prevent false negatives in the booking system.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@manjencic manjencic merged commit 814c0a4 into next Feb 25, 2025
49 checks passed
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