kolibri icon indicating copy to clipboard operation
kolibri copied to clipboard

Migrate ExamViewset to serializer-derived values pattern

Open rtibbles opened this issue 9 months ago • 13 comments

❌ This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues.

Overview

Migrate ExamViewset from explicit values/field_map to serializer-derived pattern as part of the BaseValuesViewset refactor (#14036).

Complexity: High Target branch: develop

Context

ExamViewset in kolibri/core/exams/api.py serves two models (Exam and DraftExam) from one viewset. It has multiple values tuples (common_values, values for Exam, draft_values for DraftExam), a field_map with a rename (assignments → assignment_collections) and a lambda for instant_report_visibility, and an annotate_queryset() using annotate_array_aggregate. It already has serializer_class = ExamSerializer.

The viewset has a custom list() that merges and sorts results from both models, serialize_draft() for the draft model, custom get_object(), filter_querysets(), update(), and serialize_object() methods. The update() re-serializes after write because the model type may change (Draft → Exam) during save.

The Change

Remove the explicit values tuples and field_map from ExamViewset so that values and field mappings are derived from ExamSerializer. The dual-model nature and custom list() merge logic will need careful handling — the serializer must work for both models' value sets. The custom serialize_draft() will need to work with the serializer-derived pattern.

See #14036 for the overall pattern and FacilityUserViewSet in kolibri/core/auth/api.py for a concrete migration example.

Relocation

After the migration commits, extract the Exam domain into kolibri/core/exams/viewsets/exam.py as a pure-move commit: the viewset(s), their serializers (inline above the viewsets), and any domain-specific filters and permission classes (ExamFilter, ExamPermissions, with the serializers.py contents inline). Update imports (api_urls.py, tests, cross-references).

Moving code breaks GitHub blame (local git blame -C -C still works), so digest the history the move obscures:

  1. Run blame over the code being moved; flag hunks whose purpose isn't evident from the code or tests (odd guards, magic orderings, special cases).
  2. Chase each flagged hunk to its originating PR/issue; where the rationale is non-obvious and load-bearing, carry it forward as a code comment citing the reference.
  3. Where the rationale turns out to be obsolete, remove the code as part of the migration commits rather than annotating it.

This is the only issue touching kolibri/core/exams/api.py and serializers.py; delete both after the move.

Out of Scope

  • Changes to the API response shape — the API contract must not change
  • Modifications to existing tests — if tests need to change, the migration is wrong
  • Write-path changes — only the read serialization path is affected
  • Changes to the dual-model merge logic in list()

Acceptance Criteria

  • [ ] Explicit values tuples and field_map removed from ExamViewset

  • [ ] ExamSerializer updated with all read-path fields and correct sources

  • [ ] Both Exam and DraftExam serialization continues to work correctly

  • [ ] list() merge of both models produces identical output

  • [ ] instant_report_visibility None → True mapping handled via serializer

  • [ ] Existing API tests pass unchanged

  • [ ] Benchmark comparison passes (data hash match + no performance regression)

  • [ ] The migrated domain lives in kolibri/core/exams/viewsets/exam.py, moved as a pure-move commit separate from import updates

  • [ ] Comments citing the originating PR/issue added where blame digestion found non-obvious, load-bearing rationale

  • [ ] Remaining non-migrating code moved; kolibri/core/exams/api.py/serializers.py deleted

Testing

  • Before migrating: verify that existing test coverage is adequate. If the viewset has insufficient API tests, write them first to capture the current behavior. Tests must pass before and after migration without modification.
  • Benchmark: run the benchmark script before and after the migration using the same data:
    python integration_testing/scripts/viewset_serialization_benchmark.py \
        kolibri.core.exams.api.ExamViewset \
        --inherit-kolibri-home -o baseline.json
    
    # ... make changes ...
    
    python integration_testing/scripts/viewset_serialization_benchmark.py \
        kolibri.core.exams.api.ExamViewset \
        --inherit-kolibri-home --compare baseline.json
    
  • The benchmark comparison must pass — this validates that the data output is identical and there is no performance regression.
  • Include the benchmark before/after comparison in the pull request description.

Benchmark data setup: import the Kolibri QA channel and generate user data before benchmarking:

kolibri manage importchannel network 95a52b386f2c485cb97dd60901674a98
kolibri manage importcontent network 95a52b386f2c485cb97dd60901674a98
kolibri manage generateuserdata --num-exams 10

References

  • Tracking issue: #14036
  • Benchmark script: integration_testing/scripts/viewset_serialization_benchmark.py
  • Example migration: FacilityUserViewSet in kolibri/core/auth/api.py

AI usage

This issue was drafted with Claude Code assistance, reviewed and directed by @rtibbles.

  • After the move, the benchmark comparison run uses the new dotted path (e.g. kolibri.core.exams.viewsets.exam.ExamViewset).

rtibbles avatar Mar 02 '26 04:03 rtibbles

Watching for resolution on behalf of learningequality/kolibri#14302.

rtibblesbot avatar Jun 09 '26 15:06 rtibblesbot

The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.

rtibblesbot avatar Jun 11 '26 08:06 rtibblesbot

The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.

rtibblesbot avatar Jun 12 '26 00:06 rtibblesbot

I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.

rtibblesbot avatar Jun 12 '26 22:06 rtibblesbot

I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.

rtibblesbot avatar Jun 14 '26 21:06 rtibblesbot

I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.

rtibblesbot avatar Jun 15 '26 21:06 rtibblesbot

I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.

rtibblesbot avatar Jun 15 '26 21:06 rtibblesbot

PHASE_COMPLETE

All reviewer feedback has been addressed and CI re-triggered.

Reviewer thread resolution:

  • Thread (PRRT_kwDOAvqWa86I22Jm, OUTDATED): Fixed — used directly, removing .
  • Thread (PRRT_kwDOAvqWa86I23fK): Fixed — removed from //; they are now excluded from the DB query via on .
  • Thread (PRRT_kwDOAvqWa86I24cU): No code change needed — is a SQL annotation from and cannot be deferred (it must appear in the main query). Declared as in the serializer to include it in .
  • Thread (PRRT_kwDOAvqWa86I2495): No code change needed — marks , , , , , , as to prevent clients from setting them via POST/PATCH. Django model doesn't mark them so DRF would otherwise auto-generate them as writable.
  • Thread (PRRT_kwDOAvqWa86I27JM, OUTDATED): Fixed — removed ; uses .

CI: The failing job was a Docker Hub network timeout pulling — infrastructure, not code. Force-pushed 3 squashed commits incorporating all reviewer feedback, triggering a new CI run.

rtibblesbot avatar Jun 15 '26 22:06 rtibblesbot

PHASE_COMPLETE

All reviewer feedback has been addressed and CI re-triggered.

Reviewer thread resolution:

  • Thread (PRRT_kwDOAvqWa86I22Jm, OUTDATED): Fixed — QuestionSourceSerializer(many=True) used directly, removing ListField(child=QuestionSourceSerializer()).
  • Thread (PRRT_kwDOAvqWa86I23fK): Fixed — removed write_only=True from assignments/learner_ids/draft; they are now excluded from the DB values() query via deferred_fields = ("assignments", "learner_ids", "draft") on ExamViewset.
  • Thread (PRRT_kwDOAvqWa86I24cU): No code change needed — assignment_collections is a SQL annotation from annotate_queryset and cannot be deferred (it must appear in the main values() query). Declared as ListField(read_only=True) in the serializer to include it in _values.
  • Thread (PRRT_kwDOAvqWa86I2495): No code change needed — extra_kwargs marks seed, question_count, creator, data_model_version, date_created, date_archived, date_activated as read_only=True to prevent clients from setting them via POST/PATCH. Django's ModelSerializer auto-generates them as writable (the model doesn't mark them editable=False), so extra_kwargs overrides that.
  • Thread (PRRT_kwDOAvqWa86I27JM, OUTDATED): Fixed — removed _RawListField; question_sources uses QuizSectionSerializer(many=True, required=False).

