Skip to content

Educational Mode

smattymatty edited this page Aug 25, 2025 · 1 revision

🎓 Educational Mode Guide

Transform every performance issue into a learning opportunity. Mercury doesn't just find problems - it teaches you to understand and fix them.

What is Educational Mode?

Educational Mode is Mercury's unique approach to performance testing that combines:

  • Interactive learning while you test
  • Real-time explanations of issues
  • Quizzes to reinforce understanding
  • Progress tracking to see improvement
  • Gradual complexity as you learn

Philosophy: Learn by Doing

Following the 80-20 Human-in-the-Loop philosophy:

  • 80% Tool Assistance: Mercury finds issues, explains them, suggests fixes
  • 20% Human Learning: You understand why, make decisions, apply knowledge

Starting Your Learning Journey

Step 1: Enable Student Profile

# First-time setup
mercury-test --profile student

# This enables:
# ✅ Learn plugin - Interactive tutorials
# ✅ Wizard plugin - Guided navigation  
# ✅ Hints plugin - Contextual tips
# ✅ Discovery plugin - Helpful errors

Step 2: Take the Placement Quiz

# Assess your current knowledge
mercury-test --learn --placement-quiz

📚 MERCURY PLACEMENT QUIZ
════════════════════════════════════════
This quiz will help Mercury adapt to your level.

Q1: What is an N+1 query problem?
   A) Network timeout issue
   B) Multiple queries for related data
   C) Missing database index
   D) Memory overflow

Your answer: B
✅ Correct!

[... more questions ...]

Your Level: Intermediate
Recommended starting topic: Database Optimization

Step 3: Begin Learning

# Start with recommended topic
mercury-test --learn database-optimization

# Or choose your topic
mercury-test --learn --list-topics
Available Topics:
1. 🔍 N+1 Queries (Beginner)
2. 📊 Database Indexing (Beginner)
3. 💾 Caching Strategies (Intermediate)
4. 🧠 Memory Optimization (Intermediate)
5. ⚡ Query Optimization (Advanced)

Core Learning Features

📖 Interactive Tutorials

Mercury provides slideshow-style tutorials that teach concepts:

mercury-test --learn n1-queries
📚 INTERACTIVE TUTORIAL: N+1 Queries
═══════════════════════════════════════════════════════

[Slide 1/8] Introduction
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Welcome! Today we'll learn about N+1 queries,
one of the most common performance problems.

By the end, you'll be able to:
✓ Identify N+1 patterns
✓ Understand why they're slow
✓ Fix them effectively

Press ENTER to continue...

[Slide 2/8] What is N+1?
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Imagine you're displaying a list of books with authors:

books = Book.objects.all()  # 1 query
for book in books:
    print(book.author.name)  # N queries (1 per book)

With 100 books = 101 queries total!
That's why it's called "N+1"

🤔 Think: Why is this inefficient?
Press ENTER to continue...

[Slide 3/8] The Impact
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Each query has overhead:
• Network round trip: ~1-2ms
• Query parsing: ~0.5ms  
• Result processing: ~0.5ms

100 books × 2ms = 200ms just in overhead!
Plus actual query time = slow page loads

Press ENTER to continue...

🎮 Interactive Quizzes

Test your understanding with contextual quizzes:

mercury-test --learn --quiz
🎯 QUIZ TIME: Performance Optimization
═══════════════════════════════════════════════════════

Question 1/5
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
You have this view:

def user_list(request):
    users = User.objects.all()
    return render(request, 'users.html', {'users': users})

Template shows: {{ user.profile.bio }}

What's the performance issue?

A) Missing pagination
B) N+1 query on profile
C) No caching
D) Unindexed query

Your answer: B

✅ Correct! 

Explanation: Each user triggers a separate query to fetch 
their profile. With 50 users = 51 queries total.

Fix: users = User.objects.select_related('profile')

Press ENTER for next question...

📊 Real-Time Learning

Mercury explains issues as they occur in your tests:

# Your test
class TestAPI(DjangoMercuryAPITestCase):
    def test_user_endpoint(self):
        response = self.client.get('/api/users/')

Output in educational mode:

🎓 LEARNING MOMENT DETECTED
═══════════════════════════════════════════════════════

Found: N+1 Query Pattern
Location: UserSerializer.get_profile_data()

📖 What's happening:
1. First query gets all users (1 query)
2. For each user, accessing user.profile (N queries)
3. Total: N+1 queries

💡 Why this matters:
- 100 users = 101 queries
- Each query adds ~2ms overhead
- Page loads become slower as data grows

🔧 How to fix:
Option 1: select_related (for ForeignKey)
  queryset = User.objects.select_related('profile')

Option 2: prefetch_related (for ManyToMany)
  queryset = User.objects.prefetch_related('groups')

📚 Want to learn more?
Run: mercury-test --learn n1-queries

Press ENTER to continue testing...

📈 Progress Tracking

Mercury tracks your learning journey:

mercury-test --learn --progress
📊 YOUR LEARNING PROGRESS
═══════════════════════════════════════════════════════

