Skip to content

Fix build activation race condition#9952

Merged
Meldiron merged 22 commits into1.7.xfrom
fix-build-activation-race-condition
Jul 9, 2025
Merged

Fix build activation race condition#9952
Meldiron merged 22 commits into1.7.xfrom
fix-build-activation-race-condition

Conversation

@vermakhushboo
Copy link
Copy Markdown
Contributor

@vermakhushboo vermakhushboo commented Jun 2, 2025

…an active deployment

What does this PR do?

Don't auto-activate deployment which started earlier & ended later than the current active deployment

Test Plan

Need to test on stage

Related PRs and Issues

  • (Related PR or issue)

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

@vermakhushboo vermakhushboo requested a review from Meldiron June 2, 2025 12:25
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 2, 2025

📝 Walkthrough
## Walkthrough

The changes refactor update operations in the `buildDeployment` method to use minimal `Document` instances containing only updated fields instead of modifying entire resource or rule documents. This applies to updates of the resource's `latestDeploymentStatus`, adapter and fallback files, and platform rules during deployment status transitions. A new auto-activation logic prevents activating an older deployment over a newer one by comparing `buildStartedAt` timestamps before proceeding. When auto-activation occurs, the resource and matching platform rules are updated with minimal documents reflecting the new deployment details. Additionally, updates to VCS branch rules now use minimal documents for deployment ID changes. The Docker image tag for the `appwrite-console` service is updated from `6.1.2` to `6.1.12`.

## Possibly related PRs

- appwrite/appwrite#9902: Refactors deployment status updates and auto-activation logic to use minimal Document updates and standardizes branch-specific rule handling, closely related to deployment rule update logic changes in `buildDeployment`.
- appwrite/appwrite#9863: Modifies `Builds.php` to inject and use a plan array for configurable deployment and build size limits, related by touching the same file and deployment update logic but focusing on size configuration rather than update handling.

## Suggested reviewers

- christyjacob4

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd63f0c and 26496e6.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: scan-pr / osv-scan
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Jun 2, 2025

Security Scan Results for PR

Docker Image Scan Results

Package Version Vulnerability Severity
binutils 2.42-r0 CVE-2025-0840 HIGH
libexpat 2.6.4-r0 CVE-2024-8176 HIGH
libxml2 2.12.7-r0 CVE-2024-56171 HIGH
libxml2 2.12.7-r0 CVE-2025-24928 HIGH
libxml2 2.12.7-r0 CVE-2025-27113 HIGH
libxml2 2.12.7-r0 CVE-2025-32414 HIGH
libxml2 2.12.7-r0 CVE-2025-32415 HIGH
pyc 3.12.9-r0 CVE-2024-12718 HIGH
pyc 3.12.9-r0 CVE-2025-4138 HIGH
pyc 3.12.9-r0 CVE-2025-4330 HIGH
pyc 3.12.9-r0 CVE-2025-4517 HIGH
python3 3.12.9-r0 CVE-2024-12718 HIGH
python3 3.12.9-r0 CVE-2025-4138 HIGH
python3 3.12.9-r0 CVE-2025-4330 HIGH
python3 3.12.9-r0 CVE-2025-4517 HIGH
python3-pyc 3.12.9-r0 CVE-2024-12718 HIGH
python3-pyc 3.12.9-r0 CVE-2025-4138 HIGH
python3-pyc 3.12.9-r0 CVE-2025-4330 HIGH
python3-pyc 3.12.9-r0 CVE-2025-4517 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2024-12718 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2025-4138 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2025-4330 HIGH
python3-pycache-pyc0 3.12.9-r0 CVE-2025-4517 HIGH
sqlite-libs 3.45.3-r1 CVE-2025-29087 HIGH
xz 5.6.2-r0 CVE-2025-31115 HIGH
xz-libs 5.6.2-r0 CVE-2025-31115 HIGH
golang.org/x/crypto v0.31.0 CVE-2025-22869 HIGH

Source Code Scan Results

🎉 No vulnerabilities found!

Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1075-1088: Good implementation with room for improvement in timestamp handling.

The logic correctly prevents auto-activation of older deployments, which addresses the PR objective well. However, the string comparison of timestamps could be more robust.

Consider using proper date comparison instead of string comparison for better reliability:

