Skip to content

Refactor exercise accessibility into points cache - #1562

Open
ihalaij1 wants to merge 3 commits into
apluslms:masterfrom
ihalaij1:fix_1242
Open

ihalaij1 wants to merge 3 commits into
apluslms:masterfrom
ihalaij1:fix_1242

Conversation

@ihalaij1

@ihalaij1 ihalaij1 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

What?

Move reading and exercise accessibility checks onto cached points entries, including reveal state and module prerequisites. Cache requirement rules, and invalidate affected modules when thresholds, points, or prerequisite relations change.

Update course, exercise, and LTI templates to use the cached checks, and add coverage for accessibility and cache invalidation.

These changes require a fresh/invalidated cache or things will break, since the positional cache format is changed without changing its keys.

Why?

This trades larger cache payloads and initial prefetch work for less database work during rendering.

How?

  • Accessibility moves into points-cache entries, combining opening times, requirements, student points, and reveal state.
  • Templates delegate to that API instead of duplicating reveal checks.
  • Threshold definitions are prefetched and cached, with invalidation for rule changes, relation changes, moves, and deletions. Tested requirement checks execute without database queries.
  • LTI listings use points entries while preserving LTI links. Server-side permission enforcement remains unchanged.

Fixes #1242

@ihalaij1
ihalaij1 requested review from murhum1 and sayravai October 22, 2026 10:41
@ihalaij1 ihalaij1 moved this from Todo to Under review in A+ sprints Oct 22, 2026
@ihalaij1

Copy link
Copy Markdown
Contributor Author

@murhum1 @sayravai Could you help me review/test these cache changes?

The code is AI generated and I don't have a good understanding of how the custom A+ cache code works, so it makes understanding the changes difficult.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The incompatible positional cache format requires a coordinated cache reset, and the expanded invalidation paths warrant human validation.

No open issues 🎉

What changed in this PR

Moves reading and exercise accessibility checks into the points cache, addressing #1242 and reducing database work during rendering.

Changes:

  • Centralizes opening-time, prerequisite, and reveal-state checks in cached entries.
  • Caches prerequisite rules and expands invalidation for related model changes.
  • Updates templates and LTI listings to use points entries, with added accessibility and invalidation tests.
File Description
threshold/​models.py Ensures threshold point labels return strings.
lti_tool/​views.py Applies LTI links to points-cache entries.
lti_tool/​templates/​lti_tool/​lti_course.html Renders modules from the points cache.
exercise/​tests_cache.py Adds accessibility and prerequisite-cache invalidation coverage.
exercise/​templatetags/​exercise.py Delegates accessibility checks to cached entries.
exercise/​templates/​exercise/​_user_results.html Uses cached accessibility methods for result links.
exercise/​templates/​exercise/​_children.html Uses the combined entry accessibility check.
exercise/​cache/​points.py Implements cached accessibility and prerequisite evaluation.
exercise/​cache/​invalidate_util.py Identifies modules affected by prerequisite changes.
exercise/​cache/​basetypes.py Prefetches and caches requirement rules; registers invalidation signals.
course/​templates/​course/​_siblings.html Removes reveal checks now handled by accessibility methods.

Review effort: Balanced

@sayravai

Copy link
Copy Markdown
Contributor

Here is an (AI-generated) overall picture for reference of what is cached and when it gets invalidated, both before and after this PR...

Cached per-student properties (after PR 1562)