Overall Level: Intermediate (750 XP)
════════════════████████████░░░░░░░ 65%

Topics Mastered:
✅ N+1 Queries          (10/10 quizzes)
✅ Basic Indexing       (8/8 quizzes)
✅ Response Time        (5/5 quizzes)

Currently Learning:
🔄 Caching Strategies   ████████░░░░ 70%
🔄 Memory Optimization  ███░░░░░░░░░ 30%

Not Started:
⭕ Advanced Query Optimization
⭕ Database Sharding
⭕ Async Performance

Achievements:
🏆 First N+1 Fixed
🏆 Speed Demon (50ms response time)
🏆 Query Master (optimized 10 endpoints)

Next Goal: Complete Caching Strategies
Estimated Time: 15 minutes

💡 Contextual Hints

Get tips based on your actual test results:

# After running slow tests
mercury-test users.tests
💡 PERFORMANCE TIP
═══════════════════════════════════════════════════════
Your tests took 142 seconds to complete.

Based on your results, here are personalized tips:

1. Run tests in parallel:
   mercury-test --parallel 4
   
   This could reduce time to ~35 seconds

2. You have 3 tests with 100+ queries each:
   - test_user_list (234 queries)
   - test_product_search (189 queries)  
   - test_order_history (156 queries)
   
   These likely have N+1 issues. Learn about them:
   mercury-test --learn n1-queries

3. Use --failfast during development:
   mercury-test --failfast
   
   Stop on first failure to save time

Would you like to learn more? (y/n)

Learning Paths

🌱 Beginner Path

For developers new to performance optimization:

Week 1: Fundamentals

# Day 1-2: Understanding performance metrics
mercury-test --learn performance-basics
mercury-test --learn response-time
mercury-test --learn --quiz basics

# Day 3-4: Database queries
mercury-test --learn database-basics
mercury-test --learn n1-queries

# Day 5: Practice
mercury-test --profile student
# Run your actual tests and learn from issues

Week 2: Common Patterns

# Learn about common issues
mercury-test --learn common-patterns
mercury-test --learn debugging-slow-tests

# Practice fixing
mercury-test --wizard  # Guided test selection

🚀 Intermediate Path

For developers with basic knowledge:

Focus Areas

# Database optimization
mercury-test --learn indexing
mercury-test --learn query-optimization

# Caching
mercury-test --learn caching-strategies
mercury-test --learn cache-invalidation

# Memory management
mercury-test --learn memory-optimization

🎯 Advanced Path

For experienced developers:

# Complex topics
mercury-test --learn database-sharding
mercury-test --learn async-performance
mercury-test --learn microservices-performance

# Create custom learning content
mercury-test --learn --create-content

Educational Output Examples

Beginner-Friendly Explanations

❌ TEST FAILED: test_api_endpoint
═══════════════════════════════════════════════════════

Don't worry! Let's understand what happened:

1️⃣ What went wrong:
   Your endpoint took 523ms to respond
   
2️⃣ Why this is a problem:
   Users expect pages to load in under 200ms
   Slow pages = frustrated users = lost customers
   