-                        if (!empty($currentStartTime) && !empty($newStartTime) && $currentStartTime > $newStartTime) {
+                        if (!empty($currentStartTime) && !empty($newStartTime)) {
+                            $currentStartDateTime = new \DateTime($currentStartTime);
+                            $newStartDateTime = new \DateTime($newStartTime);
+                            if ($currentStartDateTime > $newStartDateTime) {
                             Console::info('Skipping auto-activation as current deployment started later');
                             return;
+                            }
                         }

This approach:

  • Handles timezone differences properly
  • Provides better error handling for malformed timestamps
  • Is more explicit about date comparison intent
  • Guards against potential string comparison edge cases
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c92a14d and 7a465dc.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan

@github-actions
Copy link
Copy Markdown

github-actions bot commented Jun 2, 2025

✨ Benchmark results

  • Requests per second: 853
  • Requests with 200 status code: 153,647
  • P99 latency: 0.217519847

⚡ Benchmark Comparison

Metric This PR Latest version
RPS 853 1,085
200 153,647 195,339
P99 0.217519847 0.171592984

@vermakhushboo vermakhushboo changed the title Don't auto-activate deployment which started earlier & ended later th… Fix build activation race condition Jun 3, 2025
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

277-281: Consider optimizing resource reloading frequency.

While reloading the resource ensures data freshness, there are four separate reload operations in this method. Consider if some of these could be consolidated or cached temporarily to reduce database queries, especially in high-frequency build scenarios.

For example, you could reload once at key decision points rather than before each status update:

# Instead of reloading before each status update, consider:
# 1. Reload once before the auto-activation logic
# 2. Cache the result for subsequent status updates within the same execution

Also applies to: 528-532, 1066-1070, 1283-1287

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ad5a26 and ddb5c52.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • docker-compose.yml (1 hunks)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docker-compose.yml
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
🧬 Code Graph Analysis (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)
src/Appwrite/Event/Database.php (2)
  • getDocument (107-110)
  • getCollection (85-88)
src/Appwrite/Vcs/Comment.php (1)
  • isEmpty (26-29)
🪛 PHPMD (2.15.0)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php

1100-1100: Avoid using static access to class '\Utopia\CLI\Console' in method 'buildDeployment'. (Clean Code Rules)

(StaticAccess)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan
🔇 Additional comments (5)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (5)

277-281: LGTM: Improved consistency and data freshness.

The change from getSequence() to getInternalId() aligns with consistent deployment identification patterns, and reloading the resource ensures fresh data before status comparisons.


528-532: LGTM: Consistent pattern applied.

Same improvement as the previous status update - using internal ID for comparison and ensuring resource freshness.


1066-1070: LGTM: Pattern consistently maintained.

The deployment status update logic remains consistent with the previous changes.


1084-1104: Well-implemented race condition prevention logic.

The timestamp comparison logic correctly prevents activation of deployments that started earlier but finished later than the currently active deployment. The conditional logic is sound:

  1. Checks if current active deployment started later than the deployment being activated
  2. AND current active deployment finished earlier than the deployment being activated
  3. Skips activation in this overlapping scenario

This effectively prevents the race condition described in the PR objectives.


1283-1287: LGTM: Final status update follows established pattern.

The failed deployment status update maintains consistency with the other status update locations.

Copy link
Copy Markdown
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)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1077-1156: Race condition prevention logic implemented correctly.

The core race condition fix addresses the PR objective well. The logic properly:

  • Reloads resource state to avoid stale data
  • Compares deployment timestamps to detect overlapping builds
  • Skips auto-activation when an older deployment would override a newer one
  • Updates both resource and platform rules consistently

Consider these minor improvements:

  1. The buildEndedAt assignment to DateTime::now() (line 1088-1090) might not reflect the actual build end time
  2. The complex timestamp comparison logic could benefit from inline comments explaining the race condition scenario
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a23c99a and 1a286ad.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • docker-compose.yml (1 hunks)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docker-compose.yml
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Indexes/Delete.php:40-40
Timestamp: 2025-06-25T06:25:45.054Z
Learning: In Appwrite's database module, the event label for deleting a table index intentionally uses 'update' (e.g., 'databases.[databaseId].tables.[tableId].indexes.[indexId].update') instead of 'delete', to match legacy behavior as seen in previous controller implementations.
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
🧬 Code Graph Analysis (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)
src/Appwrite/Utopia/Response/Model/Document.php (1)
  • Document (8-97)
🪛 PHPMD (2.15.0)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php

1122-1122: Avoid unused local variables such as '$rulesUpdated'. (Unused Code Rules)

