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

Development: Fix issue when high number of items are added to the queue in a short period of time #9876

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

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

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)

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

  • I (as a reviewer) confirm that the client changes (in particular related to REST calls and UI responsiveness) are implemented with a very good performance even for very large courses with more than 2000 students.
  • I (as a reviewer) confirm that the server changes (in particular related to database calls) are implemented with a very good performance even for very large courses with more than 2000 students.

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

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:Programming, ready to merge, buildagent

Suggested reviewers

  • krusche
  • 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.


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

Comment on lines +363 to +364
List<BuildJobQueueItem> processingJobsList = new ArrayList<>(processingJobs.values());
return processingJobsList.stream().filter(job -> Objects.equals(job.buildAgent().memberAddress(), memberAddress)).toList();
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Potential concurrent modification issues found in SharedQueueProcessingService

The verification revealed another instance in SharedQueueProcessingService that directly streams from a Hazelcast collection:

processingJobs.getAll(runningBuildJobIdsAfterGracePeriod).values().stream().toList();

This pattern is susceptible to the same concurrent modification issue. The locations that need attention:

  • SharedQueueProcessingService.java: Line 363 (already fixed in this PR)
  • SharedQueueProcessingService.java: Direct streaming from processingJobs.getAll(...).values() needs similar defensive copying

Other usages of .values().stream() in the codebase are safe as they operate on regular Java collections, not Hazelcast distributed collections.

🔗 Analysis chain

LGTM! The change addresses concurrent modification issues.

The modification to create a new ArrayList before streaming is a good approach to prevent IllegalStateException when the underlying Hazelcast map is modified concurrently. This aligns with the PR objective of fixing issues during rapid queue updates.

For better performance, consider using a more memory-efficient approach:

-        List<BuildJobQueueItem> processingJobsList = new ArrayList<>(processingJobs.values());
-        return processingJobsList.stream().filter(job -> Objects.equals(job.buildAgent().memberAddress(), memberAddress)).toList();
+        return processingJobs.values().stream()
+            .filter(job -> Objects.equals(job.buildAgent().memberAddress(), memberAddress))
+            .collect(Collectors.toCollection(ArrayList::new));

Let's verify if similar patterns exist in the codebase that might need the same fix:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct streaming on Hazelcast collections
ast-grep --pattern 'IMap<$_, $_> $map = $_;
  $$$
  $map.values().stream().$$$'

# Search for potential concurrent access patterns
rg -A 2 'values\(\)\.stream\(\)' 

Length of output: 9569

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 server Pull requests that update Java code. (Added Automatically!)
Projects
Status: Ready For Review
Development

Successfully merging this pull request may close these issues.

1 participant