CI failure: The "Python tests" failure was a transient Docker Hub network timeout pulling python:3.7-buster — infrastructure, not code. All Python 3.8–3.14 test jobs passed. Force-pushed 3 squashed commits incorporating all reviewer feedback, triggering a new CI run.

rtibblesbot avatar Jun 15 '26 22:06 rtibblesbot

PHASE_COMPLETE

All reviewer feedback has been addressed. Verification summary:

Thread resolution:

  • Thread (PRRT_kwDOAvqWa86I22Jm, OUTDATED): Fixed — QuestionSourceSerializer(many=True) used directly in QuizSectionSerializer.questions, removing the ListField(child=QuestionSourceSerializer()) wrapper.
  • Thread (PRRT_kwDOAvqWa86I23fK): Fixed — removed write_only=True from assignments, learner_ids, and draft. They are now excluded from the DB values() query via deferred_fields = ('assignments', 'learner_ids', 'draft') on ExamViewset, which accurately describes their semantics.
  • Thread (PRRT_kwDOAvqWa86I24cU): No code change needed — assignment_collections is a SQL annotation computed in the main query by annotate_queryset. Excluding it from _values via deferred_fields would break the annotation entirely (it must be fetched in the main values() call). Declared as ListField(read_only=True) to include it in _values.
  • Thread (PRRT_kwDOAvqWa86I2495): No code change needed — extra_kwargs marks seed, question_count, creator, data_model_version, date_created, date_archived, date_activated as read_only=True to prevent clients from setting them via POST/PATCH. Django's ModelSerializer auto-generates them as writable (the model doesn't mark them editable=False), so extra_kwargs overrides that.
  • Thread (PRRT_kwDOAvqWa86I27JM, OUTDATED): Fixed — removed _RawListField; question_sources now uses QuizSectionSerializer(many=True, required=False) directly.

Verification: All 85 exam API tests pass.

rtibblesbot avatar Jun 15 '26 22:06 rtibblesbot

The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.

rtibblesbot avatar Jun 16 '26 01:06 rtibblesbot

The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.

rtibblesbot avatar Jun 22 '26 04:06 rtibblesbot

The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.

rtibblesbot avatar Jun 22 '26 22:06 rtibblesbot