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 exercise deletion with existing Iris messages #9875

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

Conversation

kaancayli
Copy link
Contributor

@kaancayli kaancayli commented Nov 26, 2024

⚠️ Contains Database Migrations!

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).
  • I added pre-authorization annotations according to the guidelines and checked the course groups for all new REST Calls (security).
  • I documented the Java code using JavaDoc style.

Motivation and Context

Currently, we are unable to delete exercises in some cases which have any associated iris sessions in the database with messages and message_contents, due to a foreign key integrity violation. This PR adds a database migration to introduce a cascading deletes on that foreign keys, so when an exercise is deleted, all associated sessions are automatically deleted as well. This also triggers cascading deletes of all of the session's messages, and all of those messages' contents.

Description

  • Added a liquibase changeset which drops the existing foreign key constraints for iris messages and re-adds them with a cascading delete.
  • Added two integration tests to catch this issue in the future

Steps for Testing

Prerequisites:

  • Artemis with Iris globally enabled
  • 1 Course with Iris enabled
  • 1 Exercise (either Programming or Text, as those are the ones where Iris is supported)
  1. Start a chat with Iris in the exercise
  2. Send message to Iris and receive a response
  3. Try to delete the exercise

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

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced message handling in chat session tests.
    • Added support for text and JSON message content in integration tests.
  • Tests

    • Introduced new test methods to verify deletion of exercise chat sessions and associated messages.
  • Chores

    • Adjusted minimum coverage ratio for code coverage verification in the build configuration.

@kaancayli kaancayli requested a review from a team as a code owner November 26, 2024 22:15
@github-actions github-actions bot added tests database Pull requests that update the database. (Added Automatically!). Require a CRITICAL deployment. labels Nov 26, 2024
@github-actions github-actions bot added the iris Pull requests that affect the corresponding module label Nov 26, 2024
@kaancayli kaancayli changed the title Development: Fix exercise deletion with existing Iris messages Development: Fix exercise deletion with existing Iris messages Nov 26, 2024
Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

The pull request introduces enhancements to the IrisExerciseChatSessionIntegrationTest class by adding functionalities for message handling within chat sessions. It incorporates new dependencies for message services and repositories, introduces private methods for creating mock messages, and expands the test suite with new test methods that verify the deletion of exercise chat sessions and their associated messages. Additionally, the build.gradle file is modified to adjust the minimum coverage ratio for the jacocoTestCoverageVerification task.

Changes

File Change Summary
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java - Added fields: irisMessageService, irisMessageRepository
- Added methods: createDefaultMockTextMessage, createDefaultMockJsonMessage, createMockTextContent, createMockJsonContent
- Added test methods: testDeleteExerciseWithIrisMessagesWithTextMessageContent, testDeleteExerciseWithIrisMessagesWithJsonMessageContent
build.gradle - Modified jacocoTestCoverageVerification task to change minimum coverage ratio from 0.895 to 0.894

Possibly related PRs

  • Development: Fix exercise deletion with existing Iris sessions #9567: This PR adds a new test method testDeleteExerciseWithIrisSession in the IrisExerciseChatSessionIntegrationTest class, which is directly related to the changes made in the main PR that also modifies the IrisExerciseChatSessionIntegrationTest class to enhance message handling and deletion scenarios.

Suggested labels

ready to merge, maintainer-approved

Suggested reviewers

  • krusche

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b9e35a8 and 9162f16.