Three per-student entry layers, each keyed with the user_id plus a
show_unrevealed modifier. A dependency mechanism cascades upward:
CachedPointsData records its module entries and ModulePoints records its
exercise entries as dependencies, so when a child entry is regenerated after
invalidation, parent entries regenerate too ("We rely on a ModuleEntry being
invalid if any of the exercises are…" — CachedPointsData._generate_data).
No operation needs to flush the whole course.

Entry (key prefix) Cached properties
Exercise entry exercisepoints.<exId>.<userId> (ExercisePoints / LearningObjectPoints) Structure: parent, children, module link, model_answer_modules, category & status fields, order/link/URLs. Points: full submissions: List[SubmissionEntry] (per-submission grade, status, unofficial, hash, late penalty, group_id, url, is_assessed), _true_best_submission/_best_submission, last-submission fallback, graded, unofficial, forced_points, submission_count, passed, points/_true_points (reveal-masked), by-difficulty totals. Access: personal_deadline(_has_penalty), personal_max_submissions (deviations), feedback_revealed, feedback_reveal_time, show_zero_points_immediately, _expires_on, notified/unseen, confirmable_children, children_unconfirmed. Derived accessors (1562, computed not stored): is_revealed (parent chain + is_model_answer_revealeds), is_reading_accessible/is_exercise_accessible/is_accessible delegating to module + own reveal state.
Module entry modulepoints.<moduleId>.<userId> (ModulePoints + ModuleEntryBase) Content: name, introduction, link, order, status, opening_time, reading_opening_time, closing_time, points_to_pass, requirement_rules_text, children/module_index links. NEW in 1562: requirement_rules — the actual CourseModuleRequirement objects with threshold prefetch (passed_modules/categories/exercises via threshold__…, points) plus the rendered requirements strings — previously DB-fetched at render time. Points rollups: _true_points, _points, by-difficulty & unconfirmed dicts, submission_count, passed, module_goal_points, is_model_answer_revealed, confirmable_children, children_unconfirmed, _expires_on. NEW accessors: is_reading_accessible/is_exercise_accessible = opening time + _requirements_passed() evaluated against sibling points entries.
Instance entry instancepoints.<instId>.<userId> (CachedPointsData) modules/module_index/exercise_index (proxy tree), categories (per-category points rollups incl. by-difficulty/unconfirmed), total (Totals), is_on_lifesupport, lifesupport_start, points_created, url/course kwargs, paths.

What invalidates what

✅ = pre-existing, 🆕 = added by 1562. "via dependency" = entry regenerates
lazily when a child entry it depends on is rebuilt, not by a direct signal.

Operation (model, signal) Exercise entries Module entries Instance entry Notes / partial scope
Submission save/delete, submitters m2m change ✅ that student's entries for that exercise only (per submitter via with_user_ids) + entries of confirm_the_level siblings via dependency only via dependency only The classic hot path; nothing else touched
DeadlineRuleDeviation / MaxSubmissionsRuleDeviation save/delete ✅ same per-submitter exercise entries (+ confirm siblings) — via dependency Only personal_deadline/personal_max_submissions consumers
RevealRule (exercise feedback rule) save/delete ✅ that exercise's entries for its submitters (+ confirm siblings) — via dependency Per-student reveal flips land here
RevealRule (module model-solution rule) save/delete — ✅ affected students' module entries (ModulePoints.INVALIDATORS, with_user_ids(model_module)) via dependency Feeds is_model_answer_revealed → 1562's is_revealed
Notification save/delete ✅ exercise entries (notified/unseen) — via dependency Also fired for confirm siblings
LearningObject save/delete ✅ (id and parent_id, and whole-module via module_learning_objects) ✅ (its module's entries) ✅ Exercise entry embeds module times/status
CourseModule save ✅ all child exercise entries ✅ its module entries ✅
CourseModule delete 🆕 — ✅ + every module that has a requirement whose threshold passes this module (pre_delete → threshold_modules_for_target) ✅ pre_delete so passed_modules is still queryable
LearningObjectCategory save/delete ✅ its exercises ✅ its modules + 🆕 on delete, modules whose threshold passes this category ✅ (categories rollup) Category drives points rollups & thresholds
BaseExercise delete 🆕 — ✅ modules whose threshold passes this exercise (threshold_modules_for_target) — pre_delete variant
CourseModuleRequirement save/delete — ✅ target module (module_id) —
CourseModuleRequirement reassigned (module moved) 🆕 — ✅ the old module too (pre_save → previous_requirement_module reads the pre-update row) — Fixes "stale old module keeps dead rule" bug
Threshold save 🆕 — ✅ all modules with a requirement pointing at it — Content changes (name/rule fields) now invalidate
Threshold delete 🆕 — ✅ same modules (pre_delete) — Previously leaked live rows into cache
ThresholdPoints save/delete 🆕 — ✅ modules using that threshold; on reassignment, old threshold's modules too (pre_save) —
Membership edits to Threshold.passed_modules/categories/exercises (m2m) 🆕 — ✅ modules whose requirement uses any affected threshold (both directions: pk_set/reverse handling covers "threshold edited" and "module/exercise deleted/cleared") —
CourseInstance save — — ✅ instance entry lifesupport toggle etc.

Review-relevant observations

  1. Threshold edits invalidate module entries only — not exercise entries,
    not the rules' result. Correct by design in 1562 (requirement_rules are
    re-read with the module entry; results are re-evaluated per render against
    current points entries), but correctness leans entirely on the 🆕 signal
    list being exhaustive: there is no TTL behind it (TIMEOUT: None) — a
    missed signal is a permanently wrong lock until some other edit lands on
    the same key.
  2. Scope is genuinely surgical: a submission touches 1–few keys per
    member; a threshold edit touches only the module keys of courses that
    actually reference the threshold, across all students; the upward
    dependency revalidation means the fat instancepoints payload is rebuilt
    lazily, once, on next visit — not in the signal handler.

@ihalaij1

Copy link
Copy Markdown
Contributor Author

I'm running another Copilot review with the new "Max" preview option.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical cache-invalidation races and incompatible cached module formats can leave stale access decisions, produce incorrect module visibility, or crash prerequisite checks.

7 open issues

Review effort: Max

Comment thread exercise/cache/basetypes.py Resolved
Comment thread exercise/cache/basetypes.py Resolved
Comment thread exercise/cache/basetypes.py Resolved
Comment thread exercise/cache/basetypes.py Resolved
Comment thread exercise/tests_cache.py Resolved
@sayravai

Copy link
Copy Markdown
Contributor

I started to look into this yesterday by checking if there's some synergy between this and #1539 but turned out that is not much. The "best points" cache table of #1539 could potentially speed up cache generation in this PR, but turns out there are some edge cases where that table does not give 1:1 information to how the general caching works due to different handling of forced and invalidated points at least. So it's possible to use that table, but only after we've made sure they have compatible information.

Move reading and exercise accessibility checks onto cached points entries,
including reveal state and module prerequisites. Cache requirement rules and
invalidate affected modules when thresholds, points, or prerequisite relations
change.

Update course, exercise, and LTI templates to use the cached checks, and add
coverage for accessibility and cache invalidation.

Fixes apluslms#1242
@ihalaij1

Copy link
Copy Markdown
Contributor Author

I will run another expensive Copilot Max code review on this pull request next month when we have more AI credits.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread exercise/cache/basetypes.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Under review

Development

Successfully merging this pull request may close these issues.

Refactor exercise_accessible and is_revealed

4 participants