#!/usr/bin/env python3 """Benchmark Django 6.1.3 password timing-attack mitigation and Admin ChangeList N+1 vs list_select_related latency on `desk/`. Writes recordings/ch11-bench.txt. """ from __future__ import annotations import statistics import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk def median_ms(fn, *, trials: int = 5, loops: int = 1) -> float: fn() # warmup samples = [] for _ in range(trials): t0 = time.perf_counter() for _ in range(loops): fn() dt_ms = (time.perf_counter() - t0) * 1e3 / loops samples.append(dt_ms) return statistics.median(samples) def main() -> None: seeded = boot_desk() from django.contrib import admin from django.contrib.auth import authenticate, get_user_model from django.contrib.auth.hashers import PBKDF2PasswordHasher from django.contrib.messages.storage.fallback import FallbackStorage from django.contrib.sessions.backends.db import SessionStore from django.test import RequestFactory from newsroom.admin import StoryAdmin from newsroom.models import Desk, Edition, Reporter, Story from seed import EDITOR_PASSWORD, EDITOR_USERNAME User = get_user_model() rec = Recorder( "ch11-bench", "Django 6.1.3 benchmark on SQLite (in-memory): auth timing & Admin ChangeList", ) # 1. Password timing-attack mitigation at 1,500,000 PBKDF2 iterations (5 trials) with rec.block("1. authenticate() timing-attack mitigation (1,500,000 PBKDF2 iters, 5 trials, ms)"): legacy_hash = PBKDF2PasswordHasher().encode( "legacy-secret", salt="benchsalt001", iterations=100_000 ) User.objects.create( username="legacy_user", email="legacy@desk.example", is_staff=True, password=legacy_hash, ) cases = [ ( "real user · valid password (1.5M)", lambda: authenticate(username=EDITOR_USERNAME, password=EDITOR_PASSWORD), ), ( "real user · wrong password (1.5M)", lambda: authenticate(username=EDITOR_USERNAME, password="wrong-password"), ), ( "nonexistent user · dummy hash (1.5M)", lambda: authenticate(username="no_such_editor", password="wrong-password"), ), ( "legacy 100k hash · wrong + harden_runtime", lambda: authenticate(username="legacy_user", password="wrong-password"), ), ] rec.emit(f"{'auth_path':<44s} {'median_ms':>10s} {'rel':>8s}") base_ms = None for label, fn in cases: ms = median_ms(fn, trials=5, loops=1) if base_ms is None: base_ms = ms rec.emit(f"{label:<44s} {ms:10.1f} {ms / base_ms:7.2f}x") # 2. Admin ChangeList N+1 storm vs list_select_related (25 stories, 7 trials) with rec.block("2. StoryAdmin ChangeList render over 25 stories (7 trials, ms/render)"): desks = list(Desk.objects.all()) reporters = list(Reporter.objects.all()) editions = list(Edition.objects.all()) Story.objects.bulk_create( [ Story( headline=f"Bench wire story #{i:02d}", slug=f"bench-wire-{i:02d}", body="Bench story body.", priority=2, status=Story.Status.PUBLISHED, desk=desks[i % len(desks)], reporter=reporters[i % len(reporters)], edition=editions[i % len(editions)], ) for i in range(1, 20) ] ) rf = RequestFactory() editor = seeded["editor"] class CallableNoSelectAdmin(StoryAdmin): list_display = ("headline", "byline", "priority", "status") def byline(self, obj): return f"{obj.reporter.name} ({obj.desk.section_code} · {obj.edition.slug})" class CallableWithSelectAdmin(CallableNoSelectAdmin): list_select_related = ("desk", "reporter", "edition") class CallableNoFullCountAdmin(CallableWithSelectAdmin): show_full_result_count = False admin_cases = [ ("callable list_display (N+1 storm)", CallableNoSelectAdmin), ("default StoryAdmin (auto select_related)", StoryAdmin), ("callable + list_select_related", CallableWithSelectAdmin), ("callable + select_related + no full count", CallableNoFullCountAdmin), ] rec.emit(f"{'changelist_config':<44s} {'sql':>5s} {'median_ms':>10s} {'speedup':>8s}") base_cl_ms = None for label, ma_cls in admin_cases: ma = ma_cls(Story, admin.site) def render_once(): req = rf.get("/admin/newsroom/story/") req.user = editor req.session = SessionStore() req._messages = FallbackStorage(req) resp = ma.changelist_view(req) resp.render() # Count exact SQL queries req_q = rf.get("/admin/newsroom/story/") req_q.user = editor req_q.session = SessionStore() req_q._messages = FallbackStorage(req_q) with rec.capture_sql(log=False) as sql: resp_q = ma.changelist_view(req_q) resp_q.render() ms = median_ms(render_once, trials=7, loops=3) if base_cl_ms is None: base_cl_ms = ms rec.emit(f"{label:<44s} {sql.count:5d} {ms:10.2f} {base_cl_ms / ms:7.2f}x") out = rec.write() print(f"wrote {out.relative_to(Path.cwd()) if out.is_relative_to(Path.cwd()) else out}") if __name__ == "__main__": main()