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

Quiz exercises: Fix an error after using the practice mode #9571

Merged
merged 3 commits into from
Oct 24, 2024

Conversation

Hialus
Copy link
Member

@Hialus Hialus commented Oct 23, 2024

Checklist

General

Server

  • Important: I implemented the changes with a very good performance and prevented too many (unnecessary) and too complex database calls.
  • I strictly followed the principle of data economy for all database calls.
  • I strictly followed the server coding and design guidelines.
  • I added multiple integration tests (Spring) related to the features (with a high test coverage). -> Follow-up
  • I documented the Java code using JavaDoc style.

Motivation and Context

We encountered a bug today on production which prevented students from viewing their quiz result after they also participated in the practice mode.

Description

This was caused by a small change in the endpoint where we tried to load a single submission of a participation. This does not work, as participations can have multiple submissions when it is not fully new. I now changed it to instead load the submission of the fetched result if it has any.

Steps for Testing

Prerequisites:

  • 1 Instructor
  • 2 Students
  • 1 Programming Exercise with Complaints enabled
  1. Log in to Artemis
  2. Participate in a quiz
  3. View the result -> Works
  4. Practice the quiz
  5. View the result -> Works

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

Test Coverage

-> Integration test will be done in a follow-up

Summary by CodeRabbit

  • New Features

    • Introduced a method to retrieve quiz submissions along with submitted answers based on a specific result ID, enhancing data retrieval capabilities.
  • Improvements

    • Updated logic in the quiz participation handling to ensure correct submission loading based on the existence of a result, improving user experience during quiz participation.
    • Enhanced the handling of quiz submissions by ensuring the correct optional value is returned, streamlining data processing.

@Hialus Hialus self-assigned this Oct 23, 2024
@github-actions github-actions bot added server Pull requests that update Java code. (Added Automatically!) quiz Pull requests that affect the corresponding module labels Oct 23, 2024
@Hialus Hialus added this to the 7.6.2 milestone Oct 23, 2024
@Hialus Hialus force-pushed the bugfix/quiz/fix-practice-mode branch from 89f06ca to 13a5d8c Compare October 23, 2024 15:20
@Hialus Hialus marked this pull request as ready for review October 23, 2024 15:44
@Hialus Hialus requested a review from a team as a code owner October 23, 2024 15:44
Copy link

coderabbitai bot commented Oct 23, 2024

Walkthrough

The pull request modifies the QuizSubmissionRepository interface by changing the return type of an existing method and adding a new method to retrieve QuizSubmission entities by result ID. It also updates the startParticipation method in the QuizParticipationResource class to include logic that checks for the existence of a result before determining which submission to load. Additionally, changes in the QuizSubmissionService class improve the handling of optional values and mark a method as deprecated in favor of using a Data Transfer Object (DTO).

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/quiz/repository/QuizSubmissionRepository.java Changed return type of findWithEagerSubmittedAnswersByParticipationId(long participationId) to List<QuizSubmission>. Added method Optional<QuizSubmission> findWithEagerSubmittedAnswersByResultId(@Param("resultId") long resultId).
src/main/java/de/tum/cit/aet/artemis/quiz/web/QuizParticipationResource.java Updated startParticipation method to include conditional logic for handling submissions based on result existence.
src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizSubmissionService.java Modified calculateAllResults method to assign quizSubmissionOptional using findFirst() on the result stream. Marked removeUnnecessaryObjectsBeforeSendingToClient as deprecated.

Possibly related PRs

Suggested labels

tests, bugfix, programming

Suggested reviewers

  • SimonEntholzer
  • krusche
  • egekurt123

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/quiz/repository/QuizSubmissionRepository.java (1)

42-50: Add JavaDoc documentation for the new method.

To maintain consistency with other documented methods in the repository, please add JavaDoc documentation explaining the purpose and parameters of the new method.

Add this documentation above the method:

+    /**
+     * Retrieve QuizSubmission with eagerly fetched submitted answers for a given result ID
+     *
+     * @param resultId the ID of the result for which to find the submission
+     * @return Optional containing the QuizSubmission if found, empty otherwise
+     */
    @Query("""
src/main/java/de/tum/cit/aet/artemis/quiz/web/QuizParticipationResource.java (2)

72-73: Consider splitting the endpoint responsibilities.

The TODOs highlight that this endpoint serves dual purposes: starting a participation and viewing results. This violates the single responsibility principle and REST best practices.

Consider:

  1. Creating a separate endpoint for viewing results (e.g., GET /quiz-exercises/{exerciseId}/results)
  2. Renaming this endpoint to clarify its primary purpose
  3. Adding proper documentation about the endpoint's behavior

Would you like me to propose a detailed design for this separation of concerns?


97-104: Enhance error handling and documentation.

While the logic correctly handles both new and existing results, there are several improvements that could be made:

  1. Add custom exception messages to .orElseThrow() calls to provide better error context
  2. Document the business logic explaining why we handle results differently
  3. Consider more descriptive variable names

Apply this diff:

 if (result.getId() == null) {
     // Load the live submission of the participation
-    result.setSubmission(quizSubmissionRepository.findWithEagerSubmittedAnswersByParticipationId(participation.getId()).orElseThrow());
+    result.setSubmission(quizSubmissionRepository.findWithEagerSubmittedAnswersByParticipationId(participation.getId())
+        .orElseThrow(() -> new IllegalStateException(
+            String.format("No submission found for participation %d", participation.getId()))));
 }
 else {
     // Load the actual submission of the result
-    result.setSubmission(quizSubmissionRepository.findWithEagerSubmittedAnswersByResultId(result.getId()).orElseThrow());
+    result.setSubmission(quizSubmissionRepository.findWithEagerSubmittedAnswersByResultId(result.getId())
+        .orElseThrow(() -> new IllegalStateException(
+            String.format("No submission found for result %d", result.getId()))));
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c17b2c4 and b3fc404.

📒 Files selected for processing (2)
  • src/main/java/de/tum/cit/aet/artemis/quiz/repository/QuizSubmissionRepository.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/quiz/web/QuizParticipationResource.java (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/main/java/de/tum/cit/aet/artemis/quiz/repository/QuizSubmissionRepository.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

src/main/java/de/tum/cit/aet/artemis/quiz/web/QuizParticipationResource.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 (2)
src/main/java/de/tum/cit/aet/artemis/quiz/repository/QuizSubmissionRepository.java (1)

42-50: Consider performance optimizations for the new query method.

The implementation looks good and follows the repository patterns. However, there are a few suggestions for optimization:

  1. Consider adding an index hint for the results.id column if not already indexed, as this is now a primary lookup path.
  2. If the result details are frequently accessed, consider eager fetching them to prevent N+1 queries.

Consider these improvements:

    @Query("""
            SELECT submission
            FROM QuizSubmission submission
                LEFT JOIN FETCH submission.submittedAnswers
-               JOIN submission.results r
+               JOIN FETCH submission.results r
            WHERE r.id = :resultId
            """)

Let's verify if there's an index on the results table:

src/main/java/de/tum/cit/aet/artemis/quiz/web/QuizParticipationResource.java (1)

97-104: Verify database query performance.

The code makes multiple database calls in sequence. Let's verify the query performance and check if we can optimize it.

✅ Verification successful

Based on the results, I can now generate the final response since I have enough information about the database queries.

Database queries are properly optimized with eager loading

The repository methods are well-implemented with appropriate JOIN FETCH clauses to prevent N+1 query issues:

  • Both findWithEagerSubmittedAnswersByParticipationId and findWithEagerSubmittedAnswersByResultId use LEFT JOIN FETCH for loading submitted answers
  • The queries are separate but each performs a single database call with eager loading
  • The conditional logic ensures only one query is executed per request
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for N+1 query patterns and verify eager loading

# Test 1: Check if the repository methods use proper JOIN FETCH
ast-grep --pattern 'SELECT $$$'

# Test 2: Look for related repository queries to see if we can combine them
rg -A 5 'findWithEagerSubmittedAnswersByResultId|findWithEagerSubmittedAnswersByParticipationId'

Length of output: 3811

coderabbitai[bot]
coderabbitai bot previously approved these changes Oct 23, 2024
Copy link

⚠️ Unable to deploy to test servers ⚠️

Testserver "artemis-test4.artemis.cit.tum.de" is already in use by PR #9283.

@github-actions github-actions bot added the deployment-error Added by deployment workflows if an error occured label Oct 23, 2024
@github-actions github-actions bot removed the deployment-error Added by deployment workflows if an error occured label Oct 23, 2024
@sachmii sachmii temporarily deployed to artemis-test5.artemis.cit.tum.de October 23, 2024 15:55 — with GitHub Actions Inactive
Copy link

@sachmii sachmii left a comment

Choose a reason for hiding this comment

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

Tried it on TS5, I still get the "Internal server error".

Bildschirmfoto 2024-10-23 um 18 13 47 Bildschirmfoto 2024-10-23 um 18 13 55

Copy link

@Feras797 Feras797 left a comment

Choose a reason for hiding this comment

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

I tested on TS5. Both after the initial graded participation and practice I was able to view the results.

@Hialus
Copy link
Member Author

Hialus commented Oct 23, 2024

Tried it on TS5, I still get the "Internal server error".

Bildschirmfoto 2024-10-23 um 18 13 47 Bildschirmfoto 2024-10-23 um 18 13 55

This is also fixed now

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 (1)
src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizSubmissionService.java (1)

150-150: LGTM! Consider adding a comment explaining submission selection.

The change correctly handles multiple submissions by selecting the first one, fixing the internal server error. However, it would be helpful to add a comment explaining why we choose the first submission when multiple exist.

-            Optional<QuizSubmission> quizSubmissionOptional = quizSubmissionRepository.findWithEagerSubmittedAnswersByParticipationId(participation.getId()).stream().findFirst();
+            // Select the first submission when multiple exist (e.g., from practice mode)
+            Optional<QuizSubmission> quizSubmissionOptional = quizSubmissionRepository.findWithEagerSubmittedAnswersByParticipationId(participation.getId()).stream().findFirst();
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b3fc404 and 50d6229.

📒 Files selected for processing (3)
  • src/main/java/de/tum/cit/aet/artemis/quiz/repository/QuizSubmissionRepository.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizSubmissionService.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/quiz/web/QuizParticipationResource.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/de/tum/cit/aet/artemis/quiz/repository/QuizSubmissionRepository.java
  • src/main/java/de/tum/cit/aet/artemis/quiz/web/QuizParticipationResource.java
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizSubmissionService.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 (2)
src/main/java/de/tum/cit/aet/artemis/quiz/service/QuizSubmissionService.java (2)

Line range hint 273-274: Enhance error handling in TODO section.

The TODO comment suggests adding additional checks, but the comment about performance concerns seems premature. Consider:

  1. Implementing course membership validation
  2. Moving the check earlier in the request pipeline
  3. Adding specific error messages for each failure case

Let's analyze the current error handling patterns:


Line range hint 211-241: Consider prioritizing migration to DTOs.

The current approach of modifying entity objects directly before sending to the client is fragile and could lead to security issues. While the @deprecated annotation indicates future plans to use DTOs, this should be prioritized because:

  1. Direct entity modification is an anti-pattern
  2. Current approach risks accidental exposure of sensitive data
  3. Changes to entity structure could break this logic

Let's check if there are other similar patterns in the codebase:

✅ Verification successful

Let me gather more information to verify the presence of DTOs and similar patterns in the codebase:


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

Migration to DTOs is already a pattern in the codebase

The codebase shows extensive use of DTOs across different modules, with numerous DTO classes and conversion patterns present. The current deprecated method is an outlier from the established patterns. Specific observations:

  1. Many modules already follow DTO pattern (e.g., ExerciseDTO, ParticipationDTO, etc.)
  2. Conversion services exist (e.g., ConversationDTOService with convertToDTO methods)
  3. The codebase demonstrates proper separation of domain and DTO layers

The review comment's concern about migrating to DTOs is valid and aligns with the existing architectural patterns in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar patterns of entity modification before sending to client
rg -l "removeUnnecessaryObjects|filterForClient|stripSensitiveData" 

# Search for existing DTO patterns to align with
ast-grep --pattern 'class $_ implements $_ {
  $$$
  toDTO() {
    $$$
  }
  $$$
}'

Length of output: 356


Script:

#!/bin/bash
# Search for DTO classes and patterns
rg -l "DTO|Dto" --type java

# Look for specific patterns of data transformation
rg -A 5 "toDTO|mapToDTO|convertToDTO" --type java

# Check for any existing mapper classes
rg -l "Mapper|mapper" --type java

Length of output: 76814

Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

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

Tested on TS3. Works as described!

image
image

Is it possible to view the results of old submissions. I think when I click on view result, only the latest one is shown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
quiz 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.

6 participants