3️⃣ What caused this:
   Found 89 database queries (that's a lot!)
   Looks like an N+1 pattern in your serializer
   
4️⃣ How to fix it:
   Add .select_related('author') to your queryset
   This will reduce queries from 89 to just 2!
   
5️⃣ Learn more:
   mercury-test --learn n1-queries
   
You're doing great! Every expert started here. 💪

Progressive Complexity

As you improve, explanations become more technical:

⚠️ Performance Issue: N+1 in UserSerializer.to_representation()

Queries: 45 (1 + 44 profile lookups)
Impact: O(n) query complexity
Pattern: ForeignKey traversal without select_related

Suggested optimization:
queryset = User.objects.select_related('profile')

Alternative: Use prefetch_related() if you need profile.groups
Consider: only() if you need specific fields

Benchmark: Expected 95% query reduction

Interactive Learning Sessions

Live Coding Fixes

Mercury can guide you through fixes:

mercury-test --learn --interactive-fix
🔧 INTERACTIVE FIX SESSION
═══════════════════════════════════════════════════════

Issue found: N+1 in views.py:45

Let's fix this together!

Step 1: Open views.py
Step 2: Find line 45 (UserListView)

Current code:
  users = User.objects.all()

Suggested fix:
  users = User.objects.select_related('profile')

Did you make the change? (y/n): y

Great! Now let's test if it worked:
Running: mercury-test users.tests.TestUserList

✅ Success! Queries reduced from 101 to 2!
🎉 You just made your app 50x faster!

Want to fix another issue? (y/n):

Pair Learning

Learn with Mercury as your pair programmer:

mercury-test --learn --pair-mode
👥 PAIR LEARNING MODE
═══════════════════════════════════════════════════════

Hi! I'm Mercury, your performance pair programmer.
Let's optimize your Django app together!

What would you like to work on?
1. Fix a slow test
2. Learn a new concept
3. Review my code
4. Optimize an endpoint

Your choice: 1

Great! Let's run your tests first:
mercury-test --show-worst 1

Found slowest test: test_dashboard (4.5 seconds)

Let me analyze this...
- 234 queries (wow, that's a lot!)
- 3 distinct N+1 patterns
- Missing database indexes

Should we start with the N+1 issues? They're usually
the easiest wins. (y/n):

Gamification Elements

🏆 Achievements

Unlock achievements as you learn:

mercury-test --achievements
🏆 YOUR ACHIEVEMENTS
═══════════════════════════════════════════════════════

Unlocked (12/30):
✅ First Test - Ran your first Mercury test
✅ N+1 Hunter - Fixed your first N+1 query
✅ Speed Demon - Achieved <50ms response time
✅ Query Optimizer - Reduced queries by 90%
✅ Cache Master - Implemented effective caching
✅ Index Wizard - Added your first database index
✅ Memory Saver - Reduced memory usage by 50%
✅ Parallel Pioneer - Used parallel testing
✅ Quick Learner - Completed 5 tutorials
✅ Quiz Champion - Perfect score on a quiz
✅ Performance Guardian - Added performance tests
✅ Team Player - Shared knowledge with team

Locked:
🔒 Grand Master - All topics mastered
🔒 Contributor - Contributed to Mercury
🔒 Mentor - Helped 5 other developers

Next achievement: "CI/CD Hero" (2/3 complete)
Add Mercury to your CI pipeline to unlock!

📊 Leaderboards (Team Feature)

mercury-test --team-leaderboard
📊 TEAM PERFORMANCE LEADERBOARD - This Week
═══════════════════════════════════════════════════════

1. 🥇 Sarah Chen
   Fixed: 12 performance issues
   Learning: Advanced (Level 8)
   Best optimization: 95% query reduction

2. 🥈 James Rodriguez  
   Fixed: 8 performance issues
   Learning: Intermediate (Level 5)
   Best optimization: 80% response time improvement

3. 🥉 You
   Fixed: 6 performance issues
   Learning: Intermediate (Level 4)
   Best optimization: 70% memory reduction

Team Goals This Sprint:
[████████░░] 80% - Reduce average response time
[██████░░░░] 60% - Fix N+1 queries
[██████████] 100% - Add performance tests ✅

Customizing Educational Experience

Adjust Learning Speed

# mercury_config.toml
[profiles.student]
learning_pace = "relaxed"  # relaxed, normal, intensive
auto_pause_on_issues = true
show_hints_always = true
quiz_frequency = "often"  # never, sometimes, often, always
explanation_detail = "high"  # low, medium, high, maximum

Focus on Specific Areas

# Focus learning on your weak points
mercury-test --learn --focus database

# Skip topics you know
mercury-test --learn --skip n1-queries,indexing

# Advanced topics only
mercury-test --learn --level advanced

Create Learning Groups

# Share learning with your team
mercury-test --learn --share-progress team@example.com

# Join a learning group
mercury-test --learn --join-group django-beginners

# Compete with friends
mercury-test --learn --challenge @colleague

Graduating from Educational Mode

Signs You're Ready

You might be ready for expert mode when:

  • Consistently scoring 9/10 on quizzes
  • Fixing issues without reading explanations
  • Understanding trade-offs between solutions
  • Teaching others what you've learned

Transition Process

# Week 1: Reduce educational features
mercury-test --profile student --no-wizard

# Week 2: Less hand-holding
mercury-test --profile student --no-hints

# Week 3: Try expert mode
mercury-test --profile expert

# But keep learning available
mercury-test --profile expert --learn  # When needed

Keep Learning Features

Even experts benefit from continuous learning:

# mercury_config.toml
[profiles.expert_with_learning]
base = "expert"
plugins.enabled = ["discovery", "learn"]
learn.level = "advanced"
learn.auto_activate = false  # Manual activation only

Resources for Continuous Learning

Built-in Documentation

# View all learning resources
mercury-test --learn --resources

# Specific topic deep-dive
mercury-test --learn --deep-dive caching

# Best practices guide
mercury-test --learn --best-practices

Community Learning

  • Discord: Join study groups
  • GitHub Discussions: Share learning experiences
  • Blog Posts: Write about what you learned
  • Contribute: Add new learning content

Common Learning Questions

"How long does it take to learn?"

  • Basics: 1-2 weeks (30 min/day)
  • Intermediate: 1-2 months
  • Advanced: Ongoing journey

"What if I get stuck?"

# Get unstuck
mercury-test --learn --help-me

# Mercury will:
# 1. Analyze your recent tests
# 2. Identify knowledge gaps
# 3. Suggest specific tutorials
# 4. Provide example fixes

"Can I contribute learning content?"

Yes! Create tutorials for others:

# Create a new tutorial
mercury-test --learn --create-tutorial "My Topic"

# Submit to community
mercury-test --learn --submit-content

Next Steps


Remember: Every expert was once a beginner. The difference is they kept learning.

Django Mercury Wiki

🏠 Overview

Clone this wiki locally