OK, so reviewing all the mentions of ->gradebookroles in the code, as a plausible way to find all the DB queries that might be affected.
1. grade/import/lib.php line 175: Seems to be OK. Hmm... unless we should change
"AND ra.id IS NULL" to "AND (ra.id IS NULL OR u.deleted = 1)"?
2. grade/lib.php class graded_users_iterator::init(): Two queries here, both of which will duplicate users if they have multiple role assignments. Yes. For example, this is used by all the export code. If you have a user with two roles, then they are included twice in the export file.
(By the way, it is crazy the way this code is doing the $ofields stuff. Surely that is not really necessary!)
3. grade/report/lib.php grade_report::grade_report constructor: Just copies $this->gradebookroles = $CFG->gradebookroles; No problem.
(Note that there is a nasty use of Error here, that gives the wrong place to go for the setting admin->appearance->graderoles)
4. grade/report/lib.php grade_report::get_numusers method: No problem with the multiple roles thing, because it is using COUNT(DISTINCT ...)) in includes u.delete = 0.
5. grade/report/grader/lib.php grade_report_grader::load_users method: Oh look at the comment at the top "// the MAX() magic is required in order to please PG". No, Postgres was pointing out this bug, and you chose to ignore it!
Anyway the queries here are wrong, but this is probably masked by the fact that get_records_sql eliminates duplicate rows when it converts the recordset to an array. Well, one of the queries does a SELECT DISTINCT, but those tend to give bad performance. Mind you, I am not sure that SELECT ... WHERE EXISTS is particularly efficient either.
(I also wonder why this method cannot use the graded_users_iterator class? Anyway, I will just fix the existing code.)
There is horrible duplicated code here. Yes, I will refactor.
6. grade/report/grader/lib.php grade_report_grader::get_avghtml method: This is where we started, and my previous commits should have fixed this. I just reviewed the code again and tweaked the coding style a bit.
7. mentions in mod/assignment/lib.php are not relevant to us (and appear to be fine on a quick look.)
Note that there are mentions of gradebookroles in other places in Moodle 2.0. For example, in 2.0 there are separate queries in the user report that are not present in 1.9. For now, let's get 1.9 right, before porting the changes to 2.0.
Note, I just did a quick test, which I think covered all the code I changed, and I think it worked for me.
OK, all these changes pushed to https://github.com/timhunt/moodle/compare/MOODLE_19_STABLE...MDL-20946_19. I am looking for review and testing please.