Can I truncate grades history table without getting problems?

Can I truncate grades history table without getting problems?

by Madhu Avasarala -
Number of replies: 15

My grades history (as well as grades) tables are really large. I cannot control the grades but the grades history is not important to me. The table size has been stubbornly high at > 6GB even after disabling site admin->clean->disable grades history. Therefore, can I run the MYSQL command: 

TRUNCATE TABLE mdl_grade_grades_history; 

without encountering any issues with running of Moodle? I searched for this high and low but could not find any answer anywehere.

Thanks in advance for any help.

Average of ratings: -
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
You don't need to. There's a setting in the site administration.

Site administration > Server > Cleanup
Average of ratings: Useful (1)
In reply to Howard Miller

Re: Can I truncate grades history table without getting problems?

by Madhu Avasarala -
Thanks for the reply. I have set the holding date to 30d just last week (my site is several years old) and even after tasks have run for several days, the table size is still about 6GB. I tried running the tasks on-demand and they ran fine but did not reduce the size. I tried disabling history and not and no change. Therefore I am toying with forcefully emptying the table, out of desperation.
Average of ratings: Useful (1)
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Ken Task -
Picture of Particularly helpful Moodlers

The database for an old/used site can develop tables that need optimizing.  Even if the cleanups are keeping the rows in the tables for the set number of days, etc., cleanups won't reduce the size the table.

If you can, install mysqltuner and run it.   Among the checks tuner performs is alerting you of tables that need optimizing.

Assuming MySQL:

https://dev.mysql.com/doc/refman/5.7/en/optimize-table.html

'SoS', Ken

In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
Just checking - your Cron and Scheduled tasks are all running properly, without errors?  Have you actually checked the database table to make sure the expected data rows have been deleted (not just checked the physical size). 

I know you say they are working properly but what's your evidence for that? Have you checked the scheduled task logs for errors?

As Ken alludes to it's worth running an optimize.... https://dev.mysql.com/doc/refman/8.0/en/optimize-table.html

Lastly, what's your actual underlying issue? The table is 6GB.... so what?
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Here's what mine looks like... notices the index data size.   Grade history lifetime is set to 365 days and I have around 40,000 active users.



In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

