def _reset_or_delete_module(studentmodule): if delete_module: studentmodule.delete() create_new_event_transaction_id() set_event_transaction_type(grades_events.STATE_DELETED_EVENT_TYPE) tracker.emit( six.text_type(grades_events.STATE_DELETED_EVENT_TYPE), { 'user_id': six.text_type(student.id), 'course_id': six.text_type(course_id), 'problem_id': six.text_type(module_state_key), 'instructor_id': six.text_type(requesting_user.id), 'event_transaction_id': six.text_type(get_event_transaction_id()), 'event_transaction_type': six.text_type(grades_events.STATE_DELETED_EVENT_TYPE), } ) if not submission_cleared: _fire_score_changed_for_block( course_id, student, block, module_state_key, ) else: _reset_module_attempts(studentmodule)
def grade_updated(**kwargs): """ Emits the appropriate grade-related event after checking for which event-transaction is active. Emits a problem.submitted event only if there is no current event transaction type, i.e. we have not reached this point in the code via an outer event type (such as problem.rescored or score_overridden). """ root_type = get_event_transaction_type() if not root_type: root_id = get_event_transaction_id() if not root_id: root_id = create_new_event_transaction_id() set_event_transaction_type(PROBLEM_SUBMITTED_EVENT_TYPE) tracker.emit( str(PROBLEM_SUBMITTED_EVENT_TYPE), { 'user_id': str(kwargs['user_id']), 'course_id': str(kwargs['course_id']), 'problem_id': str(kwargs['usage_id']), 'event_transaction_id': str(root_id), 'event_transaction_type': str(PROBLEM_SUBMITTED_EVENT_TYPE), 'weighted_earned': kwargs.get('weighted_earned'), 'weighted_possible': kwargs.get('weighted_possible'), } ) elif root_type in [GRADES_RESCORE_EVENT_TYPE, GRADES_OVERRIDE_EVENT_TYPE]: current_user = get_current_user() instructor_id = getattr(current_user, 'id', None) tracker.emit( str(root_type), { 'course_id': str(kwargs['course_id']), 'user_id': str(kwargs['user_id']), 'problem_id': str(kwargs['usage_id']), 'new_weighted_earned': kwargs.get('weighted_earned'), 'new_weighted_possible': kwargs.get('weighted_possible'), 'only_if_higher': kwargs.get('only_if_higher'), 'instructor_id': str(instructor_id), 'event_transaction_id': str(get_event_transaction_id()), 'event_transaction_type': str(root_type), } ) elif root_type in [SUBSECTION_OVERRIDE_EVENT_TYPE]: tracker.emit( str(root_type), { 'course_id': str(kwargs['course_id']), 'user_id': str(kwargs['user_id']), 'problem_id': str(kwargs['usage_id']), 'only_if_higher': kwargs.get('only_if_higher'), 'override_deleted': kwargs.get('score_deleted', False), 'event_transaction_id': str(get_event_transaction_id()), 'event_transaction_type': str(root_type), } )
def _create_override(self, request_user, subsection_grade_model, **override_data): """ Helper method to create a `PersistentSubsectionGradeOverride` object and send a `SUBSECTION_OVERRIDE_CHANGED` signal. """ override_data[ 'system'] = grades_constants.GradeOverrideFeatureEnum.gradebook override = PersistentSubsectionGradeOverride.update_or_create_override( requesting_user=request_user, subsection_grade_model=subsection_grade_model, feature=grades_constants.GradeOverrideFeatureEnum.gradebook, **override_data) set_event_transaction_type(grades_events.SUBSECTION_GRADE_CALCULATED) create_new_event_transaction_id() recalculate_subsection_grade_v3.apply(kwargs=dict( user_id=subsection_grade_model.user_id, anonymous_user_id=None, course_id=text_type(subsection_grade_model.course_id), usage_id=text_type(subsection_grade_model.usage_key), only_if_higher=False, expected_modified_time=to_timestamp(override.modified), score_deleted=False, event_transaction_id=six.text_type(get_event_transaction_id()), event_transaction_type=six.text_type(get_event_transaction_type()), score_db_table=grades_constants.ScoreDatabaseTableEnum.overrides, force_update_subsections=True, )) # Emit events to let our tracking system to know we updated subsection grade grades_events.subsection_grade_calculated(subsection_grade_model) return override
def override_subsection_grade( user_id, course_key_or_id, usage_key_or_id, overrider=None, earned_all=None, earned_graded=None, feature=constants.GradeOverrideFeatureEnum.proctoring, comment=None, ): """ Creates a PersistentSubsectionGradeOverride corresponding to the given user, course, and usage_key. Will also create a ``PersistentSubsectionGrade`` for this (user, course, usage_key) if none currently exists. Fires off a recalculate_subsection_grade async task to update the PersistentCourseGrade table. Will not override ``earned_all`` or ``earned_graded`` value if they are ``None``. Both of these parameters have ``None`` as their default value. """ course_key = _get_key(course_key_or_id, CourseKey) usage_key = _get_key(usage_key_or_id, UsageKey) try: grade = get_subsection_grade(user_id, usage_key.course_key, usage_key) except ObjectDoesNotExist: grade = _create_subsection_grade(user_id, course_key, usage_key) override = update_or_create_override( grade, requesting_user=overrider, subsection_grade_model=grade, feature=feature, system=feature, earned_all_override=earned_all, earned_graded_override=earned_graded, comment=comment, ) # Cache a new event id and event type which the signal handler will use to emit a tracking log event. create_new_event_transaction_id() set_event_transaction_type(events.SUBSECTION_OVERRIDE_EVENT_TYPE) # This will eventually trigger a re-computation of the course grade, # taking the new PersistentSubsectionGradeOverride into account. signals.SUBSECTION_OVERRIDE_CHANGED.send( sender=None, user_id=user_id, course_id=text_type(course_key), usage_id=text_type(usage_key), only_if_higher=False, modified=override.modified, score_deleted=False, score_db_table=constants.ScoreDatabaseTableEnum.overrides)
def handle(self, *args, **options): if 'modified_start' not in options: raise CommandError('modified_start must be provided.') if 'modified_end' not in options: raise CommandError('modified_end must be provided.') modified_start = utc.localize( datetime.strptime(options['modified_start'], DATE_FORMAT)) modified_end = utc.localize( datetime.strptime(options['modified_end'], DATE_FORMAT)) event_transaction_id = create_new_event_transaction_id() set_event_transaction_type(PROBLEM_SUBMITTED_EVENT_TYPE) kwargs = { 'modified__range': (modified_start, modified_end), 'module_type': 'problem' } for record in StudentModule.objects.filter(**kwargs): if not record.course_id.is_course: # This is not a course, so we don't store subsection grades for it. continue task_args = { "user_id": record.student_id, "course_id": str(record.course_id), "usage_id": str(record.module_state_key), "only_if_higher": False, "expected_modified_time": to_timestamp(record.modified), "score_deleted": False, "event_transaction_id": str(event_transaction_id), "event_transaction_type": PROBLEM_SUBMITTED_EVENT_TYPE, "score_db_table": ScoreDatabaseTableEnum.courseware_student_module, } recalculate_subsection_grade_v3.apply_async(kwargs=task_args) kwargs = {'created_at__range': (modified_start, modified_end)} for record in Submission.objects.filter(**kwargs): if not record.student_item.course_id.is_course: # This is not a course, so ignore it continue task_args = { "user_id": user_by_anonymous_id(record.student_item.student_id).id, "anonymous_user_id": record.student_item.student_id, "course_id": str(record.student_item.course_id), "usage_id": str(record.student_item.item_id), "only_if_higher": False, "expected_modified_time": to_timestamp(record.created_at), "score_deleted": False, "event_transaction_id": str(event_transaction_id), "event_transaction_type": PROBLEM_SUBMITTED_EVENT_TYPE, "score_db_table": ScoreDatabaseTableEnum.submissions, } recalculate_subsection_grade_v3.apply_async(kwargs=task_args)
def undo_override_subsection_grade(user_id, course_key_or_id, usage_key_or_id, feature=''): """ Delete the override subsection grade row (the PersistentSubsectionGrade model must already exist) Fires off a recalculate_subsection_grade async task to update the PersistentSubsectionGrade table. If the override does not exist, no error is raised, it just triggers the recalculation. feature: if specified, the deletion will only occur if the override to be deleted was created by the corresponding subsystem """ course_key = _get_key(course_key_or_id, CourseKey) usage_key = _get_key(usage_key_or_id, UsageKey) try: override = get_subsection_grade_override(user_id, course_key, usage_key) except ObjectDoesNotExist: return if override is not None and (not feature or not override.system or feature == override.system): override.delete() else: return # Cache a new event id and event type which the signal handler will use to emit a tracking log event. create_new_event_transaction_id() set_event_transaction_type(events.SUBSECTION_OVERRIDE_EVENT_TYPE) # Signal will trigger subsection recalculation which will call PersistentSubsectionGrade.update_or_create_grade # which will no longer use the above deleted override, and instead return the grade to the original score from # the actual problem responses before writing to the table. signals.SUBSECTION_OVERRIDE_CHANGED.send( sender=None, user_id=user_id, course_id=text_type(course_key), usage_id=text_type(usage_key), only_if_higher=False, modified=datetime.now().replace( tzinfo=pytz.UTC), # Not used when score_deleted=True score_deleted=True, score_db_table=constants.ScoreDatabaseTableEnum.overrides)
def compute_grades_for_course_v2(self, **kwargs): """ Compute grades for a set of students in the specified course. The set of students will be determined by the order of enrollment date, and limited to at most <batch_size> students, starting from the specified offset. TODO: Roll this back into compute_grades_for_course once all workers have the version with **kwargs. """ if 'event_transaction_id' in kwargs: set_event_transaction_id(kwargs['event_transaction_id']) if 'event_transaction_type' in kwargs: set_event_transaction_type(kwargs['event_transaction_type']) try: return compute_grades_for_course(kwargs['course_key'], kwargs['offset'], kwargs['batch_size']) except Exception as exc: raise self.retry(kwargs=kwargs, exc=exc)
def _recalculate_subsection_grade(self, **kwargs): """ Updates a saved subsection grade. Keyword Arguments: user_id (int): id of applicable User object anonymous_user_id (int, OPTIONAL): Anonymous ID of the User course_id (string): identifying the course usage_id (string): identifying the course block only_if_higher (boolean): indicating whether grades should be updated only if the new raw_earned is higher than the previous value. expected_modified_time (serialized timestamp): indicates when the task was queued so that we can verify the underlying data update. score_deleted (boolean): indicating whether the grade change is a result of the problem's score being deleted. event_transaction_id (string): uuid identifying the current event transaction. event_transaction_type (string): human-readable type of the event at the root of the current event transaction. score_db_table (ScoreDatabaseTableEnum): database table that houses the changed score. Used in conjunction with expected_modified_time. """ try: course_key = CourseLocator.from_string(kwargs['course_id']) if are_grades_frozen(course_key): log.info( "Attempted _recalculate_subsection_grade for course '%s', but grades are frozen.", course_key) return scored_block_usage_key = UsageKey.from_string( kwargs['usage_id']).replace(course_key=course_key) set_custom_attributes_for_course_key(course_key) set_custom_attribute('usage_id', str(scored_block_usage_key)) # The request cache is not maintained on celery workers, # where this code runs. So we take the values from the # main request cache and store them in the local request # cache. This correlates model-level grading events with # higher-level ones. set_event_transaction_id(kwargs.get('event_transaction_id')) set_event_transaction_type(kwargs.get('event_transaction_type')) # Verify the database has been updated with the scores when the task was # created. This race condition occurs if the transaction in the task # creator's process hasn't committed before the task initiates in the worker # process. has_database_updated = _has_db_updated_with_new_score( self, scored_block_usage_key, **kwargs) if not has_database_updated: raise DatabaseNotReadyError _update_subsection_grades( course_key, scored_block_usage_key, kwargs['only_if_higher'], kwargs['user_id'], kwargs['score_deleted'], kwargs.get('force_update_subsections', False), ) except Exception as exc: if not isinstance(exc, KNOWN_RETRY_ERRORS): log.info( "tnl-6244 grades unexpected failure: {}. task id: {}. kwargs={}" .format( repr(exc), self.request.id, kwargs, )) raise self.retry(kwargs=kwargs, exc=exc)
def override_score_module_state(xmodule_instance_args, module_descriptor, student_module, task_input): ''' Takes an XModule descriptor and a corresponding StudentModule object, and performs an override on the student's problem score. Throws exceptions if the override is fatal and should be aborted if in a loop. In particular, raises UpdateProblemModuleStateError if module fails to instantiate, or if the module doesn't support overriding, or if the score used for override is outside the acceptable range of scores (between 0 and the max score for the problem). Returns True if problem was successfully overriden for the given student, and False if problem encountered some kind of error in overriding. ''' # unpack the StudentModule: course_id = student_module.course_id student = student_module.student usage_key = student_module.module_state_key with modulestore().bulk_operations(course_id): course = get_course_by_id(course_id) instance = _get_module_instance_for_task(course_id, student, module_descriptor, xmodule_instance_args, course=course) if instance is None: # Either permissions just changed, or someone is trying to be clever # and load something they shouldn't have access to. msg = "No module {location} for student {student}--access denied?".format( location=usage_key, student=student) TASK_LOG.warning(msg) return UPDATE_STATUS_FAILED if not hasattr(instance, 'set_score'): msg = "Scores cannot be overridden for this problem type." raise UpdateProblemModuleStateError(msg) weighted_override_score = float(task_input['score']) if not (0 <= weighted_override_score <= instance.max_score()): # lint-amnesty, pylint: disable=superfluous-parens msg = "Score must be between 0 and the maximum points available for the problem." raise UpdateProblemModuleStateError(msg) # Set the tracking info before this call, because it makes downstream # calls that create events. We retrieve and store the id here because # the request cache will be erased during downstream calls. create_new_event_transaction_id() set_event_transaction_type(grades_events.GRADES_OVERRIDE_EVENT_TYPE) problem_weight = instance.weight if instance.weight is not None else 1 if problem_weight == 0: # lint-amnesty, pylint: disable=no-else-raise msg = "Scores cannot be overridden for a problem that has a weight of zero." raise UpdateProblemModuleStateError(msg) else: instance.set_score( Score(raw_earned=weighted_override_score / problem_weight, raw_possible=instance.max_score() / problem_weight)) instance.publish_grade() instance.save() TASK_LOG.debug( "successfully processed score override for course %(course)s, problem %(loc)s " "and student %(student)s", dict(course=course_id, loc=usage_key, student=student)) return UPDATE_STATUS_SUCCEEDED
def rescore_problem_module_state(xmodule_instance_args, module_descriptor, student_module, task_input): ''' Takes an XModule descriptor and a corresponding StudentModule object, and performs rescoring on the student's problem submission. Throws exceptions if the rescoring is fatal and should be aborted if in a loop. In particular, raises UpdateProblemModuleStateError if module fails to instantiate, or if the module doesn't support rescoring. Returns True if problem was successfully rescored for the given student, and False if problem encountered some kind of error in rescoring. ''' # unpack the StudentModule: course_id = student_module.course_id student = student_module.student usage_key = student_module.module_state_key with modulestore().bulk_operations(course_id): course = get_course_by_id(course_id) # TODO: Here is a call site where we could pass in a loaded course. I # think we certainly need it since grading is happening here, and field # overrides would be important in handling that correctly instance = _get_module_instance_for_task(course_id, student, module_descriptor, xmodule_instance_args, grade_bucket_type='rescore', course=course) if instance is None: # Either permissions just changed, or someone is trying to be clever # and load something they shouldn't have access to. msg = "No module {location} for student {student}--access denied?".format( location=usage_key, student=student) TASK_LOG.warning(msg) return UPDATE_STATUS_FAILED if not hasattr(instance, 'rescore'): # This should not happen, since it should be already checked in the # caller, but check here to be sure. msg = f"Specified module {usage_key} of type {instance.__class__} does not support rescoring." raise UpdateProblemModuleStateError(msg) # We check here to see if the problem has any submissions. If it does not, we don't want to rescore it if not instance.has_submitted_answer(): return UPDATE_STATUS_SKIPPED # Set the tracking info before this call, because it makes downstream # calls that create events. We retrieve and store the id here because # the request cache will be erased during downstream calls. create_new_event_transaction_id() set_event_transaction_type(grades_events.GRADES_RESCORE_EVENT_TYPE) # specific events from CAPA are not propagated up the stack. Do we want this? try: instance.rescore(only_if_higher=task_input['only_if_higher']) except (LoncapaProblemError, StudentInputError, ResponseError): TASK_LOG.warning( "error processing rescore call for course %(course)s, problem %(loc)s " "and student %(student)s", dict(course=course_id, loc=usage_key, student=student)) return UPDATE_STATUS_FAILED instance.save() TASK_LOG.debug( "successfully processed rescore call for course %(course)s, problem %(loc)s " "and student %(student)s", dict(course=course_id, loc=usage_key, student=student)) return UPDATE_STATUS_SUCCEEDED