⛔ Files ignored due to path filters (1)
  • src/main/resources/config/liquibase/master.xml is excluded by !**/*.xml
📒 Files selected for processing (1)
  • build.gradle (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • build.gradle

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/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (3)

81-91: Consider enhancing JSON content variety.

While the implementation is correct, consider making the JSON content more varied to better test different scenarios.

 private IrisJsonMessageContent createMockJsonContent() {
-    var jsonMap = Map.of("key1", "value1", "key2", "value2", "key3", "value3");
+    var rdm = ThreadLocalRandom.current();
+    var jsonMap = Map.of(
+        "messageId", String.valueOf(rdm.nextInt(1000)),
+        "timestamp", String.valueOf(System.currentTimeMillis()),
+        "content", "Test message " + rdm.nextInt(100)
+    );
     JsonNode jsonNode = new ObjectMapper().valueToTree(jsonMap);
     return new IrisJsonMessageContent(jsonNode);
 }

157-174: LGTM! Comprehensive test for text message cleanup.

The test properly verifies the cascade deletion of both the session and its messages.

Consider enhancing the verification by checking the message count before deletion:

 irisMessageService.saveMessage(createDefaultMockTextMessage(irisSession), irisSession, IrisMessageSender.LLM);

+// Verify initial state
+assertThat(irisMessageRepository.findAllBySessionId(irisSession.getId())).hasSize(4);
 assertThat(irisExerciseChatSessionRepository.findByIdElseThrow(irisSession.getId())).isNotNull();

176-193: LGTM! Comprehensive test for JSON message cleanup.

The test effectively verifies the cascade deletion behavior with JSON message content.

Consider enhancing the verification similar to the text message test:

 irisMessageService.saveMessage(createDefaultMockJsonMessage(irisSession), irisSession, IrisMessageSender.LLM);

+// Verify initial state
+assertThat(irisMessageRepository.findAllBySessionId(irisSession.getId())).hasSize(4);
 assertThat(irisExerciseChatSessionRepository.findByIdElseThrow(irisSession.getId())).isNotNull();
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1539df5 and 909d35e.

⛔ Files ignored due to path filters (2)
  • src/main/resources/config/liquibase/changelog/20241125000900_changelog.xml is excluded by !**/*.xml
  • src/main/resources/config/liquibase/master.xml is excluded by !**/*.xml
📒 Files selected for processing (1)
  • src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

📓 Learnings (1)
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (1)
Learnt from: alexjoham
PR: ls1intum/Artemis#9455
File: src/test/java/de/tum/cit/aet/artemis/iris/IrisTextExerciseChatMessageIntegrationTest.java:401-401
Timestamp: 2024-11-12T12:51:58.050Z
Learning: In the Artemis project, when new fields are added to classes like `PyrisChatStatusUpdateDTO`, corresponding tests may be implemented in separate integration test classes such as `IrisChatTokenTrackingIntegrationTest`.
🔇 Additional comments (3)
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (3)

6-7: LGTM! Dependencies and field injections are properly organized.

The new imports and autowired fields are well-structured and follow the existing patterns in the test class.

Also applies to: 15-23, 28-29, 39-43


58-61: LGTM! Well-structured helper method for session creation.

The method follows the class's existing patterns and properly uses the repository for persistence.


63-79: LGTM! Text message creation is well implemented.

The random text generation provides good test data variety while maintaining readability.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 26, 2024
Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in the IrisExerciseChatSessionIntegrationTest class enhance its functionality by adding new dependencies for JSON handling and random content generation. Several private methods for creating mock messages have been introduced, along with two new test cases that validate the deletion of exercise sessions and their associated messages. Additionally, new dependencies for IrisMessageService and IrisMessageRepository have been autowired to support message management within the tests.

Changes

File Change Summary
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java - Added dependencies for JSON and random content handling.
- Introduced private methods for creating mock text and JSON messages.
- Added two new test cases for message deletion.
- Autowired IrisMessageService and IrisMessageRepository.

Possibly related PRs

  • Development: Fix exercise deletion with existing Iris sessions #9567: This PR adds a test method in the IrisExerciseChatSessionIntegrationTest class that verifies the deletion of a programming exercise and its associated Iris session, which is directly related to the changes made in the main PR that also enhances the IrisExerciseChatSessionIntegrationTest class with new test cases for message deletion.

Suggested labels

tests, database, ready to merge, maintainer-approved, iris

Suggested reviewers

  • dfuchss
  • Hialus
  • JohannesStoehr

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/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.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 (2)
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (2)

69-79: Consider extracting test data arrays as constants

The arrays of adjectives and nouns could be moved to class-level constants to improve maintainability and reusability.

 class IrisExerciseChatSessionIntegrationTest extends AbstractIrisIntegrationTest {
+    private static final String[] TEST_ADJECTIVES = { "happy", "sad", "angry", "funny", "silly", "crazy", "beautiful", "smart" };
+    private static final String[] TEST_NOUNS = { "dog", "cat", "house", "car", "book", "computer", "phone", "shoe" };
     
     private IrisMessageContent createMockTextContent() {
-        String[] adjectives = { "happy", "sad", "angry", "funny", "silly", "crazy", "beautiful", "smart" };
-        String[] nouns = { "dog", "cat", "house", "car", "book", "computer", "phone", "shoe" };
 
         var rdm = ThreadLocalRandom.current();
-        String randomAdjective = adjectives[rdm.nextInt(adjectives.length)];
-        String randomNoun = nouns[rdm.nextInt(nouns.length)];
+        String randomAdjective = TEST_ADJECTIVES[rdm.nextInt(TEST_ADJECTIVES.length)];
+        String randomNoun = TEST_NOUNS[rdm.nextInt(TEST_NOUNS.length)];

176-193: Consider combining duplicate test logic

This test is nearly identical to the text message test. Consider parameterizing the test to reduce duplication.

+    @ParameterizedTest
+    @EnumSource(MessageType.class)
     @WithMockUser(username = TEST_PREFIX + "instructor1", roles = "INSTRUCTOR")
-    void testDeleteExerciseWithIrisMessagesWithJsonMessageContent() throws Exception {
+    void testDeleteExerciseWithIrisMessages(MessageType messageType) throws Exception {
         var irisSession = createSessionForUser("instructor1");
 
         // Create and some messages to the session
-        irisMessageService.saveMessage(createDefaultMockJsonMessage(irisSession), irisSession, IrisMessageSender.USER);
-        irisMessageService.saveMessage(createDefaultMockJsonMessage(irisSession), irisSession, IrisMessageSender.LLM);
-        irisMessageService.saveMessage(createDefaultMockJsonMessage(irisSession), irisSession, IrisMessageSender.USER);
-        irisMessageService.saveMessage(createDefaultMockJsonMessage(irisSession), irisSession, IrisMessageSender.LLM);
+        var createMessage = messageType == MessageType.TEXT ? 
+            this::createDefaultMockTextMessage : 
+            this::createDefaultMockJsonMessage;
+        
+        irisMessageService.saveMessage(createMessage.apply(irisSession), irisSession, IrisMessageSender.USER);
+        irisMessageService.saveMessage(createMessage.apply(irisSession), irisSession, IrisMessageSender.LLM);
+        irisMessageService.saveMessage(createMessage.apply(irisSession), irisSession, IrisMessageSender.USER);
+        irisMessageService.saveMessage(createMessage.apply(irisSession), irisSession, IrisMessageSender.LLM);

Add this enum at class level:

private enum MessageType {
    TEXT, JSON
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1539df5 and 909d35e.

⛔ Files ignored due to path filters (2)
  • src/main/resources/config/liquibase/changelog/20241125000900_changelog.xml is excluded by !**/*.xml
  • src/main/resources/config/liquibase/master.xml is excluded by !**/*.xml
📒 Files selected for processing (1)
  • src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

📓 Learnings (1)
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (1)
Learnt from: alexjoham
PR: ls1intum/Artemis#9455
File: src/test/java/de/tum/cit/aet/artemis/iris/IrisTextExerciseChatMessageIntegrationTest.java:401-401
Timestamp: 2024-11-12T12:51:58.050Z
Learning: In the Artemis project, when new fields are added to classes like `PyrisChatStatusUpdateDTO`, corresponding tests may be implemented in separate integration test classes such as `IrisChatTokenTrackingIntegrationTest`.
🔇 Additional comments (4)
src/test/java/de/tum/cit/aet/artemis/iris/IrisExerciseChatSessionIntegrationTest.java (4)

6-7: LGTM: Dependencies and autowired fields are properly structured

The new dependencies and autowired fields are well-organized and align with the PR's objective of handling Iris messages in tests.

Also applies to: 15-16, 19-23, 28-29, 39-43


58-61: LGTM: Session creation helper is well-structured

The helper method follows good practices by using the repository layer and maintaining test data isolation with the TEST_PREFIX.


157-174: LGTM: Test case properly validates text message deletion

The test follows good practices:

  • Creates multiple messages to verify bulk deletion
  • Verifies both session and message deletion
  • Uses appropriate assertions

157-193: Verify database migration impact

The tests effectively verify the cascade deletion behavior, but we should ensure the database migration has been properly applied before running these tests.

@MichaelOwenDyer
Copy link
Contributor

I thought this was fixed with #9567?

@bassner
Copy link
Member

bassner commented Nov 28, 2024

@MichaelOwenDyer The other PR only added a casecase from exercise -> session. We need to cascade all the way from exercise -> session -> message -> content, though, which we didn't so far

@kaancayli
Copy link
Contributor Author

kaancayli commented Nov 28, 2024

I thought this was fixed with #9567?

@MichaelOwenDyer I have migrated my local setup to a new computer and it was not possible to deleting the exercises with an Iris session that includes messages. Other people in the Iris working group reported the same issue. The previous PR solves the issue regarding session, but I can at least confirm from my experience that I was receiving foreign key violations when trying to delete exercises

Copy link
Contributor

@sebastianloose sebastianloose left a comment

Choose a reason for hiding this comment

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

LGTM! I tested locally, and deleting courses now works as expected, even after creating Iris messages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
database Pull requests that update the database. (Added Automatically!). Require a CRITICAL deployment. iris Pull requests that affect the corresponding module ready for review tests
Projects
Status: Work In Progress
Development

Successfully merging this pull request may close these issues.

5 participants