And..... here is the code for the cleanup task....

        if (!empty($CFG->gradehistorylifetime)) {
            $now = time();
            $histlifetime = $now - ($CFG->gradehistorylifetime * DAYSECS);
            $tables = [
                'grade_outcomes_history',
                'grade_categories_history',
                'grade_items_history',
                'grade_grades_history',
                'scale_history'
            ];
            foreach ($tables as $table) {
                if ($DB->delete_records_select($table, "timemodified < ?", [$histlifetime])) {
                    mtrace("    Deleted old grade history records from '$table'");
                }
            }


In a nutshell, if you must I can't see any issue TRUNCATEing the contents of those 5 tables. 

Average of ratings: Useful (1)
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Madhu Avasarala -
Thanks for the replies so far, Howard and Ken, appreciate your spirit of helping the community at large.
1. I did run mysqltuner several times. There were no major recommendations. All of my 15GB database fits in my innodb_buffer_pool of 16GB with 16 instances of 1G.
2. Checking the task logs for running any of the grades and grads history shows no issues. i can run them at will and they show no errors.
3. The only task that does show an error is the following: (Execute scheduled task: Background processing for assignment module (mod_assign\task\cron_task)
... used 63 dbqueries
... used 0.33621788024902 seconds
Scheduled task failed: Background processing for assignment module (mod_assign\task\cron_task),Invalid course module ID
)

My mine issue is that the teachers are unable to edit/delete assignments in a particular course. The course is very heavy with assignments (over 500). There are several such courses. I am trying to reduce the database size so all of it fits into an innodb_buffer_pool of 8GB and not have the edit/delete problem the teachers are having with Assignments.
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
In the nicest way.... it's a good idea to tell us the problem you have rather than the problem you think you have and it might have saved us digging around in the grade history.

My immediate reaction is that a course with 500 of *any* activity might be an issue. Unless there's something else you're not telling us, I wouldn't immediately pin it on the database and certainly not table sizes. This is a problem I've seen, editing huge courses can get very slow. Probably due to constantly having to rebuild invalidated caches. At the risk of stating the very obvious, the least stressful solution is probably just to split the course up.
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Ken Task -
Picture of Particularly helpful Moodlers

Wonder if you wouldn't mind sharing info on server setup?

All in one?  DB server dedicated?  Memory?

In tuner output, Performance Metrics
what does it say for:
Maximum reached memory usage
Maximum possible memory usage
Overall possible memory usage with other process is compatible with memory available

And it appears there really isn't a problem with size of tables, but, rather, the server's adhoc_task jobs which have been building up and failing related to assignments.

Am in agreement with Howard ... 500 of anything is too much ... I, personally, would hate to be in a course, that had 500 assignments!!! :|  

Moodle admin user doesn't get any advanced warning about course designs ... there is no plugin/addon/report that one could set for threshold warnings. sad   Even if there were, a Moodle Admin might have a hard time convincing teachers of such courses how to design them in such a way as to not overtax a server.   Teachers, however, do need to realize Moodle is a shared resource.

'SoS', Ken




In reply to Ken Task

Re: Can I truncate grades history table without getting problems?

by Madhu Avasarala -
Hi Ken,
My Moodle server is a dedicated one on LAMP Ubuntu 18.04, DIgital Ocean 32M, 4cpu (dedicated), 160GB SSD. There are 1450 active users on the system. K-12
I list the Mysqltuner metrices at the end.
Because of Covid, every class including primary is issuing home assignments on a daily basis. So there is at least 1 Assignment per day. There are also content resources etc. That is why the course load is high since the teacher supposedly needs the work for the entire year visible for both teachers and parents.
The problem started with PHP running out of memory. It wanted to allocate 2GB of memory just to login for users in such courses. So I suspected the tables were too large to be loaded and started examining tables and saw that the largest tables were: grades, grades-history, and logs. When I reduced the logs duration the log table size came down. Not so however, the grades_history. So that's where the post got started.
Obviously there are no clear guidelines on scaling of Moodle. When I scaled my server to twice the RAM, the problem of editing the Assignments did not change at all. Clearly there is a problem here that is not addressed anywhere.
-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 18h 52m 57s (7M q [106.242 qps], 43K conn, TX: 6G, RX: 1G)
[--] Reads / Writes: 82% / 18%
[--] Binary logging is disabled
[--] Physical Memory : 31.4G
[--] Max MySQL memory : 16.6G
[--] Other process memory: 1.4G
[--] Total buffers: 16.1G global + 1.1M per thread (500 max threads)
[--] P_S Max memory usage: 72B
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 16.1G (51.28% of installed RAM)
[OK] Maximum possible memory usage: 16.6G (52.83% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/7M)
[OK] Highest usage of available connections: 5% (29/500)
[OK] Aborted connections: 0.00% (2/43688)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 5M selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (1K temp sorts / 837K sorts)
[!!] Joins performed without indexes: 13497
[OK] Temporary tables created on disk: 11% (109K on disk / 975K total)
[OK] Thread cache hit rate: 99% (41 created / 43K connections)
[!!] Table cache hit rate: 3% (2K open / 64K opened)
[OK] Open file limit used: 0% (0/5K)
[OK] Table locks acquired immediately: 100% (12K immediate / 12K locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 72B
[--] Sys schema is installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (3M used / 16M cache)
[OK] Key buffer size / total MyISAM indexes: 16.0M/43.0K
[!!] Read Key buffer hit rate: 92.7% (96 cached / 7 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 16.0G/15.8G
[OK] Ratio InnoDB log file size / InnoDB Buffer pool size: 2.0G * 2/16.0G should be equal 25%
[OK] InnoDB buffer pool instances: 16
[--] Number of InnoDB Buffer Pool Chunk : 128 for 16 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 99.93% (443671249 hits/ 443975362 total)
[!!] InnoDB Write Log efficiency: 32.75% (519856 hits/ 1587182 total)
[OK] InnoDB log waits: 0.00% (0 waits / 1067326 writes)
-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
MySQL started within last 24 hours - recommendations may be inaccurate
Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
Adjust your join queries to always utilize indexes
Increase table_open_cache gradually to avoid file descriptor limits
Read this before increasing table_open_cache over 64: http://bit.ly/1mi7c4C
Beware that open_files_limit (5000) variable
should be greater than table_open_cache (2245)
Variables to adjust:
query_cache_size (=0)
query_cache_type (=0)
query_cache_limit (> 1M, or use smaller result sets)
join_buffer_size (> 256.0K, or always use indexes with joins)
table_open_cache (> 2245)
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Ken Task -
Picture of Particularly helpful Moodlers

Thanks for info ... at top you say you have 32M (which is megs), yet in tuner, those checks on memory, I see 31.4G (which is Gigs).

Devils are always in details! :|

There is one recommendation tuner made that you should correct .... in config.php the DB host is 'localhost' ... correct?  If so that is actually using socket connection and not using 'network' thus one doesn't need MySQL to perform DNS lookups on every ... that's every ... query.

The the recommendation: skip-name-resolve=1

Also ... each time we change config of MySQL and restart the service, it will take some time for the DB server to collect stats ... so one needs to wait a day ... then run tuner again.

Am assuming that these classes are not being conducted face-2-face, where teacher and students are present in class using moodle at the same time, but async. ... where students can access at any time of the day/evening or even late at night.

Is there a class schedule?

Are the assignments configured to be opened at a certain time and then also close at a certain time?

Also, there are assignment types ... are the assignments such that students have to upload a file to the moodle?

Also, what about document conversion?

At any given time, how many students/teachers are logged on?

Here's a command line script I have called 'last5' and placed in code/admin/cli/:

mysql -u root -p'yourpassword' -e "use moodle;SELECT firstname,lastname,lastip,from_unixtime(lastaccess) as LastClick,now()-interval 5 minute as Last5Minutes FROM mdl_user having LastClick > Last5Minutes order by lastaccess desc;"> last5.txt;cat last5.txt;wc -l last5.txt

-rwx------. 1 apache apache 272 Jul 23  2020 last5

It's not really accurate cause it depends upon users logging out ... and many don't! (grrrr) ... but I use it to see how disruptive I would be if I were to update/upgrade or perform a backup.

Got any errors in your apache error logs?

This is a balancing act between MySQL/Apache and whatever else is running on server.

'SoS', Ken

Average of ratings: Useful (2)
In reply to Ken Task

Re: Can I truncate grades history table without getting problems?

by Ken Task -
Picture of Particularly helpful Moodlers

Ok, in re-reading ...

this:

Scheduled task failed: Background processing for assignment module (mod_assign\task\cron_task),Invalid course module ID

is really the problem.

From command line in /admin/tool/task/cli/

run

php schedule_task.php --execute="\core_files\task\conversion_cleanup_task"

I have a bash shell script at that location just for cleanup ... called 'cleanup' and made executable for root users only.

Looks like:

php schedule_task.php --execute="\logstore_legacy\task\cleanup_task"
php schedule_task.php --execute="\logstore_standard\task\cleanup_task"
php schedule_task.php --execute="\core\task\file_trash_cleanup_task"
php schedule_task.php --execute="\core\task\messaging_cleanup_task"
php schedule_task.php --execute="\core\task\password_reset_cleanup_task"
php schedule_task.php --execute="\core\task\session_cleanup_task"
php schedule_task.php --execute="\core_files\task\conversion_cleanup_task"
php schedule_task.php --execute="\tool_recyclebin\task\cleanup_category_bin"
php schedule_task.php --execute="\tool_recyclebin\task\cleanup_course_bin"

'SoS', Ken


Average of ratings: Useful (2)
In reply to Ken Task

Re: Can I truncate grades history table without getting problems?

by Madhu Avasarala -
I did all of the CLI cleanup tasks you suggested. I had done them earlier too. Even after all of this I get the same error for the mod_assign, invalic course moudule id, no other clue for that error.
The greades_history remains stubbornly high and constant no matter what. The cleanup scripts are doing nothing to it. This is the same as reported by several people on the forums.
As far as the apache2 errors nothing significant. When I turn on debugging there is a lot of garbage regarding deprecated calls etc., in core code (I am on 3.11++)
The only time I see errors are when someone tries to edit a problem course and the memory demand shoots up beyond what is set as allowable.
As far as mysql tuner output, it is remarkably constant no matter when I run it so mysql is not the issue. Apache is not the issue. It is Moodle. Most probably, as you pointed out, the large number of activities in some courses and possible corruption while editing such courses therein maybe causing the problems I see. I have asked for the courses to be changed to a maximum allowable 200-350 activities. I hope that will help. I may even have a problem deleting these problem courses until I delete the activities one by one and empty the bad courses. Very painful.
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Howard Miller -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
I did say, several posts back that I thought the DB was nothing to do with it.

Moodle has to do a huge amount of work to build the page content. If you have course/activity completion on it gets even worse. I'm almost certain that the number of acvitities is your issue. While there's no limit on the number I wouldn't want to go too far north of 100 or so.

I would also have a hard look at your caching. Caching is absolutely critical to Moodle performance. If your cache setup is sub-optimal (or, more likely, you've never given it a thought) then that won't help matters either.
In reply to Madhu Avasarala

Re: Can I truncate grades history table without getting problems?

by Ken Task -
Picture of Particularly helpful Moodlers

"This is the same as reported by several people on the forums."

References/urls please.

"turn on debugging there is a lot of garbage regarding deprecated calls"

Can you share an example of those?

"am on 3.11++"

No such version ... highest for 3.11 is:

3.11.3+ (Build: 20210917)

Again ... 'devil' is in the details.

"same error for the mod_assign"

| Tables_in_moodle311 (%assign%)   |
+----------------------------------+
| mdl_assign                       |
| mdl_assign_grades                |
| mdl_assign_overrides             |
| mdl_assign_plugin_config         |
| mdl_assign_submission            |
| mdl_assign_user_flags            |
| mdl_assign_user_mapping

What do you get with this query:

select id, course, name from mdl_assign;

'SoS', Ken