(UnusedLocalVariable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (12)
  • GitHub Check: E2E Service Test (Teams)
  • GitHub Check: E2E Service Test (Realtime)
  • GitHub Check: E2E Service Test (Tokens)
  • GitHub Check: E2E Service Test (Locale)
  • GitHub Check: E2E Service Test (Health)
  • GitHub Check: E2E Service Test (Databases)
  • GitHub Check: E2E Service Test (Avatars)
  • GitHub Check: E2E Service Test (GraphQL)
  • GitHub Check: E2E Service Test (Dev Keys)
  • GitHub Check: E2E General Test
  • GitHub Check: Unit Test
  • GitHub Check: Benchmark
🔇 Additional comments (3)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (3)

277-279: Optimized update pattern for deployment status.

Good optimization to update only the latestDeploymentStatus field instead of the entire resource document. This reduces database overhead and follows a more targeted update approach.


526-528: Consistent optimization pattern applied.

This follows the same optimized update pattern as seen elsewhere in the file, updating only the necessary field rather than the entire document.


1062-1064: Optimization pattern completed.

This completes the consistent application of the optimized update pattern for deployment status changes throughout the build lifecycle.

Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (2)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)

1090-1090: Potential inconsistency: Document update with partial data.

The line updates the deployment with only the buildEndedAt field, but the variable $deployment used afterwards may not reflect this update. Consider using the returned document or updating the variable:

-$deployment = $dbForProject->updateDocument('deployments', $deployment->getId(), new Document(['buildEndedAt' => $tentativeEndTime]));
+$deployment = $dbForProject->updateDocument('deployments', $deployment->getId(), $deployment->setAttribute('buildEndedAt', $tentativeEndTime));

1122-1129: Remove unused variable flagged by static analysis.

The variable $rulesUpdated is set but never used, as correctly identified by PHPMD. Since it doesn't serve any functional purpose, it should be removed:

-$rulesUpdated = false;
-$dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment, &$rulesUpdated) {
-    $rulesUpdated = true;
+$dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment) {
     $rule = $rule
         ->setAttribute('deploymentId', $deployment->getId())
         ->setAttribute('deploymentInternalId', $deployment->getSequence());
     $dbForPlatform->updateDocument('rules', $rule->getId(), $rule);
 }, $queries);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1a286ad and 067b534.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (5 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Indexes/Delete.php:40-40
Timestamp: 2025-06-25T06:25:45.054Z
Learning: In Appwrite's database module, the event label for deleting a table index intentionally uses 'update' (e.g., 'databases.[databaseId].tables.[tableId].indexes.[indexId].update') instead of 'delete', to match legacy behavior as seen in previous controller implementations.
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php:57-59
Timestamp: 2025-06-19T09:20:03.312Z
Learning: In table-related endpoints (such as `src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php`), parameter descriptions should use "table" and "row" terminology instead of "collection" and "document" for clarity and consistency.
🪛 PHPMD (2.15.0)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php

1122-1122: Avoid unused local variables such as '$rulesUpdated'. (Unused Code Rules)

(UnusedLocalVariable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Linter
  • GitHub Check: scan
🔇 Additional comments (3)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (3)

278-278: LGTM: Syntax error resolved and implementation improved.

The Document constructor now correctly uses the => operator in the associative array, resolving the previous syntax error. The approach of updating only the latestDeploymentStatus field instead of the entire document is more efficient and reduces potential conflicts.

Also applies to: 527-527, 1063-1063, 1284-1284


1077-1102: Well-implemented race condition prevention logic.

The new logic effectively prevents activation of deployments that started earlier but finished later than the currently active deployment. The timestamp comparison logic is sound:

  1. Reloads the resource to get current state
  2. Retrieves the active deployment information
  3. Compares build timestamps to detect overlapping builds
  4. Prevents activation when current deployment is more recent

This addresses the core race condition described in the PR objectives.


1104-1156: Auto-activation logic correctly implements conditional deployment.

The updated auto-activation logic properly:

  1. Only activates when $activateBuild is true after race condition checks
  2. Updates resource attributes appropriately for both functions and sites
  3. Handles platform database rules updates consistently
  4. Maintains proper separation between function and site handling

The implementation follows established patterns and maintains data consistency.

Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1113-1115: Remove unused variable to clean up the code.

The $rulesUpdated variable is declared and set but never used. This creates unnecessary code clutter.

Apply this diff to remove the unused variable:

-            $rulesUpdated = false;
             $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment, &$rulesUpdated) {
-                $rulesUpdated = true;
                 $dbForPlatform->updateDocument('rules', $rule->getId(), new Document([
                     'deploymentId' => $deployment->getId(),
                     'deploymentInternalId' => $deployment->getSequence(),
                 ]));
             }, $queries);

