56 Commits

Author SHA1 Message Date
Irtaza Akram
76018183d4 Use runtime-provided XQueueService instead of constructing it in ProblemBlock (#37998)
* fix: move xqueue services
2026-02-19 11:02:00 +05:00
Irtaza Akram
8b5a22ea3a fix: deprecate enable_grading_method_in_problems (#37811) 2026-01-29 12:11:51 +05:00
Irtaza Akram
5b1951228e refactor: Move score_render to lms/grades (#37884)
* fix: move score_render to lms
2026-01-21 17:13:33 +05:00
Tarun Tak
f841763640 chore: use zoneinfo instead of pytz 2026-01-09 11:43:33 -05:00
Irtaza Akram
d29b0473f4 fix: align pylint fixes in edx-platform Problem XBlock with extracted xblocks-contrib/problem (#37758)
* fix: pylint issues for problem xblock
2026-01-07 16:39:11 +05:00
Irtaza Akram
fd33d80fb7 fix: autoformat problem block template files using djlint (#37760) 2026-01-06 17:55:30 +05:00
Jesus Balderrama
2637cc6b0f feat(numericalInput): endpoint added to validate a numerical input (#37677)
To be used in the visual Problem editor to validate numeric input. 

Part of: https://github.com/openedx/frontend-app-authoring/issues/1680
2025-12-16 17:23:31 -05:00
Leonardo Beroes
70ea641c99 feat: Improve robust score rendering with event-based architecture
This commit implements a comprehensive solution for test score integration in the
enhancement system along with improvements to the score rendering mechanism. Key
changes include:

- Add event handler for rendering blocks with edx-submissions scores
- Implement event-based mechanism to render XBlocks with scoring data
- Create signal handlers in handlers.py to process external grader scores
- Develop specialized XBlock loader for rendering without HTTP requests
- Add queue_key propagation across the submission pipeline
- Register submission URLs in LMS routing configuration
- Add complete docstrings to score render module for better code maintainability
- Add ADR for XBlock rendering with external grader integration
- Add openedx-events fork branch as a dependency in testing.in
- Upgrade edx submission dependency

These changes support the migration from traditional XQueue callback HTTP requests
to a more robust event-based architecture, improving performance and reliability
when processing submission scores. The included ADR documents the architectural
decision and implementation approach for this significant improvement to the
external grading workflow.
2025-12-15 09:01:40 -05:00
Irtaza Akram
99c6e901d9 Convert Problem Block Mako Templates to Django Templates (#37570)
* fix: convert mako to django templates for problem block

* fix: pylint issues
2025-12-09 19:29:06 +05:00
Irtaza Akram
c3e85426cb Autoformat Problem XBlock Source Files for Consistency (2/2) (#37487)
* fix: run prettier on problem block code

* fix: codeql issues
2025-12-08 20:01:42 +05:00
Irtaza Akram
1945b12769 Autoformat Problem XBlock Source Files for Consistency (1/2) (#37476)
* fix: run formatter black and isort

* fix: linting, pydocstyle, xsslint and security issues
2025-12-05 18:31:45 +05:00
Kyle McCormick
834cb9482d refactor: rename ModuleStore runtimes now that XModules are gone (#35523)
* Consolidates and renames the runtime used as a base for all the others:
  * Before: `xmodule.x_module:DescriptorSystem` and
            `xmodule.mako_block:MakoDescriptorSystem`.
  * After:  `xmodule.x_module:ModuleStoreRuntime`.

* Co-locates and renames the runtimes for importing course OLX:
  * Before: `xmodule.x_module:XMLParsingSystem` and
            `xmodule.modulestore.xml:ImportSystem`.
  * After:  `xmodule.modulestore.xml:XMLParsingModuleStoreRuntime` and
            `xmodule.modulestore.xml:XMLImportingModuleStoreRuntime`.
  * Note: I would have liked to consolidate these, but it would have
          involved nontrivial test refactoring.

* Renames the stub Old Mongo runtime:
  * Before: `xmodule.modulestore.mongo.base:CachingDescriptorSystem`.
  * After: `xmodule.modulestore.mongo.base:OldModuleStoreRuntime`.

* Renames the Split Mongo runtime, the which is what runs courses in LMS and CMS:
  * Before: `xmodule.modulestore.split_mongo.caching_descriptor_system:CachingDescriptorSystem`.
  * After: `xmodule.modulestore.split_mongo.runtime:SplitModuleStoreRuntime`.

* Renames some of the dummy runtimes used only in unit tests.
2025-10-29 15:46:07 -04:00
Tim McCormack
447fd0b6cb feat: Upgrade to codejail 4.0.0 (#36916)
This brings an important security improvement -- codejail won't default to
running in unsafe mode, which can happen if certain configuration errors
are present.

Properly configured installations shouldn't be affected. We just need to
adjust some unit tests to opt into unsafe mode.

Changes:

- Update `edx-codejail` dependency to [version 4.0.0](https://github.com/openedx/codejail/blob/master/CHANGELOG.rst#400---2025-06-13)
- Define a `use_unsafe_codejail` decorator that allows running a unit test (or entire TestCase class) in unsafe mode
- Use that decorator as needed, based on which tests started failing
2025-06-17 09:33:52 -04:00
Daniel Wong
204a1eb438 test: test_capa_system helper function replaced by mock_capa_system 2025-05-13 14:45:57 -06:00
Daniel Wong
77eb6e8254 fix: use geom_type instead of type for Shapely objects 2025-05-13 14:45:57 -06:00
Tim McCormack
4c462918e8 fix: Pass limit overrides context to codejail execution in all places (#36685)
Some of the calls to `safe_exec` were missing the `limit_overrides_context`
parameter. This normally conveys the course key to codejail so that we can
give some courses different resource limits, but it's also valuable for
diagnosing codejail issues in logs and other telemetry.

I wasn't able to test all of these paths manually, but the utility function
`get_course_id_from_capa_block` will swallow errors, so the situation
should be no worse if the `LoncapaResponse.capa_block` field has something
unexpected.
2025-05-08 16:55:57 -04:00
Tim McCormack
d5a273ce2f feat!: Expand codejail darklaunch normalizers; append by default (#36682)
For darklaunch comparisons where the two sides have different Python
versions, we'll want a more comprehensive list of normalizers.

- Expand the default list to include patterns discovered during a Python
  3.8 vs. 3.12 comparison.
- Append the setting value by default, rather than replacing (but still
  allow replacing).
- Use default normalizers if custom ones can't be loaded.
- Add log message when loading normalizers fails.
- Validate the replacement pattern, not just the search pattern.
2025-05-08 13:43:53 -04:00
Tim McCormack
5bc05810dc feat: Improve codejail darklaunch logging (#36671)
This is intended to make logs more or less a standalone source for
analyzing mismatches.

- Only log mismatches or exceptions
- Merge local and remote log messages into one so they can be correlated
  more easily
- Different log messages for mismatch vs. unexpected exceptions
- Include course ID (as limit overrides context) in log message
2025-05-06 16:42:55 -04:00
Tim McCormack
ca335b3c3a feat: Fix character range for codejail darklaunch tmpdir normalization (#36615)
Python's tempfile naming also includes underscore:
https://github.com/python/cpython/blob/3.12/Lib/tempfile.py#L140

This omission would cause normalization to fail about 1/6 of the time.

Also expand test to exercise more of character range.
2025-04-28 12:35:41 -04:00
Tim McCormack
3a9b4367e6 fix: Call json_safe on globals in codejail remote_exec (#36542)
We need to make globals JSON-friendly before sending them across the
network.

Addresses https://github.com/edx/edx-arch-experiments/issues/1016
2025-04-18 11:22:43 -04:00
Tim McCormack
a960cdff8d fix: Add much more codejail darklaunch info; fix remote error bug (#36534)
- Fix bug where we were overwriting `remote_emsg` with None, and add test
  that would have caught it.
- Suppress differences due solely to the codejail sandbox directory name
  differing (in stack traces), and add test for this. Configurable because
  we'll need to add an additional search/replace pair for the sandbox venv
  paths.
- Add a variety of custom attributes, replacing existing ones. The attrs
  now have a prefixed naming scheme to simplify searching.
- Add slug to log output so we can more readily correlate traces and logs,
  as well as logs across services.
- Fix typo in error message.
- Fix existing import sort order lint.
2025-04-17 15:39:47 -04:00
Tim McCormack
bf2f8c3705 fix: Don't let local codejail exec pollute darklaunched remote globals
We were running local exec before making the copy of globals_dict for
remote_exec, so remote exec has been getting a polluted version of the
globals.
2025-04-15 15:50:12 -04:00
Tim McCormack
fd66048a49 test: Improve codejail darklaunch tests
- Separate test for misconfiguration
- Add helper method for generic dark launch testing
- Test two darklaunch scenarios: Globals interference, and error that would
  previously have caused the remote side not to run
- Rename mocks to have our usual `mock_` prefix
2025-04-15 15:50:12 -04:00
Tim McCormack
3f2271ab69 feat: Catch all exceptions from codejail dark launch
- Catch all exceptions, not just Exception, to better prevent errors from
  interfering with mainline responses.
- Introduce a separate try block around the monitoring code so that bugs
  there don't cause issues.
- Print exception information as well for both sides (but only if not a
  SafeExecException, which is redundant with emsg).

Some formatting changes to log messages as well.

Example outputs:

For `1/0`:

```
2025-04-14 17:26:34,239 INFO 10232 [xmodule.capa.safe_exec.safe_exec] [user 3] [ip 172.18.0.1] safe_exec.py:240 - Remote execution in darklaunch mode produces globals={'expect': None, 'ans': '1/0'}, emsg=None, exception=None
2025-04-14 17:26:34,239 INFO 10232 [xmodule.capa.safe_exec.safe_exec] [user 3] [ip 172.18.0.1] safe_exec.py:245 - Local execution in darklaunch mode produces globals={'expect': None, 'ans': '1/0'}, emsg='ZeroDivisionError: division by zero', exception=None
```

For `raise BaseException("hi")`:

```
2025-04-14 17:26:13,359 INFO 10232 [xmodule.capa.safe_exec.safe_exec] [user 3] [ip 172.18.0.1] safe_exec.py:240 - Remote execution in darklaunch mode produces globals={'expect': None, 'ans': 'raise BaseException("hi")'}, emsg=None, exception=None
2025-04-14 17:26:13,359 INFO 10232 [xmodule.capa.safe_exec.safe_exec] [user 3] [ip 172.18.0.1] safe_exec.py:245 - Local execution in darklaunch mode produces globals={'expect': None, 'ans': 'raise BaseException("hi")'}, emsg='hi', exception=BaseException('hi')
```

With codejail-service down, and `out = 1 + 2`:

```
2025-04-14 17:30:28,597 INFO 12484 [xmodule.capa.safe_exec.safe_exec] [user 3] [ip 172.18.0.1] safe_exec.py:241 - Remote execution in darklaunch mode produces globals={'expect': None, 'ans': 'out = 1 + 2', 'out': 3, 'cfn_return': {'input_list': [{'ok': True, 'msg': 'Output:\n3', 'grade_decimal': 1}]}}, emsg=None, exception=CodejailServiceUnavailable('Codejail API Service is unavailable. Please try again in a few minutes.')
2025-04-14 17:30:28,597 INFO 12484 [xmodule.capa.safe_exec.safe_exec] [user 3] [ip 172.18.0.1] safe_exec.py:246 - Local execution in darklaunch mode produces globals={'expect': None, 'ans': 'out = 1 + 2', 'out': 3, 'cfn_return': {'input_list': [{'ok': True, 'msg': 'Output:\n3', 'grade_decimal': 1}]}}, emsg=None, exception=None
```
2025-04-15 15:50:12 -04:00
Tim McCormack
45a96e2430 feat: Run remote codejail even if unexpected exception in local safe_exec
During dark launch of remote codejail, we want to ensure we always run both
local and remote execution -- otherwise we're missing data for the remote
side in an important situation.

This will help answer the question of whether the unexpected exception
happens on both sides, even though it may not look exactly the same due to
differences in how unexpected errors are handled.

An example input that provokes this in unsafe execution mode is
`raise BaseException("hi")`; in safe execution mode, printing to
`sys.__stdout__` should also produce an appropriate error.
2025-04-15 15:50:12 -04:00
gabrielC1409
db27ab6166 feat: Send xqueue submissions to edx-submission
fix: Restructuring to send course_id and score to edx submission

fix: Refactoring of sending information to sent_to_submission

fix: Elimination of unnecessary functions

fix: Added usage comment to ProblemBlock in XqueueInterface constructor

fix: update doc ADR

fix: setting for Quality Others test (ubuntu-24.04, 3.11, 20)

fix: Deprecation for django-trans-escape-filter-parse-error

test: Add @pytest.mark.django_db decorator to test functions

test: Fix for pylint being disabled

fix: updated changes for pylint disable

fix: update error from docs ADR-0005

update: xmodule/docs/decisions/0005-send-data-to-edx-submission.rst

Co-authored-by: Sarina Canelake <sarina@axim.org>

update: xmodule/docs/decisions/0005-send-data-to-edx-submission.rst

Co-authored-by: Sarina Canelake <sarina@axim.org>

fix: Adjusted correction

fix: update date for docs ADR

Revert "fix: update date for docs ADR"

This reverts commit 0b4229c51c4937f95cb407872645dd448df45418.

fix: replace call created_submission to create_external_grader_detail

fix: update test xqueue_submission

fix: add docstring in test_xqueue_submission

fix: update date doc ADR

fix: update version edx-submission 3.8.6

fix: add @pytest.mark.xfail

fix: add 20 chances in test_capa_block:

fix: increase retry attempts for seed generation in ProblemBlockTest

fix: change version to edx-submission lib

fix: new version edx-submission in testings

fix: replace parameter file to files

fix: update variable grader_file_name and points_possible

fix: Adjustment in the is_flag_active function to always take the last record edited in the waffle

fix: wrap large line of code

fix: update function is_flag_active

fix: code style adjustment

fix: changes for 60 retry

feat: use CourseWaffleFlag to determine xqueue callback path

fix: Code style adjustment

fix: remove deprecated xqueue callback route and simplify callback type logic

fix: Deleting a comment in the ADR document

fix: add log in self.block is None

fix: Code style adjustment in log
2025-04-15 11:59:32 -04:00
Tim McCormack
1303965a29 feat: Also set MPLCONFIGDIR to make matplotlib complain less (#36456)
Example output from running `import matplotlib; 1/0`, before and after the change:

```diff
--- tmp/before	2025-03-28 03:34:06.633689552 +0000
+++ tmp/after	2025-03-28 03:34:37.268688891 +0000
@@ -1,6 +1,5 @@
-Matplotlib created a temporary cache directory at /tmp/codejail-hveq16ah/tmp/matplotlib-tv0c_vzt because the default path (/home/sandbox/.config/matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.
 Traceback (most recent call last):
   File "jailed_code", line 19, in <module>
     exec(code, g_dict)
   File "<string>", line 1, in <module>
 ZeroDivisionError: division by zero
```
2025-03-28 07:31:50 -04:00
Tim McCormack
2009e8972c feat: Set TMPDIR for codejail executions (#36412)
This makes it easier to run matplotlib in codejail, and should prevent a
number of other issues in the future with other packages that need to
create tempfiles.

No change is required for existing codejail installations, but after this
change operators may be able to tighten their apparmor configuration to
prevent write access to global temp or cache dirs.

Manual testing instructions: Create a codejail problem that runs
`import matplotlib` and confirm that it runs without error. (Unit tests
aren't feasible here because this requires a fully configured codejail in
order for the tmp subdirectory to exist.)

Also: Add comment for `OPENBLAS_NUM_THREADS` and numpy support.
2025-03-20 15:41:43 -04:00
Diana Huang
8935af7ab4 feat: Add observability to codejail darklaunch.
Sets up tracing in code jail calls to track remote
and local execution, and adds custom attributes
to track error messages from the calls.

https://github.com/edx/edx-arch-experiments/issues/895
2025-03-07 11:19:40 -05:00
Diana Huang
ef49090c31 feat: Add codejail darklaunch toggle.
This adds a toggle for running codejail in both remote
and local configurations for testing purposes.

https://github.com/edx/edx-arch-experiments/issues/895
2025-03-05 17:56:40 -05:00
Usama Sadiq
b6828cecaa fix: enable pylint warnings (#36195)
* fix: enable pylint warnings
2025-01-30 17:15:33 +05:00
Irtaza Akram
ec2a698604 cleanup references of python 2 & <3.11 (#35799)
* chore: cleanup of old python references
2024-11-15 16:58:20 +05:00
Raymond Zhou
22b81165e7 chore: calc version bump (#35590) 2024-10-07 14:39:23 -04:00
Irtaza Akram
f7229e0aad chore: replace bleach with nh3 2024-05-28 13:02:16 +05:00
Kyle McCormick
11626148d9 refactor: switch from mock to unittest.mock (#34844)
As of Python 3.3, the 3rd-party `mock` package has been subsumed into the
standard `unittest.mock` package. Refactoring tests to use the latter will
allow us to drop `mock` as a dependency, which is currently coming in
transitively through requirements/edx/paver.in.

We don't actually drop the `mock` dependency in this PR. That will happen
naturally in:

* https://github.com/openedx/edx-platform/pull/34830
2024-05-22 13:52:24 -04:00
Bryann Valderrama
85620ec73c feat: add grading method support for problems with multiple attempts (#33911)
A new field in the Problem settings for choosing a Grading Method. Currently, the only Grading Method is the Last Score. From now on, when turning the feature flag on, the new grading methods available for configuration in Studio are:
- Last Score (Default): The last score made is taken for grading.
- First Score: The first score made is taken for grading.
- Highest Score: The highest score made is taken for grading.
- Average Score: The average of all scores made is taken for grading.
2024-04-04 14:04:25 -04:00
Kyle McCormick
9c6e765bf6 test: run ./xmodule/ tests with CMS settings (#33534)
Currently, ./xmodule/ unit tests are only run with LMS settings. However,
./common/ and ./xmodule/ are run twice: once with LMS settings and once with
CMS settings.

Just like ./common/ and ./openedx/, the unit tests in ./xmodule/ validate
behavior in both LMS and CMS. So, order to fully test ./xmodule/, we should to
run its tests with CMS settings too.

This will enable us to better validate certain LibraryContentBlocks behaviors
being touched by https://github.com/openedx/edx-platform/pull/33263 which can't
be expressed under LMS settings.

Also in this commit:

* refactor: rename the shards to be clear whether they're running under LMS or CMS
* docs: correct comments regarding conditions under which codejail's
   test_cant_do_something_forbidden is skipped.
* test: update a unit test which was using the now-deleted library_sourced block to use
   library_content block instead.
2023-10-19 10:19:28 -04:00
Babatunde Olusola
6e2c43e4e0 refactor: update codejail test condition (#32955)
Skip the test for codejail if the codejailservice api is not enabled.
It fixes running this test case in Tutor.
2023-09-07 17:08:30 +02:00
Usama Sadiq
7710e60328 fix: fix middleware get_response parameter deprecation warning (#33067) 2023-08-22 15:52:30 +05:00
Usama Sadiq
852246db8c fix: replace ugettext with gettext (#33022) 2023-08-16 17:07:23 +05:00
Diego Velasquez
547e5b1f7b chore: remove warnings from defusedxml package (#32652)
Co-authored-by: Diego Velásquez <diego@emptor.io>
2023-07-26 12:20:56 -04:00
Braden MacDonald
9b9b88df52 chore: remove some usages of six (Python2 compat) (#32554)
* get rid of six.text_type(s)
* get rid of six.b()
* get rid of six.string_types
* get rid of six.PY2/six.PY3
* get rid of six.iteritems() and six.viewvalues()
2023-07-17 12:18:43 -07:00
Braden MacDonald
162175f0c4 chore: get rid of edx_six - not needed anymore (#32555)
* chore: get rid of edx_six - not needed anymore
* chore: remove reference to TODO that was completed.
2023-07-10 11:16:57 -07:00
Piotr Surowiec
0137f21627 feat: move XQueueService from the runtime to ProblemBlock
The XQueueService is used only by the ProblemBlock. Therefore, we are moving 
it out of the runtime, and into the ProblemBlock, where it's initialized only 
when it's going to be used.
2023-06-21 20:08:31 +02:00
Kaustav Banerjee
c5439221cb chore: address review comments 2023-04-21 11:53:49 +02:00
Feanil Patel
57f2ca1a21 fix: Prepare for the bleach 6.0.0 upgrad.
Changelog: https://bleach.readthedocs.io/en/latest/changes.html#version-6-0-0-january-23rd-2023

The major change is that the tags and protocols attributes and related
constants are expected to be sets rather than lists.
2023-02-01 11:46:44 -05:00
0x29a
a027f36724 refactor: rename module -> block within xmodule 2023-01-30 18:15:22 +01:00
0x29a
4c005e86e8 refactor: xmodule/capa_module.py -> xmodule/capa_block.py 2022-12-19 17:48:49 +01:00
Piotr Surowiec
f419d6b194 feat: deprecate track_function and publish in ModuleSystem [BD-13] (#30046)
* feat: delete `track_function` from ModuleSystem

* feat: delete `publish` argument from ModuleSystem
2022-11-15 10:46:24 -05:00
Usama Sadiq
4734f9f16e fix: bump pylint version (#31084) 2022-10-27 12:19:09 +05:00