protected function delete_expired_context(expired_context $expiredctx) {
        $context = \context::instance_by_id($expiredctx->get('contextid'));

        $this->get_progress()->output("Deleting context {$context->id} - " . $context->get_context_name(true, true));

        // Update the expired_context and verify that it is still ready for deletion.
        $expiredctx = $this->update_expired_context($expiredctx);
        if (empty($expiredctx)) {
            $this->get_progress()->output("Context has changed since approval and is no longer pending approval. Skipping", 1);
            return false;
        }

        if (!$expiredctx->can_process_deletion()) {
            // This only happens if the record was updated after being first fetched.
            $this->get_progress()->output("Context has changed since approval and must be re-approved. Skipping", 1);
            $expiredctx->set('status', expired_context::STATUS_EXPIRED);
            $expiredctx->save();

            return false;
        }

        $privacymanager = $this->get_privacy_manager();
        if ($expiredctx->is_fully_expired()) {
            if ($context instanceof \context_user) {
                $this->delete_expired_user_context($expiredctx);
            } else {
                // This context is fully expired - that is that the default retention period has been reached, and there are
                // no remaining overrides.
                $privacymanager->delete_data_for_all_users_in_context($context);
            }

            // Mark the record as cleaned.
            $expiredctx->set('status', expired_context::STATUS_CLEANED);
            $expiredctx->save();

            return $context;
        }

        // We need to find all users in the context, and delete just those who have expired.
        $collection = $privacymanager->get_users_in_context($context);

        // Apply the expired and unexpired filters to remove the users in these categories.
        $userassignments = $this->get_role_users_for_expired_context($expiredctx, $context);
        $approvedcollection = new \core_privacy\local\request\userlist_collection($context);
        foreach ($collection as $pendinguserlist) {
            $userlist = filtered_userlist::create_from_userlist($pendinguserlist);
            $userlist->apply_expired_context_filters($userassignments->expired, $userassignments->unexpired);
            if (count($userlist)) {
                $approvedcollection->add_userlist($userlist);
            }
        }

        if (count($approvedcollection)) {
            // Perform the deletion with the newly approved collection.
            $privacymanager->delete_data_for_users_in_context($approvedcollection);
        }

        // Mark the record as cleaned.
        $expiredctx->set('status', expired_context::STATUS_CLEANED);
        $expiredctx->save();

        return $context;
    }