Also update the use clause to remove the unused reference:

-            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment, &$rulesUpdated) {
+            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 067b534 and 61a27bf.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (8 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Indexes/Delete.php:40-40
Timestamp: 2025-06-25T06:25:45.054Z
Learning: In Appwrite's database module, the event label for deleting a table index intentionally uses 'update' (e.g., 'databases.[databaseId].tables.[tableId].indexes.[indexId].update') instead of 'delete', to match legacy behavior as seen in previous controller implementations.
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php:57-59
Timestamp: 2025-06-19T09:20:03.312Z
Learning: In table-related endpoints (such as `src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php`), parameter descriptions should use "table" and "row" terminology instead of "collection" and "document" for clarity and consistency.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
🧬 Code Graph Analysis (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)
src/Appwrite/Utopia/Response/Model/Document.php (1)
  • Document (8-97)
🪛 PHPMD (2.15.0)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php

1113-1113: Avoid unused local variables such as '$rulesUpdated'. (Unused Code Rules)

(UnusedLocalVariable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan
🔇 Additional comments (5)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (5)

278-278: LGTM! Excellent refactoring to use the new Document approach.

The changes correctly implement the minimal document update pattern, updating only the latestDeploymentStatus field instead of modifying the entire resource document. This is more efficient and follows the recommended approach.

Also applies to: 527-527, 1061-1061, 1277-1277


859-859: LGTM! Proper implementation of the new Document approach.

The adapter and fallbackFile update correctly uses the minimal document pattern, which is more efficient than updating the entire resource document.


1075-1094: Excellent implementation of race condition prevention.

The logic correctly addresses the deployment activation race condition by:

  1. Reloading the resource to ensure fresh data
  2. Comparing buildStartedAt timestamps between deployments
  3. Preventing activation of older deployments over newer ones

This implementation aligns perfectly with the PR objectives and prevents the race condition where overlapping deployments could override the active deployment incorrectly.


1094-1149: LGTM! Well-implemented auto-activation logic with new Document approach.

The auto-activation logic correctly:

  • Uses conditional activation based on the race condition check
  • Implements the new Document approach for all resource and rule updates
  • Properly handles both function and site resource types
  • Updates only the necessary fields for each document type

The implementation is clean and efficient.


1188-1191: LGTM! Consistent use of new Document approach for VCS rule updates.

The VCS branch rule updates correctly implement the minimal document pattern, updating only the deployment-related fields. This maintains consistency with the rest of the refactoring.

Also applies to: 1204-1207

Copy link
Copy Markdown
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

♻️ Duplicate comments (3)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (3)

1075-1075: Address the default value concern.

Based on the previous review feedback, setting activateBuild = true by default could accidentally activate preview deployments. Consider setting it to false by default and only setting to true when the deployment has activate = true and there are no race condition issues.


1077-1092: Consider using createdAt for race condition detection.

The race condition prevention logic is well-implemented, but based on previous review feedback, consider using createdAt instead of buildStartedAt for timestamp comparison to ensure consistency with deployment creation order.

The overall approach of reloading the resource and comparing timestamps to prevent activation of older deployments is sound.


1083-1088: Use createdAt instead of buildStartedAt as previously suggested.

The previous review feedback specifically recommended using createdAt for race condition detection, but this implementation still uses buildStartedAt. Consider updating to use createdAt() for more reliable deployment ordering.

-                        $currentActiveStartTime = $currentActiveDeployment->getAttribute('buildStartedAt', '');
-                        $deploymentStartTime = $deployment->getAttribute('buildStartedAt', '');
+                        $currentActiveStartTime = $currentActiveDeployment->getCreatedAt();
+                        $deploymentStartTime = $deployment->getCreatedAt();
🧹 Nitpick comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1113-1113: Remove unused variable.

The variable $rulesUpdated is set but never used. Consider removing it to clean up the code.

-                            $rulesUpdated = false;
-                            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment, &$rulesUpdated) {
-                                $rulesUpdated = true;
+                            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 61a27bf and 9d7e218.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (8 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php:57-59
Timestamp: 2025-06-19T09:20:03.312Z
Learning: In table-related endpoints (such as `src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php`), parameter descriptions should use "table" and "row" terminology instead of "collection" and "document" for clarity and consistency.
🧬 Code Graph Analysis (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)
src/Appwrite/Utopia/Response/Model/Document.php (1)
  • Document (8-97)
🪛 PHPMD (2.15.0)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php

1113-1113: Avoid unused local variables such as '$rulesUpdated'. (Unused Code Rules)

(UnusedLocalVariable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan
🔇 Additional comments (4)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (4)

278-278: LGTM: Efficient document update using minimal Document instance.

The refactoring to use new Document(['latestDeploymentStatus' => ...]) correctly implements the minimal update approach, updating only the specific field rather than the entire document.


527-527: LGTM: Consistent implementation of minimal Document updates.

All instances correctly use the minimal Document approach for efficient database updates.

Also applies to: 859-859, 1061-1061, 1276-1276


1094-1149: LGTM: Correct implementation of minimal Document updates for auto-activation.

The auto-activation logic correctly uses minimal Document instances for both resource and platform rule updates, making the operations more efficient.


1203-1206: LGTM: Correct implementation of minimal Document updates for VCS branch rules.

The platform rules update correctly uses minimal Document instances for efficient database operations.

Copy link
Copy Markdown
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: 0

♻️ Duplicate comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1190-1193: Fix undefined variable reference.

This issue was flagged in previous reviews but remains unfixed. The $rule variable is undefined in this catch block scope. Use the $ruleId variable instead:

-                        $rule = $dbForPlatform->updateDocument('rules', $rule->getId(), new Document([
+                        $rule = $dbForPlatform->updateDocument('rules', $ruleId, new Document([
🧹 Nitpick comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1116-1123: Remove unused variable.

The $rulesUpdated variable is set but never used, as flagged by static analysis. Consider removing it unless it serves a specific debugging purpose:

-                            $rulesUpdated = false;
-                            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment, &$rulesUpdated) {
-                                $rulesUpdated = true;
+                            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment) {
                                 $rule = $dbForPlatform->updateDocument('rules', $rule->getId(), new Document([
                                     'deploymentId' => $deployment->getId(),
                                     'deploymentInternalId' => $deployment->getSequence(),
                                 ]));
                             }, $queries);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9d7e218 and a5a1860.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (8 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php:57-59
Timestamp: 2025-06-19T09:20:03.312Z
Learning: In table-related endpoints (such as `src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php`), parameter descriptions should use "table" and "row" terminology instead of "collection" and "document" for clarity and consistency.
🧬 Code Graph Analysis (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)
src/Appwrite/Event/Database.php (2)
  • getCollection (85-88)
  • getDocument (107-110)
src/Appwrite/Utopia/Response/Model/Document.php (1)
  • Document (8-97)
🪛 PHPMD (2.15.0)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php

1116-1116: Avoid unused local variables such as '$rulesUpdated'. (Unused Code Rules)

(UnusedLocalVariable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Linter
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan
🔇 Additional comments (5)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (5)

278-278: LGTM! Efficient partial document updates.

The refactoring to use minimal Document instances for updating only the latestDeploymentStatus field is a good optimization that reduces database overhead compared to updating entire documents.

Also applies to: 527-527, 1061-1061, 1279-1279


859-859: LGTM! Efficient partial document updates for adapter detection.

Good refactoring to use minimal Document instances for updating only the adapter and fallbackFile fields when auto-detecting the site configuration.


1075-1096: Verify timestamp choice for race condition detection.

The race condition prevention logic is well-implemented, but there's a discrepancy with past review feedback. The code uses getCreatedAt() timestamps, but a previous review comment suggested using buildStartedAt timestamps, and the PR description mentions comparing buildStartedAt timestamps.

Consider whether buildStartedAt would be more appropriate for determining deployment precedence:

-                        $currentActiveStartTime = $currentActiveDeployment->getCreatedAt();
-                        $deploymentStartTime = $deployment->getCreatedAt();
+                        $currentActiveStartTime = $currentActiveDeployment->getAttribute('buildStartedAt');
+                        $deploymentStartTime = $deployment->getAttribute('buildStartedAt');

1097-1152: LGTM! Proper activation logic implementation.

The activation logic correctly implements deployment activation for both functions and sites using efficient partial document updates. The approach of updating related platform rules through forEach is appropriate.


1119-1122: LGTM! Consistent rule updates with minimal documents.

The platform rule updates correctly follow the same efficient partial document update pattern used throughout the refactoring.

Also applies to: 1144-1147, 1206-1209

Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (1)

1097-1153: Clean up unused variable.

The activation logic correctly uses minimal Document updates throughout. However, the $rulesUpdated variable on line 1116 is set but never used afterward.

-            $rulesUpdated = false;
-            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment, &$rulesUpdated) {
-                $rulesUpdated = true;
+            $dbForPlatform->forEach('rules', function (Document $rule) use ($dbForPlatform, $deployment) {
                 $rule = $dbForPlatform->updateDocument('rules', $rule->getId(), new Document([
                     'deploymentId' => $deployment->getId(),
                     'deploymentInternalId' => $deployment->getSequence(),
                 ]));
             }, $queries);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a5a1860 and bd63f0c.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (8 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (2)
Learnt from: ItzNotABug
PR: appwrite/appwrite#9752
File: app/config/collections/platform.php:1423-1423
Timestamp: 2025-05-13T12:02:08.071Z
Learning: In the Appwrite database schema, field names like 'resourceInternalId'/'resourceType' and 'deploymentInternalId'/'deploymentResourceType' are functionally equivalent and can coexist in the codebase without causing errors. The docker build and stack work fine with these naming inconsistencies.
Learnt from: ItzNotABug
PR: appwrite/appwrite#9693
File: src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php:57-59
Timestamp: 2025-06-19T09:20:03.312Z
Learning: In table-related endpoints (such as `src/Appwrite/Platform/Modules/Databases/Http/Databases/Tables/Update.php`), parameter descriptions should use "table" and "row" terminology instead of "collection" and "document" for clarity and consistency.
🪛 PHPMD (2.15.0)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php

1116-1116: Avoid unused local variables such as '$rulesUpdated'. (Unused Code Rules)

(UnusedLocalVariable)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (15)
  • GitHub Check: Benchmark
  • GitHub Check: E2E Service Test (Webhooks)
  • GitHub Check: E2E Service Test (Teams)
  • GitHub Check: E2E Service Test (Migrations)
  • GitHub Check: E2E Service Test (VCS)
  • GitHub Check: E2E Service Test (Proxy)
  • GitHub Check: E2E Service Test (Avatars)
  • GitHub Check: E2E Service Test (Functions)
  • GitHub Check: E2E Service Test (Projects)
  • GitHub Check: E2E Service Test (Locale)
  • GitHub Check: E2E Service Test (GraphQL)
  • GitHub Check: E2E Service Test (Account)
  • GitHub Check: E2E Service Test (Dev Keys)
  • GitHub Check: Unit Test
  • GitHub Check: scan
🔇 Additional comments (5)
src/Appwrite/Platform/Modules/Functions/Workers/Builds.php (5)

278-278: LGTM: Optimized document updates implemented correctly.

The minimal Document approach has been properly implemented across all deployment status updates, which improves performance by only updating the necessary fields instead of entire documents.

Also applies to: 527-527, 1061-1061, 1279-1279


859-859: LGTM: Site adapter update optimized.

The adapter and fallback file update correctly uses the minimal Document approach while preserving the existing detection logic.


1075-1095: LGTM: Race condition prevention logic correctly implemented.

The logic properly addresses the race condition by:

  • Defaulting to safe behavior (no activation)
  • Using creation timestamps for comparison
  • Preventing older deployments from overriding newer active ones

This satisfies the PR objective of fixing build activation race conditions.


1190-1194: LGTM: VCS branch rule updates optimized.

The VCS branch rule updates correctly use the minimal Document approach, maintaining consistency with the optimization pattern applied throughout the method.

Also applies to: 1206-1210


1075-1210: Excellent implementation of race condition fix and optimizations.

The changes successfully address all the key objectives:

  1. Race condition prevention: The logic correctly prevents older deployments from overriding newer active ones by comparing creation timestamps
  2. Performance optimization: Consistent use of minimal Document updates throughout reduces database overhead
  3. Past feedback integration: All previous review suggestions have been properly implemented

The implementation is thorough, consistent, and maintains backward compatibility while solving the identified race condition issue.

@Meldiron Meldiron merged commit cc1129a into 1.7.x Jul 9, 2025
38 checks passed
@stnguyen90 stnguyen90 deleted the fix-build-activation-race-condition branch October 1, 2025 23:59
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