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

Integrated code lifecycle: Fix an issue with concurrent build queue access #9876

Merged

Conversation

BBesrour
Copy link
Member

@BBesrour BBesrour commented Nov 26, 2024

Checklist

General

Server

Changes affecting Programming Exercises

  • High priority: I tested all changes and their related features with all corresponding user types on a test server configured with the integrated lifecycle setup (LocalVC and LocalCI).

Motivation and Context

When the network experiences slow connections in a multi-node environment, it can happen that the build queues get out of sync. One issue might be that the Hazelcast data structures are not working well with streams. This leads to the following exception:

java.lang.IllegalStateException: End size 1 is less than fixed size 2
... 
at de.tum.cit.aet.artemis.programming.service.localci.SharedQueueManagementService.getQueuedJobs(SharedQueueManagementService.java:112)

This PR changes the access to the shared data structures and used new ArrayList to copy the relevant content with the toArray operation, which is implemented by the Hazelcast data structure (e.g. IQueue) and not by default methods from Java, which might not fully be supported.

Steps for Testing

Prerequisites:

  • 1 Admin
  1. Log in to Artemis
  2. Submit a programming exercise a few times (make sure to have some queued jobs, so you might to have to quickly push 10+ times)
  3. Navigate to build Overview
  4. Make sure that the page works correctly (queued jobs visible and can cancel them)

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Performance Review

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1

Summary by CodeRabbit

  • Bug Fixes

    • Improved stability and performance of job handling by using stable collections for queue and processing jobs.
    • Enhanced robustness in job cancellation methods to prevent issues with concurrent modifications.
  • New Features

    • Updated methods to ensure consistent data handling for job processing and cancellation.

@BBesrour BBesrour requested a review from a team as a code owner November 26, 2024 23:09
@BBesrour BBesrour self-assigned this Nov 26, 2024
@github-actions github-actions bot added server Pull requests that update Java code. (Added Automatically!) programming Pull requests that affect the corresponding module labels Nov 26, 2024
Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

The SharedQueueManagementService class has been modified to enhance the handling of collections derived from Hazelcast data structures. Key changes include replacing stream operations with direct collection instantiation for IQueue and IMap values in methods like getQueuedJobs and getProcessingJobs. This ensures operations are performed on stable collections, mitigating potential instability during concurrent access. The method getBuildAgentInformationWithoutRecentBuildJobs has been adjusted to utilize the updated getBuildAgentInformation method, and the cancelBuildJob method now retrieves a list of queued jobs before performing cancellation checks.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java - Replaced streams with direct collection instantiation for IQueue and IMap values.
- Updated getBuildAgentInformationWithoutRecentBuildJobs to use the updated getBuildAgentInformation method.
- Modified cancelBuildJob to create a list of queued jobs before checking for cancellation.
src/main/java/de/tum/cit/aet/artemis/buildagent/service/SharedQueueProcessingService.java - Changed getProcessingJobsOfNode to create a new ArrayList from processingJobs.values() before filtering, replacing the previous stream-based implementation.

Possibly related PRs

Suggested labels

tests, bugfix, component:integrated code lifecycle

Suggested reviewers

  • dmytropolityka
  • Hialus
  • SimonEntholzer

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 pmd (7.7.0)
src/main/java/de/tum/cit/aet/artemis/buildagent/service/SharedQueueProcessingService.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.

src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 59dd5d5 and 9bae068.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/buildagent/service/SharedQueueProcessingService.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/de/tum/cit/aet/artemis/buildagent/service/SharedQueueProcessingService.java
  • src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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 or @coderabbitai title 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

@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

🧹 Outside diff range and nitpick comments (3)
src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java (3)

113-114: Improved thread safety in collection handling

The change from streams to direct collection instantiation is a good improvement for concurrent scenarios. The comment effectively explains the rationale.

Consider adding synchronization if you need to perform multiple operations atomically on these collections.

Also applies to: 118-119


123-124: LGTM: Improved stability for course-specific queries

Creating stable snapshots before filtering is a good practice. Consider adding index-based filtering if the number of jobs per course becomes very large.

Also applies to: 128-129


168-171: Consider optimizing multiple iterations

While the change improves stability, the method performs multiple iterations over the queue:

  1. First to check if job exists
  2. Then to collect jobs to remove

Consider combining these operations into a single pass.

 public void cancelBuildJob(String buildJobId) {
-    List<BuildJobQueueItem> queuedJobs = new ArrayList<>(queue);
-    if (queuedJobs.stream().anyMatch(job -> Objects.equals(job.id(), buildJobId))) {
-        List<BuildJobQueueItem> toRemove = new ArrayList<>();
-        for (BuildJobQueueItem job : queuedJobs) {
-            if (Objects.equals(job.id(), buildJobId)) {
-                toRemove.add(job);
-            }
-        }
-        queue.removeAll(toRemove);
+    List<BuildJobQueueItem> queuedJobs = new ArrayList<>(queue);
+    List<BuildJobQueueItem> toRemove = queuedJobs.stream()
+        .filter(job -> Objects.equals(job.id(), buildJobId))
+        .toList();
+    if (!toRemove.isEmpty()) {
+        queue.removeAll(toRemove);
     }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 83ac531 and bf5d9ac.

📒 Files selected for processing (1)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java (8 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

🔇 Additional comments (5)
src/main/java/de/tum/cit/aet/artemis/programming/service/localci/SharedQueueManagementService.java (5)

8-8: LGTM: Import addition is appropriate

The addition of java.util.Collection import supports the improved collection handling throughout the service.


133-134: LGTM: Consistent implementation pattern

Also applies to: 138-139


210-211: LGTM: Consistent collection handling

The changes maintain consistency with the improved collection handling pattern used throughout the service.

Also applies to: 222-223


233-234: LGTM: Consistent implementation

Also applies to: 248-249, 263-264, 271-272


148-150: Verify the impact of publicSshKey addition

While the collection handling changes are good, let's verify the publicSshKey usage across the codebase.

✅ Verification successful

Based on the shell script results, I can now generate the final response:

publicSshKey addition is properly integrated

The publicSshKey field is consistently used across the codebase:

  • Correctly passed through BuildAgentInformation constructor in SharedQueueProcessingService
  • Properly handled in GitPublickeyAuthenticatorService for SSH authentication
  • Verified in BuildAgentSshAuthenticationIntegrationTest
  • Consistently propagated in SharedQueueManagementService
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for BuildAgentInformation constructor usage
ast-grep --pattern 'new BuildAgentInformation($$$)'

# Search for publicSshKey references
rg "publicSshKey" --type java

Length of output: 3160

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 26, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 26, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 26, 2024
@github-actions github-actions bot added the buildagent Pull requests that affect the corresponding module label Nov 27, 2024
Copy link

@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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7a5ec24 and 5d74a91.

📒 Files selected for processing (1)
  • src/main/java/de/tum/cit/aet/artemis/buildagent/service/SharedQueueProcessingService.java (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/buildagent/service/SharedQueueProcessingService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 27, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 27, 2024
@krusche krusche changed the title Development: Fix issue when high number of items are added to the queue in a short period of time Integrated code lifecycle: Fix an issue with concurrent build queue access Nov 27, 2024
@krusche krusche added this to the 7.7.3 milestone Nov 27, 2024
@krusche krusche merged commit 4eaba4e into develop Nov 27, 2024
32 of 36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
buildagent Pull requests that affect the corresponding module programming Pull requests that affect the corresponding module ready for review server Pull requests that update Java code. (Added Automatically!)
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

2 participants