From 1672e9cb703c167a6dd4bce2d1e5d83947debc27 Mon Sep 17 00:00:00 2001 From: Feanil Patel Date: Thu, 19 Nov 2026 15:56:43 -0500 Subject: [PATCH 1/2] feat!: remove the MATLAB API key and the ungraded_response handler The MATLAB integration sent code to the MathWorks hosted service through the XQueue service and got results back on the XQueue callback URL. Neither exists any more, and xblocks-core has dropped MatlabInput and the matlab_api_key argument to LoncapaSystem (https://github.com/openedx/xblocks-core/pull/338). https://github.com/openedx/public-engineering/issues/192 deprecated the MATLAB handling in 2023 because the endpoint it talked to no longer worked. Remove the matlab_api_key field from ProblemBlock and from the inheritance mixin that put it on the course's Advanced Settings, the ungraded_response ajax handler that carried MATLAB's plot output, and the MATLAB wording on the Studio import and export pages. The cms tests that used matlab_api_key as a sample settings field use source_code instead. Existing problems still parse: xblocks-core keeps the tag on CodeInput so learners keep their scores. BREAKING CHANGE: the "Matlab API key" advanced setting is gone from courses and problems. Course exports that carry matlab_api_key still import; the value is dropped. Co-Authored-By: Claude Fable 5.1 --- .../tests/test_downstream_sync_integration.py | 1 - .../contentstore/tests/test_export_git.py | 2 +- cms/lib/xblock/test/test_upstream_sync.py | 10 ++--- cms/templates/export.html | 6 +-- cms/templates/import.html | 2 +- xmodule/capa_block.py | 44 +------------------ xmodule/modulestore/inheritance.py | 9 ---- 7 files changed, 11 insertions(+), 63 deletions(-) diff --git a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py index ffa8b0fa7089..984d9d87c5eb 100644 --- a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py +++ b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py @@ -168,7 +168,6 @@ def assertXmlEqual(self, xml_str_a: str, xml_str_b: str) -> None: # OLX attributes that will appear on capa problems when saved/exported. Excludes "markdown" standard_capa_attributes = """ markdown_edited="false" - matlab_api_key="null" name="null" rerandomize="never" source_code="null" diff --git a/cms/djangoapps/contentstore/tests/test_export_git.py b/cms/djangoapps/contentstore/tests/test_export_git.py index a986b342041d..1556d641f470 100644 --- a/cms/djangoapps/contentstore/tests/test_export_git.py +++ b/cms/djangoapps/contentstore/tests/test_export_git.py @@ -126,7 +126,7 @@ def test_dirty_repo(self): self.course_block.giturl, self.user) # Make arbitrary change to course to make diff - self.course_block.matlab_api_key = 'something' + self.course_block.display_name = 'something' modulestore().update_item(self.course_block, self.user.id) # Touch a file in the directory, export again, and make sure # the test file is gone diff --git a/cms/lib/xblock/test/test_upstream_sync.py b/cms/lib/xblock/test/test_upstream_sync.py index d32f2fb5809a..cc0069bb14c1 100644 --- a/cms/lib/xblock/test/test_upstream_sync.py +++ b/cms/lib/xblock/test/test_upstream_sync.py @@ -63,12 +63,12 @@ def setUp(self): ' force_save_button="false"' ' graceperiod="1d"' ' grading_method="last_attempt"' - ' matlab_api_key="abc"' ' max_attempts="10"' ' rerandomize=""always""' ' show_correctness="never"' ' show_reset_button="false"' ' showanswer="on_correct"' + ' source_code="abc"' ' submission_wait_seconds="10"' ' use_latex_compiler="false"' ' weight="1"' @@ -250,7 +250,7 @@ def test_sync_updates_to_downstream_only_fields(self): assert downstream.upstream_display_name == "Upstream Problem Title V2" assert downstream.display_name == "Upstream Problem Title V2" assert downstream.rerandomize == '"always"' - assert downstream.matlab_api_key == 'abc' + assert downstream.source_code == 'abc' assert not downstream.use_latex_compiler # These fields are "downstream only", so field defaults are preserved, and values are NOT copied from upstream @@ -275,12 +275,12 @@ def test_sync_updates_to_downstream_only_fields(self): ' force_save_button="false"' ' graceperiod=""' ' grading_method="final_attempt"' - ' matlab_api_key="def"' ' max_attempts="11"' ' rerandomize=""per_student""' ' show_correctness="past_due"' ' show_reset_button="false"' ' showanswer="attempted"' + ' source_code="def"' ' submission_wait_seconds="11"' ' use_latex_compiler="true"' ' weight="2"' @@ -304,7 +304,7 @@ def test_sync_updates_to_downstream_only_fields(self): # Modifying synchronized fields are "unsafe" customizations downstream.rerandomize = '"onreset"' - downstream.matlab_api_key = 'hij' + downstream.source_code = 'hij' save_xblock_with_callback(downstream, self.user) # Follow-up sync. @@ -313,7 +313,7 @@ def test_sync_updates_to_downstream_only_fields(self): # "unsafe" customizations are overridden by upstream assert downstream.upstream_display_name == "Upstream Problem Title V3" assert downstream.rerandomize == '"per_student"' - assert downstream.matlab_api_key == 'def' + assert downstream.source_code == 'def' assert downstream.use_latex_compiler # but "safe" customizations survive diff --git a/cms/templates/export.html b/cms/templates/export.html index 44922b5eedb7..d5872c25dc4e 100644 --- a/cms/templates/export.html +++ b/cms/templates/export.html @@ -48,7 +48,7 @@

${_("About Exporting Courses")}

${_("You can export courses and edit them outside of {studio_name}. The exported file is a .tar.gz file (that is, a .tar file compressed with GNU Zip) that contains the course structure and content. You can also re-import courses that you've exported.").format( studio_name=settings.STUDIO_SHORT_NAME )}

-

${Text(_("{em_start}Caution:{em_end} When you export a course, information such as MATLAB API keys, LTI passports, annotation secret token strings, and annotation storage URLs are included in the exported data. If you share your exported files, you may also be sharing sensitive or license-specific information.")).format( +

${Text(_("{em_start}Caution:{em_end} When you export a course, information such as LTI passports, annotation secret token strings, and annotation storage URLs are included in the exported data. If you share your exported files, you may also be sharing sensitive or license-specific information.")).format( em_start=HTML(''), em_end=HTML("") )}

@@ -151,7 +151,7 @@

em_end=HTML("") )}

    -
  • ${_("Values from Advanced Settings, including MATLAB API keys and LTI passports")}
  • +
  • ${_("Values from Advanced Settings, including LTI passports")}
  • ${_("Course Content (all Sections, Sub-sections, and Units)")}
  • ${_("Course Structure")}
  • ${_("Individual Problems")}
  • @@ -192,7 +192,7 @@

    ${_("What content is exported?")}

  • ${_("Course dates")}
  • ${_("Grading policy")}
  • ${_("Any group configurations")}
  • -
  • ${_("Settings on the Advanced Settings page, including MATLAB API keys and LTI passports")}
  • +
  • ${_("Settings on the Advanced Settings page, including LTI passports")}

${_("The following content is not exported.")}

    diff --git a/cms/templates/import.html b/cms/templates/import.html index a711a845c4c0..638f209b9e61 100644 --- a/cms/templates/import.html +++ b/cms/templates/import.html @@ -169,7 +169,7 @@

    ${_("What content is imported?")}

  • ${_("Course dates")}
  • ${_("Grading policy")}
  • ${_("Any group configurations")}
  • -
  • ${_("Settings on the Advanced Settings page, including MATLAB API keys and LTI passports")}
  • +
  • ${_("Settings on the Advanced Settings page, including LTI passports")}

${_("The following content is not imported.")}

    diff --git a/xmodule/capa_block.py b/xmodule/capa_block.py index 770053f04161..2862649ffc4f 100644 --- a/xmodule/capa_block.py +++ b/xmodule/capa_block.py @@ -331,17 +331,6 @@ class _BuiltInProblemBlock( # pylint: disable=too-many-public-methods,too-many- help=_("Source code for LaTeX and Word problems. This feature is not well-supported."), scope=Scope.settings ) use_latex_compiler = Boolean(help=_("Enable LaTeX templates?"), default=False, scope=Scope.settings) - matlab_api_key = String( - display_name=_("Matlab API key"), - help=_( - "Enter the API key provided by MathWorks for accessing the MATLAB Hosted Service. " - "This key is granted for exclusive use by this course for the specified duration. " - "Please do not share the API key with other courses and notify MathWorks immediately " - "if you believe the key is exposed or compromised. To obtain a key for your course, " - "or to report an issue, please contact moocsupport@mathworks.com" - ), - scope=Scope.settings, - ) markdown_edited = Boolean( help=_("Indicates if the problem was edited using the Markdown editor in the Authoring MFE."), scope=Scope.settings, @@ -416,7 +405,6 @@ def handle_ajax(self, dispatch, data): # pylint: disable=too-many-locals "problem_show": self.get_answer, "score_update": self.update_score, "input_ajax": self.handle_input_ajax, - "ungraded_response": self.handle_ungraded_response, } _ = self.runtime.service(self, "i18n").gettext @@ -543,10 +531,6 @@ def non_editable_metadata_fields(self): ProblemBlock.markdown, ProblemBlock.use_latex_compiler, ProblemBlock.show_correctness, - # Temporarily remove the ability to see MATLAB API key in Studio, as - # a pre-cursor to removing it altogether. - # https://github.com/openedx/public-engineering/issues/192 - ProblemBlock.matlab_api_key, ] ) return non_editable_fields @@ -640,7 +624,6 @@ def max_score(self): resources_fs=self.runtime.resources_fs, seed=None, xqueue=None, - matlab_api_key=None, ) try: lcp = LoncapaProblem( @@ -687,7 +670,7 @@ def generate_report_data(self, user_state_iterator, limit_responses=None): capa_system = LoncapaSystem( ajax_url=None, # TODO set anonymous_student_id to the anonymous ID of the user which answered each problem - # Anonymous ID is required for Matlab, CodeResponse, and some custom problems that include + # Anonymous ID is required for CodeResponse and some custom problems that include # '$anonymous_student_id' in their XML. # For the purposes of this report, we don't need to support those use cases. anonymous_student_id=None, @@ -700,7 +683,6 @@ def generate_report_data(self, user_state_iterator, limit_responses=None): resources_fs=self.runtime.resources_fs, seed=1, xqueue=None, - matlab_api_key=None, ) _ = capa_system.i18n.gettext @@ -864,7 +846,6 @@ def new_lcp(self, state, text=None): resources_fs=self.runtime.resources_fs, seed=seed, # Why do we do this if we have self.seed? xqueue=None if is_studio else xqueue_service, - matlab_api_key=self.matlab_api_key, ) return LoncapaProblem( @@ -1541,29 +1522,6 @@ def update_score(self, data): return {} # No AJAX return is needed - def handle_ungraded_response(self, data): - """ - Delivers a response from the XQueue to the capa problem - - The score of the problem will not be updated - - Args: - - data (dict) must contain keys: - queuekey - a key specific to this response - xqueue_body - the body of the response - Returns: - empty dictionary - - No ajax return is needed, so an empty dict is returned - """ - queuekey = data["queuekey"] - score_msg = data["xqueue_body"] - - # pass along the xqueue message to the problem - self.lcp.ungraded_response(score_msg, queuekey) - self.set_state_from_lcp() - return {} - def handle_input_ajax(self, data): """ Handle ajax calls meant for a particular input in the problem diff --git a/xmodule/modulestore/inheritance.py b/xmodule/modulestore/inheritance.py index 3968972d1888..6362ef731a38 100644 --- a/xmodule/modulestore/inheritance.py +++ b/xmodule/modulestore/inheritance.py @@ -147,15 +147,6 @@ class InheritanceMixin(XBlockMixin): help=_("Enter the maximum number of times a student can try to answer problems. By default, Maximum Attempts is set to null, meaning that students have an unlimited number of attempts for problems. You can override this course-wide setting for individual problems. However, if the course-wide setting is a specific number, you cannot set the Maximum Attempts for individual problems to unlimited."), # pylint: disable=line-too-long values={"min": 0}, scope=Scope.settings ) - matlab_api_key = String( - display_name=_("Matlab API key"), - help=_("Enter the API key provided by MathWorks for accessing the MATLAB Hosted Service. " - "This key is granted for exclusive use in this course for the specified duration. " - "Do not share the API key with other courses. Notify MathWorks immediately " - "if you believe the key is exposed or compromised. To obtain a key for your course, " - "or to report an issue, please contact moocsupport@mathworks.com"), - scope=Scope.settings - ) # This is should be scoped to content, but since it's defined in the policy # file, it is currently scoped to settings. user_partitions = UserPartitionList( From 33c21d2a55a0e7605af07c50a6d253c858dcbb87 Mon Sep 17 00:00:00 2001 From: Feanil Patel Date: Thu, 19 Nov 2026 15:58:58 -0500 Subject: [PATCH 2/2] feat!: remove the XQueue service settings, callback URL and waffle flag The XQueue service is deprecated and its repo archived (https://github.com/openedx/public-engineering/issues/286). The LMS queues external grader submissions in edx-submissions and serves the API that xqueue-watcher polls, and scores come back through the EXTERNAL_GRADER_SCORE_SUBMITTED signal. Nothing posts to the service any more: xblocks-core's XQueueInterface only hands submissions to edx-submissions (https://github.com/openedx/xblocks-core/pull/338). Remove what only existed for the service: the XQUEUE_INTERFACE setting and its mock and test values, XQUEUE_PORT, the xqueue_callback view and its two URL patterns, XQueueService's HTTP setup and construct_callback, and the send_to_submission_course.enable course flag that picked between the two backends. XQUEUE_WAITTIME_BETWEEN_REQUESTS stays: it is the wait a learner has to observe between submissions to a queued problem. BREAKING CHANGE: XQUEUE_INTERFACE is no longer read. The send_to_submission_course.enable waffle flag is gone; every course's external grader submissions now go to edx-submissions. The /courses//xqueue/// callback URL is gone. Co-Authored-By: Claude Fable 5.1 --- cms/envs/mock.yml | 8 -- lms/djangoapps/courseware/block_render.py | 44 +-------- .../courseware/tests/test_block_render.py | 80 ---------------- .../tests/test_submitting_problems.py | 15 ++- lms/envs/mock.yml | 8 -- lms/envs/test.py | 8 -- lms/urls.py | 17 ---- .../core/djangoapps/xblock/runtime/shims.py | 1 - openedx/envs/common.py | 10 +- openedx/envs/test.py | 1 - xmodule/services.py | 69 +------------- xmodule/tests/test_capa_block.py | 93 +++++-------------- xmodule/tests/test_services.py | 41 +------- 13 files changed, 40 insertions(+), 355 deletions(-) diff --git a/cms/envs/mock.yml b/cms/envs/mock.yml index 3b219071ddf1..a43996e0eda9 100644 --- a/cms/envs/mock.yml +++ b/cms/envs/mock.yml @@ -792,14 +792,6 @@ XBLOCK_SETTINGS: ScormXBlock: S3_BUCKET_NAME: scorm STORAGE_FUNC: storage.s3 -XQUEUE_INTERFACE: - basic_auth: - - user - - pass - django_auth: - password: pass - username: user - url: https://xqueue.localhost YOUTUBE_API_KEY: test_youtube ZENDESK_API_KEY: test_zendesk ZENDESK_CUSTOM_FIELDS: diff --git a/lms/djangoapps/courseware/block_render.py b/lms/djangoapps/courseware/block_render.py index e3ea6a288902..9ee4f866cd8b 100644 --- a/lms/djangoapps/courseware/block_render.py +++ b/lms/djangoapps/courseware/block_render.py @@ -16,7 +16,7 @@ from django.contrib.auth.models import AnonymousUser, User # pylint: disable=imported-auth-user from django.core.cache import cache from django.db import transaction -from django.http import Http404, HttpResponse, HttpResponseForbidden +from django.http import Http404, HttpResponseForbidden from django.middleware.csrf import CsrfViewMiddleware from django.template.context_processors import csrf from django.urls import reverse @@ -690,48 +690,6 @@ def load_single_xblock(request, user_id, course_id, usage_key_string, course=Non @csrf_exempt -def xqueue_callback(request, course_id, userid, mod_id, dispatch): - ''' - Entry point for graded results from the queueing system. - ''' - data = request.POST.copy() - - # Test xqueue package, which we expect to be: - # xpackage = {'xqueue_header': json.dumps({'lms_key':'secretkey',...}), - # 'xqueue_body' : 'Message from grader'} - for key in ['xqueue_header', 'xqueue_body']: - if key not in data: - raise Http404 - - header = json.loads(data['xqueue_header']) - if not isinstance(header, dict) or 'lms_key' not in header: - raise Http404 - - course_key = CourseKey.from_string(course_id) - - with modulestore().bulk_operations(course_key): - course = modulestore().get_course(course_key, depth=0) - - instance = load_single_xblock(request, userid, course_id, mod_id, course=course) - - # Transfer 'queuekey' from xqueue response header to the data. - # This is required to use the interface defined by 'handle_ajax' - data.update({'queuekey': header['lms_key']}) - - # We go through the "AJAX" path - # So far, the only dispatch from xqueue will be 'score_update' - try: - # Can ignore the return value--not used for xqueue_callback - instance.handle_ajax(dispatch, data) - # Save any state that has changed to the underlying KeyValueStore - instance.save() - except: - log.exception("error processing ajax call") - raise - - return HttpResponse("") - - @csrf_exempt @xframe_options_exempt @transaction.non_atomic_requests diff --git a/lms/djangoapps/courseware/tests/test_block_render.py b/lms/djangoapps/courseware/tests/test_block_render.py index 409b50a2164a..64efa354af50 100644 --- a/lms/djangoapps/courseware/tests/test_block_render.py +++ b/lms/djangoapps/courseware/tests/test_block_render.py @@ -269,18 +269,6 @@ def setUp(self): # Construct a mock block for the modulestore to return self.mock_block = MagicMock() self.mock_block.id = 1 - self.dispatch = 'score_update' - - # Construct a 'standard' xqueue_callback url - self.callback_url = reverse( - 'xqueue_callback', - kwargs=dict( - course_id=str(self.course_key), - userid=str(self.mock_user.id), - mod_id=self.mock_block.id, - dispatch=self.dispatch - ) - ) def tearDown(self): OverrideFieldData.provider_classes = None @@ -317,63 +305,6 @@ def test_block_render_with_jump_to_id(self): # note if the URL mapping changes then this assertion will break assert '/courses/' + str(self.course_key) + '/jump_to_id/vertical_test' in html - def test_xqueue_callback_success(self): - """ - Test for happy-path xqueue_callback - """ - fake_key = 'fake key' - xqueue_header = json.dumps({'lms_key': fake_key}) - data = { - 'xqueue_header': xqueue_header, - 'xqueue_body': 'hello world', - } - - # Patch getmodule to return our mock block - with patch('lms.djangoapps.courseware.block_render.load_single_xblock', return_value=self.mock_block): - # call xqueue_callback with our mocked information - request = self.request_factory.post(self.callback_url, data) - render.xqueue_callback( - request, - str(self.course_key), - self.mock_user.id, - self.mock_block.id, - self.dispatch - ) - - # Verify that handle ajax is called with the correct data - request.POST._mutable = True # pylint: disable=protected-access - request.POST['queuekey'] = fake_key - self.mock_block.handle_ajax.assert_called_once_with(self.dispatch, request.POST) - - def test_xqueue_callback_missing_header_info(self): - data = { - 'xqueue_header': '{}', - 'xqueue_body': 'hello world', - } - - with patch('lms.djangoapps.courseware.block_render.load_single_xblock', return_value=self.mock_block): - # Test with missing xqueue data - with pytest.raises(Http404): # noqa: PT012 - request = self.request_factory.post(self.callback_url, {}) - render.xqueue_callback( - request, - str(self.course_key), - self.mock_user.id, - self.mock_block.id, - self.dispatch - ) - - # Test with missing xqueue_header - with pytest.raises(Http404): # noqa: PT012 - request = self.request_factory.post(self.callback_url, data) - render.xqueue_callback( - request, - str(self.course_key), - self.mock_user.id, - self.mock_block.id, - self.dispatch - ) - def _get_dispatch_url(self): """Helper to get dispatch URL for testing xblock callback.""" return reverse( @@ -612,17 +543,6 @@ def setUp(self): # Construct a mock block for the modulestore to return self.mock_block = MagicMock() self.mock_block.id = 1 - self.dispatch = 'score_update' - - # Construct a 'standard' xqueue_callback url - self.callback_url = reverse( - 'xqueue_callback', kwargs={ - 'course_id': str(self.course_key), - 'userid': str(self.mock_user.id), - 'mod_id': self.mock_block.id, - 'dispatch': self.dispatch - } - ) def _mock_file(self, name='file', size=10): """Create a mock file object for testing uploads""" diff --git a/lms/djangoapps/courseware/tests/test_submitting_problems.py b/lms/djangoapps/courseware/tests/test_submitting_problems.py index 3df373936eb9..8cba5ee202d6 100644 --- a/lms/djangoapps/courseware/tests/test_submitting_problems.py +++ b/lms/djangoapps/courseware/tests/test_submitting_problems.py @@ -28,7 +28,7 @@ OptionResponseXMLFactory, SchematicResponseXMLFactory, ) -from xblock_problem.capa.xqueue_interface import XQueueInterface +from xblock_problem.capa.xqueue_submission import XQueueInterfaceSubmission from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.student.models import CourseEnrollment, anonymous_id_for_user @@ -789,7 +789,7 @@ def problem_setup(self, name, files): # re-fetch the course from the database so the object is up to date self.refresh_course() - @patch.object(XQueueInterface, '_http_post') + @patch.object(XQueueInterfaceSubmission, 'send_to_submission') def test_three_files(self, mock_xqueue_post): # Open the test files, and arrange to close them later. filenames = "prog1.py prog2.py prog3.py" @@ -801,19 +801,18 @@ def test_three_files(self, mock_xqueue_post): self.addCleanup(fileobj.close) self.problem_setup("the_problem", filenames) - mock_xqueue_post.return_value = (0, "ok") + mock_xqueue_post.return_value = {} resp = self.submit_question_answer("the_problem", {'2_1': fileobjs}) assert resp.status_code == 200 json_resp = json.loads(resp.content.decode('utf-8')) assert json_resp['success'] == 'incorrect' - # See how post got called. + # See how the hand-off to edx-submissions got called: header, body, queue key, files. assert mock_xqueue_post.call_count == 1 - args, kwargs = mock_xqueue_post.call_args - assert len(args) == 2 - assert args[0].endswith('/submit/') - self.assertEqual(list(kwargs['files'].keys()), filenames.split()) # noqa: PT009 + args, _ = mock_xqueue_post.call_args + assert len(args) == 4 + self.assertEqual(list(args[3].keys()), filenames.split()) # noqa: PT009 @UseUnsafeCodejail() diff --git a/lms/envs/mock.yml b/lms/envs/mock.yml index 3c52f27e0209..5c62aee36020 100644 --- a/lms/envs/mock.yml +++ b/lms/envs/mock.yml @@ -1218,14 +1218,6 @@ XBLOCK_SETTINGS: ScormXBlock: S3_BUCKET_NAME: scorm STORAGE_FUNC: openedxscorm.storage.s3 -XQUEUE_INTERFACE: - basic_auth: - - user - - pass - django_auth: - password: pass - username: user - url: http://localhost:18040 X_FRAME_OPTIONS: DENY YOUTUBE_API_KEY: test_youtube_api_key ZENDESK_API_KEY: '' diff --git a/lms/envs/test.py b/lms/envs/test.py index 392acc992302..617f0e5f55d9 100644 --- a/lms/envs/test.py +++ b/lms/envs/test.py @@ -66,14 +66,6 @@ USE_I18N = True LANGUAGE_CODE = 'en' # tests assume they will get English. -XQUEUE_INTERFACE = { - "url": "http://sandbox-xqueue.edx.org", - "django_auth": { - "username": "lms", - "password": "***REMOVED***" - }, - "basic_auth": ('anant', 'agarwal'), -} XQUEUE_WAITTIME_BETWEEN_REQUESTS = 5 # seconds # Don't rely on a real staff grading backend diff --git a/lms/urls.py b/lms/urls.py index 0e624d44981a..72e509569cb8 100644 --- a/lms/urls.py +++ b/lms/urls.py @@ -23,7 +23,6 @@ handle_xblock_callback, handle_xblock_callback_noauth, xblock_view, - xqueue_callback, ) from lms.djangoapps.courseware.masquerade import MasqueradeView from lms.djangoapps.courseware.views import views as courseware_views @@ -354,22 +353,6 @@ path('', include(('openedx.core.djangoapps.xblock.rest_api.urls', 'openedx.core.djangoapps.xblock'), namespace='xblock_api')), - re_path( - r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format( # noqa: UP032 - settings.COURSE_ID_PATTERN, - ), - xqueue_callback, - name='xqueue_callback', - ), - - re_path( - r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format( # noqa: UP032 - settings.COURSE_ID_PATTERN, - ), - xqueue_callback, - name='callback_submission', - ), - # TODO: These views need to be updated before they work path('calculate', util_views.calculate), diff --git a/openedx/core/djangoapps/xblock/runtime/shims.py b/openedx/core/djangoapps/xblock/runtime/shims.py index 8d1e22c64c01..72558daa6410 100644 --- a/openedx/core/djangoapps/xblock/runtime/shims.py +++ b/openedx/core/djangoapps/xblock/runtime/shims.py @@ -238,7 +238,6 @@ def xqueue(self): # TODO: Refactor capa to access this directly, don't bother the runtime. Then remove it from here. return { 'interface': None, - 'construct_callback': None, 'default_queuename': None, 'waittime': 5, # seconds; should come from settings.XQUEUE_WAITTIME_BETWEEN_REQUESTS } diff --git a/openedx/envs/common.py b/openedx/envs/common.py index a7c8bd8a790a..085510715c58 100644 --- a/openedx/envs/common.py +++ b/openedx/envs/common.py @@ -1463,16 +1463,8 @@ def add_optional_apps(optional_apps, installed_apps): ###################### CAPA External Code Evaluation ####################### -# Used with XQueue +# Seconds a learner must wait between submissions to a problem graded by an external grader. XQUEUE_WAITTIME_BETWEEN_REQUESTS = 5 # seconds -XQUEUE_INTERFACE = { - 'url': 'http://localhost:18040', - 'basic_auth': ['edx', 'edx'], - 'django_auth': { - 'username': 'lms', - 'password': 'password' - } -} ################################### CSRF ################################### diff --git a/openedx/envs/test.py b/openedx/envs/test.py index 8c0fafe6c372..a7ba4ea244c6 100644 --- a/openedx/envs/test.py +++ b/openedx/envs/test.py @@ -101,7 +101,6 @@ def make_staticfile_dirs(settings): # These ports are carefully chosen so that if the browser needs to # access them, they will be available through the SauceLabs SSH tunnel -XQUEUE_PORT = 8040 YOUTUBE_PORT = 8031 LTI_PORT = 8765 VIDEO_SOURCE_PORT = 8777 diff --git a/xmodule/services.py b/xmodule/services.py index 068cf2c9f39c..3ed117e126de 100644 --- a/xmodule/services.py +++ b/xmodule/services.py @@ -10,10 +10,8 @@ from config_models.models import ConfigurationModel from django.conf import settings -from django.urls import reverse from edx_when.field_data import DateLookupFieldData from eventtracking import tracker -from requests.auth import HTTPBasicAuth from xblock.reference.plugins import Service from xblock.runtime import KvsFieldData from xblock_problem.capa.xqueue_interface import XQueueInterface @@ -25,7 +23,6 @@ from lms.djangoapps.grades.api import signals as grades_signals from lms.djangoapps.lms_xblock.field_data import LmsFieldData from lms.djangoapps.lms_xblock.models import XBlockAsidesConfig -from openedx.core.djangoapps.waffle_utils import CourseWaffleFlag from xmodule.modulestore.django import modulestore if TYPE_CHECKING: @@ -316,22 +313,9 @@ def _handle_deprecated_progress_event(self, block, event): self.completion_service.submit_completion(block.scope_ids.usage_id, 1.0) -# .. toggle_name: send_to_submission_course.enable -# .. toggle_implementation: CourseWaffleFlag -# .. toggle_description: Enables use of the submissions service instead of legacy xqueue for course problem submissions. -# .. toggle_default: False -# .. toggle_use_cases: opt_in -# .. toggle_creation_date: 2024-04-03 -# .. toggle_expiration_date: 2025-08-12 -# .. toggle_will_remain_in_codebase: True -# .. toggle_tickets: none -# .. toggle_status: supported -SEND_TO_SUBMISSION_COURSE_FLAG = CourseWaffleFlag("send_to_submission_course.enable", __name__) - - class XQueueService: """ - XBlock service providing an interface to the XQueue service. + XBlock service that queues external grader submissions in edx-submissions. Args: block: The `ProblemBlock` instance. @@ -339,19 +323,7 @@ class XQueueService: def __init__(self, block: "ProblemBlock"): self._block = block - - basic_auth = settings.XQUEUE_INTERFACE.get("basic_auth") - requests_auth = HTTPBasicAuth(*basic_auth) if basic_auth else None - - use_submission = self.use_edx_submissions_for_xqueue() - - self._interface = XQueueInterface( - settings.XQUEUE_INTERFACE["url"], - settings.XQUEUE_INTERFACE["django_auth"], - requests_auth, - block=block, - use_submission_service=use_submission, - ) + self._interface = XQueueInterface(block) @property def interface(self): @@ -360,41 +332,6 @@ def interface(self): """ return self._interface - def use_edx_submissions_for_xqueue(self) -> bool: - """ - Determines whether edx-submissions should be used instead of legacy XQueue. - - This helper abstracts the toggle logic so that the rest of the codebase is not tied - to specific feature flag mechanics or rollout strategies. - - Returns: - bool: True if edx-submissions should be used, False otherwise. - """ - return SEND_TO_SUBMISSION_COURSE_FLAG.is_enabled(self._block.scope_ids.usage_id.context_key) - - def construct_callback(self, dispatch: str = "score_update") -> str: - """ - Return a fully qualified callback URL for the external queueing system. - """ - course_key = self._block.scope_ids.usage_id.context_key - userid = str(self._block.scope_ids.user_id) - mod_id = str(self._block.scope_ids.usage_id) - - callback_type = "xqueue_callback" - - relative_xqueue_callback_url = reverse( - callback_type, - kwargs={ - "course_id": str(course_key), - "userid": userid, - "mod_id": mod_id, - "dispatch": dispatch, - }, - ) - - xqueue_callback_url_prefix = settings.XQUEUE_INTERFACE.get("callback_url", settings.LMS_ROOT_URL) - return f"{xqueue_callback_url_prefix}{relative_xqueue_callback_url}" - @property def default_queuename(self) -> str: """ @@ -406,6 +343,6 @@ def default_queuename(self) -> str: @property def waittime(self) -> int: """ - Returns the number of seconds to wait in between calls to XQueue. + Returns the number of seconds a learner must wait between submissions to a queued problem. """ return settings.XQUEUE_WAITTIME_BETWEEN_REQUESTS diff --git a/xmodule/tests/test_capa_block.py b/xmodule/tests/test_capa_block.py index bde2c35f7241..59bd19828fc8 100644 --- a/xmodule/tests/test_capa_block.py +++ b/xmodule/tests/test_capa_block.py @@ -14,7 +14,6 @@ import ddt import pytest -import requests import webob from codejail.safe_exec import SafeExecException from django.test import override_settings @@ -30,7 +29,7 @@ from xblock_problem.capa.correctmap import CorrectMap from xblock_problem.capa.responsetypes import LoncapaProblemError, ResponseError, StudentInputError from xblock_problem.capa.testing.codejail import UseUnsafeCodejail -from xblock_problem.capa.xqueue_interface import XQueueInterface +from xblock_problem.capa.xqueue_submission import XQueueInterfaceSubmission from lms.djangoapps.courseware.user_state_client import XBlockUserState from openedx.core.djangolib.testing.utils import skip_unless_lms @@ -267,21 +266,6 @@ def test_showanswer_default(self): problem = CapaFactory.create() assert not problem.answer_available() - @ddt.data( - (requests.exceptions.ReadTimeout, (1, "failed to read from the server")), - (requests.exceptions.ConnectionError, (1, "cannot connect to server")), - ) - @ddt.unpack - def test_xqueue_request_exception(self, exception, result): - """ - Makes sure that platform will raise appropriate exception in case of - connect/read timeout(s) to request to xqueue - """ - xqueue_interface = XQueueInterface("http://example.com/xqueue", Mock()) - with patch.object(xqueue_interface.session, "post", side_effect=exception): - response = xqueue_interface._http_post("http://some/fake/url", {}) # pylint: disable=protected-access - assert response == result - def test_showanswer_attempted(self): """Check answer availability changes after attempting the problem.""" problem = CapaFactory.create(showanswer="attempted") @@ -1239,9 +1223,9 @@ def test_submit_problem_queued(self): assert block.attempts == 1 @pytest.mark.django_db - @patch.object(XQueueInterface, "_http_post") + @patch.object(XQueueInterfaceSubmission, "send_to_submission") def test_submit_problem_with_files(self, mock_xqueue_post): - """Verify file-upload submissions are sent correctly to XQueue via submit_problem.""" + """Verify file-upload submissions reach edx-submissions via submit_problem.""" # Check a problem with uploaded files, using the submit_problem API. # The files we'll be uploading. @@ -1253,8 +1237,8 @@ def test_submit_problem_with_files(self, mock_xqueue_post): block = CapaFactoryWithFiles.create() - # Mock the XQueueInterface post method - mock_xqueue_post.return_value = (0, "ok") + # Mock the hand-off to edx-submissions + mock_xqueue_post.return_value = {} # Create a request dictionary for submit_problem. get_request_dict = { @@ -1264,51 +1248,24 @@ def test_submit_problem_with_files(self, mock_xqueue_post): block.submit_problem(get_request_dict) - # _http_post is called like this: - # _http_post( - # 'http://example.com/xqueue/xqueue/submit/', - # { - # 'xqueue_header': - # '{"lms_key": "df34fb702620d7ae892866ba57572491", ' - # '"lms_callback_url": "/", ' - # '"queue_name": "BerkeleyX-cs188x"}', - # 'xqueue_body': - # '{"student_info": "{\\"anonymous_student_id\\": ' - # '\\"student\\", \\"submission_time\\": ' - # '\\"20131117183318\\"}", ' - # '"grader_payload": "{\\"project\\": \\"p3\\"}", ' - # '"student_response": ""}', - # }, - # files={ - # path( - # u'/home/ned/edx/edx-platform/common/test/data/uploads/' - # 'asset.html' - # ): - # , - # path( - # u'/home/ned/edx/edx-platform/common/test/data/uploads/' - # 'image.jpg' - # ): - # , - # path( - # u'/home/ned/edx/edx-platform/common/test/data/uploads/' - # 'textbook.pdf' - # ): - # , - # }, + # send_to_submission is called like this: + # send_to_submission( + # '{"lms_key": "df34fb702620d7ae892866ba57572491", "queue_name": "BerkeleyX-cs188x"}', + # '{"student_info": "{\\"anonymous_student_id\\": \\"student\\", ' + # '\\"submission_time\\": \\"20131117183318\\"}", ' + # '"grader_payload": "{\\"project\\": \\"p3\\"}", "student_response": ""}', + # "df34fb702620d7ae892866ba57572491", + # {"/path/to/prog1.py": , ...}, # ) assert mock_xqueue_post.call_count == 1 - _, kwargs = mock_xqueue_post.call_args - self.assertCountEqual(fpaths, list(kwargs["files"].keys())) # noqa: PT009 - for fpath, fileobj in kwargs["files"].items(): + files = mock_xqueue_post.call_args.args[3] + self.assertCountEqual(fpaths, list(files.keys())) # noqa: PT009 + for fpath, fileobj in files.items(): assert fpath == fileobj.name @pytest.mark.django_db - @patch.object(XQueueInterface, "_http_post") + @patch.object(XQueueInterfaceSubmission, "send_to_submission") def test_submit_problem_with_files_as_xblock(self, mock_xqueue_post): """Verify file-upload submissions work correctly via the XBlock handler API.""" # Check a problem with uploaded files, using the XBlock API. @@ -1323,8 +1280,8 @@ def test_submit_problem_with_files_as_xblock(self, mock_xqueue_post): block = CapaFactoryWithFiles.create() - # Mock the XQueueInterface post method - mock_xqueue_post.return_value = (0, "ok") + # Mock the hand-off to edx-submissions + mock_xqueue_post.return_value = {} # Create a webob Request with the files uploaded. post_data = [] @@ -1336,9 +1293,9 @@ def test_submit_problem_with_files_as_xblock(self, mock_xqueue_post): block.handle("xmodule_handler", request, "problem_check") assert mock_xqueue_post.call_count == 1 - _, kwargs = mock_xqueue_post.call_args - self.assertCountEqual(fnames, list(kwargs["files"].keys())) # noqa: PT009 - for fpath, fileobj in kwargs["files"].items(): + files = mock_xqueue_post.call_args.args[3] + self.assertCountEqual(fnames, list(files.keys())) # noqa: PT009 + for fpath, fileobj in files.items(): assert fpath == fileobj.name def test_submit_problem_error(self): @@ -3978,7 +3935,7 @@ def test_rerandomized_inputs(self): } @pytest.mark.django_db - @patch.object(XQueueInterface, "_http_post") + @patch.object(XQueueInterfaceSubmission, "send_to_submission") def test_file_inputs(self, mock_xqueue_post): """Verify tracking data for file submission and custom response inputs.""" fnames = ["prog1.py", "prog2.py", "prog3.py"] @@ -3991,8 +3948,8 @@ def test_file_inputs(self, mock_xqueue_post): factory = CapaFactoryWithFiles block = factory.create() - # Mock the XQueueInterface post method - mock_xqueue_post.return_value = (0, "ok") + # Mock the hand-off to edx-submissions + mock_xqueue_post.return_value = {} answer_input_dict = { CapaFactoryWithFiles.input_key(response_num=2): fileobjs, diff --git a/xmodule/tests/test_services.py b/xmodule/tests/test_services.py index 4015cbd45b4d..19e77d03ad56 100644 --- a/xmodule/tests/test_services.py +++ b/xmodule/tests/test_services.py @@ -3,7 +3,7 @@ """ import unittest from unittest import TestCase, mock -from unittest.mock import Mock, patch +from unittest.mock import Mock import ddt import pytest @@ -184,44 +184,9 @@ def setUp(self): self.service = XQueueService(self.block) def test_interface(self): - """Test that the `XQUEUE_INTERFACE` settings are passed from the service to the interface.""" + """The service wraps an XQueueInterface for the block.""" assert isinstance(self.service.interface, XQueueInterface) - assert self.service.interface.url == "http://sandbox-xqueue.edx.org" - assert self.service.interface.auth["username"] == "lms" - assert self.service.interface.auth["password"] == "***REMOVED***" - assert self.service.interface.session.auth.username == "anant" - assert self.service.interface.session.auth.password == "agarwal" - - @patch("xmodule.services.XQueueService.use_edx_submissions_for_xqueue", return_value=True) - def test_construct_callback_with_flag_enabled(self, mock_flag): # pylint: disable=unused-argument - """Test construct_callback when the waffle flag is enabled.""" - self.service = XQueueService(self.block) - usage_id = self.block.scope_ids.usage_id - course_id = str(usage_id.course_key) - callback_url = f"courses/{course_id}/xqueue/user1/{usage_id}" - - assert self.service.construct_callback() == f"{settings.LMS_ROOT_URL}/{callback_url}/score_update" - assert self.service.construct_callback("alt_dispatch") == ( - f"{settings.LMS_ROOT_URL}/{callback_url}/alt_dispatch" - ) - - custom_callback_url = "http://alt.url" - with override_settings(XQUEUE_INTERFACE={**settings.XQUEUE_INTERFACE, "callback_url": custom_callback_url}): - assert self.service.construct_callback() == f"{custom_callback_url}/{callback_url}/score_update" - - @patch("xmodule.services.XQueueService.use_edx_submissions_for_xqueue", return_value=False) - def test_construct_callback_with_flag_disabled(self, mock_flag): # pylint: disable=unused-argument - """Test construct_callback when the waffle flag is disabled.""" - self.service = XQueueService(self.block) - usage_id = self.block.scope_ids.usage_id - callback_url = f"courses/{usage_id.context_key}/xqueue/user1/{usage_id}" - - assert self.service.construct_callback() == f"{settings.LMS_ROOT_URL}/{callback_url}/score_update" - assert self.service.construct_callback("alt_dispatch") == f"{settings.LMS_ROOT_URL}/{callback_url}/alt_dispatch" - - custom_callback_url = "http://alt.url" - with override_settings(XQUEUE_INTERFACE={**settings.XQUEUE_INTERFACE, "callback_url": custom_callback_url}): - assert self.service.construct_callback() == f"{custom_callback_url}/{callback_url}/score_update" + assert self.service.interface.block is self.block def test_default_queuename(self): """Check the format of the default queue name."""