File size: 41,896 Bytes
bee9bbb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 | """Coursera business state on the generated site-bound backend seam."""
from __future__ import annotations
import json
import sqlite3
import threading
from contextlib import contextmanager
from typing import Any, Iterator
from websitebench.local_clone_auth import LocalAuthStore
from websitebench.site_backend import SiteBackend
from backend import assignment_db, checkout
from backend.site_backend_integration import open_site_services
from catalog import load_catalog_seed
SITE_ID = "33"
COURSE_ID = "deep-learning-specialization"
FROZEN_TIME = "2026-08-16T00:00:00Z"
PUBLIC_PREVIEW_LESSON_IDS = {
"lesson-neural-intro",
"lesson-forward-propagation",
}
SEED_ACCOUNTS = [
{
"subject_id": "learner-in-progress",
"email": "progress@coursera.test",
"display_name": "Progress Learner",
"password": "Progress-Learner-33",
},
{
"subject_id": "learner-empty",
"email": "empty@coursera.test",
"display_name": "Empty Learner",
"password": "Empty-Learner-33",
},
]
MODULES = [
("module-neural-foundations", 1, "Neural network foundations"),
("module-improving-networks", 2, "Improving deep networks"),
("module-ml-strategy", 3, "Machine learning strategy"),
]
LESSONS = [
("lesson-neural-intro", "module-neural-foundations", 1, "Welcome to neural networks", "Understand neurons, layers, and supervised learning.", 1),
("lesson-forward-propagation", "module-neural-foundations", 2, "Forward propagation", "Trace data through a compact neural network.", 1),
("lesson-optimization", "module-improving-networks", 1, "Optimization methods", "Compare gradient descent and adaptive optimization.", 0),
("lesson-regularization", "module-improving-networks", 2, "Regularization", "Reduce overfitting with deterministic exercises.", 0),
("lesson-error-analysis", "module-ml-strategy", 1, "Error analysis", "Prioritize model improvements from local examples.", 0),
("lesson-transfer-learning", "module-ml-strategy", 2, "Transfer learning", "Reuse representations in a bounded offline scenario.", 0),
]
QUIZZES = [
("quiz-neural-foundations", "module-neural-foundations", "Foundations check", "Which item transforms weighted inputs?", ["Activation function", "Invoice", "Cookie"], "Activation function", "Correct: an activation function transforms weighted inputs.", "Review the lesson: activations transform weighted inputs."),
("quiz-improving-networks", "module-improving-networks", "Optimization check", "Which technique can reduce overfitting?", ["Regularization", "Remote checkout", "Public review"], "Regularization", "Correct: regularization can reduce overfitting.", "Review the regularization lesson before retrying."),
("quiz-ml-strategy", "module-ml-strategy", "Strategy check", "What should guide the next model improvement?", ["Error analysis", "A live payment", "An external email"], "Error analysis", "Correct: error analysis guides focused improvements.", "Review error analysis and try again."),
]
_SCHEMA = [
"""CREATE TABLE IF NOT EXISTS coursera_schema_migrations (
migration_id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_profiles (
subject_id TEXT PRIMARY KEY, display_name TEXT NOT NULL,
onboarding_complete INTEGER NOT NULL CHECK(onboarding_complete IN (0,1)),
current_role TEXT NOT NULL, learning_goal TEXT NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_modules (
module_id TEXT PRIMARY KEY, position INTEGER NOT NULL UNIQUE,
title TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_lessons (
lesson_id TEXT PRIMARY KEY, module_id TEXT NOT NULL REFERENCES coursera_modules(module_id),
position INTEGER NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL,
preview INTEGER NOT NULL CHECK(preview IN (0,1)), UNIQUE(module_id,position))""",
"""CREATE TABLE IF NOT EXISTS coursera_quizzes (
quiz_id TEXT PRIMARY KEY, module_id TEXT NOT NULL UNIQUE REFERENCES coursera_modules(module_id),
title TEXT NOT NULL, question TEXT NOT NULL, choices_json TEXT NOT NULL,
correct_answer TEXT NOT NULL, feedback_correct TEXT NOT NULL,
feedback_incorrect TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_enrollments (
enrollment_id INTEGER PRIMARY KEY AUTOINCREMENT, owner_subject_id TEXT NOT NULL,
course_id TEXT NOT NULL, track TEXT NOT NULL CHECK(track IN ('free','audit','paid')),
status TEXT NOT NULL CHECK(status IN ('active','canceled')),
created_at TEXT NOT NULL, canceled_at TEXT,
UNIQUE(owner_subject_id,course_id))""",
"""CREATE TABLE IF NOT EXISTS coursera_lesson_progress (
owner_subject_id TEXT NOT NULL, lesson_id TEXT NOT NULL REFERENCES coursera_lessons(lesson_id),
completed INTEGER NOT NULL CHECK(completed IN (0,1)), updated_at TEXT NOT NULL,
PRIMARY KEY(owner_subject_id,lesson_id))""",
"""CREATE TABLE IF NOT EXISTS coursera_bookmarks (
owner_subject_id TEXT NOT NULL, lesson_id TEXT NOT NULL REFERENCES coursera_lessons(lesson_id),
created_at TEXT NOT NULL, PRIMARY KEY(owner_subject_id,lesson_id))""",
"""CREATE TABLE IF NOT EXISTS coursera_resume_state (
owner_subject_id TEXT PRIMARY KEY, lesson_id TEXT NOT NULL REFERENCES coursera_lessons(lesson_id),
updated_at TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_quiz_attempts (
attempt_id INTEGER PRIMARY KEY AUTOINCREMENT, owner_subject_id TEXT NOT NULL,
quiz_id TEXT NOT NULL REFERENCES coursera_quizzes(quiz_id), answer TEXT NOT NULL,
score INTEGER NOT NULL CHECK(score IN (0,100)), feedback TEXT NOT NULL,
created_at TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_reviews (
owner_subject_id TEXT NOT NULL, course_id TEXT NOT NULL,
rating INTEGER NOT NULL CHECK(rating BETWEEN 1 AND 5), review_text TEXT NOT NULL,
updated_at TEXT NOT NULL, PRIMARY KEY(owner_subject_id,course_id))""",
"""CREATE TABLE IF NOT EXISTS coursera_preferences (
owner_subject_id TEXT PRIMARY KEY, language TEXT NOT NULL, timezone TEXT NOT NULL,
email_updates INTEGER NOT NULL CHECK(email_updates IN (0,1)),
product_updates INTEGER NOT NULL DEFAULT 0 CHECK(product_updates IN (0,1)),
course_updates INTEGER NOT NULL DEFAULT 0 CHECK(course_updates IN (0,1)),
updated_at TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_help_feedback (
owner_subject_id TEXT PRIMARY KEY,
helpful INTEGER NOT NULL CHECK(helpful IN (0,1)),
updated_at TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_weekly_targets (
owner_subject_id TEXT PRIMARY KEY,
minutes INTEGER NOT NULL CHECK(minutes BETWEEN 15 AND 1200),
updated_at TEXT NOT NULL)""",
"""CREATE TABLE IF NOT EXISTS coursera_lesson_reactions (
owner_subject_id TEXT NOT NULL,
lesson_id TEXT NOT NULL,
reaction TEXT NOT NULL CHECK(reaction IN ('like','dislike')),
updated_at TEXT NOT NULL,
PRIMARY KEY(owner_subject_id,lesson_id))""",
"""CREATE TABLE IF NOT EXISTS coursera_lesson_issues (
issue_id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_subject_id TEXT NOT NULL,
lesson_id TEXT NOT NULL,
reason TEXT NOT NULL,
created_at TEXT NOT NULL)""",
]
def migrate(connection: sqlite3.Connection) -> None:
"""Install only the Coursera-owned business schema."""
for statement in _SCHEMA:
connection.execute(statement)
# Site 33 databases created before the account-control slice do not have
# the two notification channels. Add them idempotently without replacing
# the generated runtime database or changing historical rows.
columns = {
str(row[1])
for row in connection.execute("PRAGMA table_info(coursera_preferences)")
}
for column in ("product_updates", "course_updates"):
if column not in columns:
connection.execute(
f"ALTER TABLE coursera_preferences ADD COLUMN {column} INTEGER NOT NULL DEFAULT 0"
)
checkout.migrate(connection)
assignment_db.migrate(connection)
connection.execute(
"INSERT OR IGNORE INTO coursera_schema_migrations(migration_id,applied_at) VALUES (?,?)",
("0001-learning-core", FROZEN_TIME),
)
def seed(connection: sqlite3.Connection) -> None:
"""Install deterministic public content and the two learner business states."""
connection.executemany(
"INSERT OR IGNORE INTO coursera_modules(module_id,position,title) VALUES (?,?,?)",
MODULES,
)
connection.executemany(
"INSERT OR IGNORE INTO coursera_lessons(lesson_id,module_id,position,title,body,preview) VALUES (?,?,?,?,?,?)",
LESSONS,
)
connection.executemany(
"UPDATE coursera_lessons SET preview=? WHERE lesson_id=?",
[(row[5], row[0]) for row in LESSONS],
)
connection.executemany(
"""INSERT OR IGNORE INTO coursera_quizzes(
quiz_id,module_id,title,question,choices_json,correct_answer,
feedback_correct,feedback_incorrect) VALUES (?,?,?,?,?,?,?,?)""",
[(*row[:4], json.dumps(row[4]), *row[5:]) for row in QUIZZES],
)
connection.executemany(
"""INSERT OR IGNORE INTO coursera_profiles(
subject_id,display_name,onboarding_complete,current_role,learning_goal,
created_at,updated_at) VALUES (?,?,?,?,?,?,?)""",
[
("learner-in-progress", "Progress Learner", 1, "Learner", "Finish Deep Learning", FROZEN_TIME, FROZEN_TIME),
("learner-empty", "Empty Learner", 0, "", "", FROZEN_TIME, FROZEN_TIME),
],
)
assignment_db.seed(connection)
connection.execute(
"""INSERT OR IGNORE INTO coursera_enrollments(
owner_subject_id,course_id,track,status,created_at,canceled_at)
VALUES (?,?,?,?,?,NULL)""",
("learner-in-progress", COURSE_ID, "audit", "active", FROZEN_TIME),
)
connection.executemany(
"""INSERT OR IGNORE INTO coursera_lesson_progress(
owner_subject_id,lesson_id,completed,updated_at) VALUES (?,?,1,?)""",
[
("learner-in-progress", "lesson-neural-intro", FROZEN_TIME),
("learner-in-progress", "lesson-forward-propagation", FROZEN_TIME),
],
)
connection.execute(
"""INSERT OR IGNORE INTO coursera_resume_state(owner_subject_id,lesson_id,updated_at)
VALUES (?,?,?)""",
("learner-in-progress", "lesson-optimization", FROZEN_TIME),
)
connection.execute(
"""INSERT OR IGNORE INTO coursera_bookmarks(owner_subject_id,lesson_id,created_at)
VALUES (?,?,?)""",
("learner-in-progress", "lesson-optimization", FROZEN_TIME),
)
connection.executemany(
"""INSERT OR IGNORE INTO coursera_preferences(
owner_subject_id,language,timezone,email_updates,updated_at)
VALUES (?,?,?,?,?)""",
[
("learner-in-progress", "English", "UTC", 0, FROZEN_TIME),
("learner-empty", "English", "UTC", 0, FROZEN_TIME),
],
)
class _ServiceRegistry:
def __init__(self) -> None:
self._lock = threading.Lock()
self._current: tuple[SiteBackend, LocalAuthStore] | None = None
def open(self) -> tuple[SiteBackend, LocalAuthStore]:
with self._lock:
if self._current is None:
backend, auth = open_site_services()
# Existing site-33 databases may already have recorded the stable
# runtime hook before the enrolled-course migration was added.
# Replaying this site-owned migration is intentionally idempotent.
with backend.lifecycle.connection(transaction=True) as opened:
migrate(opened)
assignment_db.migrate(opened)
assignment_db.seed(opened)
for account in SEED_ACCOUNTS:
auth.seed_account(**account)
self._current = (backend, auth)
return self._current
def close(self) -> None:
with self._lock:
self._current = None
_SERVICE_REGISTRY = _ServiceRegistry()
def services() -> tuple[SiteBackend, LocalAuthStore]:
"""Open the generated seam and idempotently bind synthetic seed accounts."""
return _SERVICE_REGISTRY.open()
def close_services() -> None:
_SERVICE_REGISTRY.close()
def create_profile(
connection: sqlite3.Connection, registration: dict[str, Any]
) -> str:
"""Bind a verified generated-auth account to one Coursera learner profile."""
subject_id = f"learner-{str(registration['account_id'])[-20:]}"
connection.execute(
"""INSERT INTO coursera_profiles(
subject_id,display_name,onboarding_complete,current_role,learning_goal,
created_at,updated_at) VALUES (?,?,0,'','',?,?)""",
(subject_id, registration["display_name"], FROZEN_TIME, FROZEN_TIME),
)
connection.execute(
"""INSERT INTO coursera_preferences(
owner_subject_id,language,timezone,email_updates,updated_at)
VALUES (?,'English','UTC',0,?)""",
(subject_id, FROZEN_TIME),
)
return subject_id
def update_profile(subject_id: str, *, current_role: str, learning_goal: str) -> None:
role = current_role.strip()
goal = learning_goal.strip()
if not role or not goal:
raise ValueError("role and learning goal are required")
with connection(transaction=True) as opened:
updated = opened.execute(
"""UPDATE coursera_profiles SET onboarding_complete=1,current_role=?,
learning_goal=?,updated_at=? WHERE subject_id=?""",
(role, goal, FROZEN_TIME, subject_id),
)
if updated.rowcount != 1:
raise LookupError("learner profile was not found")
def update_account_settings(
subject_id: str, *, display_name: str, timezone: str
) -> None:
"""Persist the source-visible account fields for one local learner."""
name = display_name.strip()
zone = timezone.strip()
if not name:
raise ValueError("display name is required")
if len(name) > 80:
raise ValueError("display name is too long")
if not zone:
raise ValueError("timezone is required")
with connection(transaction=True) as opened:
updated = opened.execute(
"""UPDATE coursera_profiles
SET display_name=?, updated_at=?
WHERE subject_id=?""",
(name, FROZEN_TIME, subject_id),
)
if updated.rowcount != 1:
raise LookupError("learner profile was not found")
preference = opened.execute(
"""UPDATE coursera_preferences
SET timezone=?, updated_at=?
WHERE owner_subject_id=?""",
(zone, FROZEN_TIME, subject_id),
)
if preference.rowcount != 1:
raise LookupError("learner preferences were not found")
def get_profile(subject_id: str) -> dict[str, Any]:
"""Return the owner-bound local learner profile."""
with connection() as opened:
row = opened.execute(
"""SELECT subject_id,display_name,onboarding_complete,current_role,
learning_goal,created_at,updated_at
FROM coursera_profiles WHERE subject_id=?""",
(subject_id,),
).fetchone()
if row is None:
raise LookupError("learner profile was not found")
return dict(row)
def _enrollment_dict(row: sqlite3.Row) -> dict[str, Any]:
return dict(row)
def enroll(subject_id: str, *, course_id: str, track: str) -> dict[str, Any]:
catalog_record = next(
(record for record in load_catalog_seed() if record["id"] == course_id),
None,
)
if catalog_record is None or catalog_record["type"] not in {"course", "specialization"}:
raise ValueError("course is unavailable")
if track == "paid":
raise ValueError("paid enrollment requires checkout")
if track not in {"free", "audit"}:
raise ValueError("choose a free or audit track")
with connection(transaction=True) as opened:
created = opened.execute(
"""INSERT INTO coursera_enrollments(
owner_subject_id,course_id,track,status,created_at,canceled_at)
VALUES (?,?,?,'active',?,NULL)
ON CONFLICT(owner_subject_id,course_id) DO UPDATE SET
track=CASE WHEN coursera_enrollments.status='canceled'
THEN excluded.track ELSE coursera_enrollments.track END,
status='active',
canceled_at=coursera_enrollments.canceled_at
RETURNING *""",
(subject_id, course_id, track, FROZEN_TIME),
).fetchone()
if created is None: # pragma: no cover - SQLite RETURNING invariant
raise RuntimeError("enrollment upsert returned no row")
return _enrollment_dict(created)
def list_enrollments(subject_id: str) -> list[dict[str, Any]]:
with connection() as opened:
return [
_enrollment_dict(row)
for row in opened.execute(
"""SELECT enrollment.*,
(SELECT orders.order_id FROM coursera_orders AS orders
WHERE orders.enrollment_id=enrollment.enrollment_id
AND orders.owner_subject_id=enrollment.owner_subject_id
ORDER BY CASE orders.status WHEN 'PAID' THEN 0 ELSE 1 END,
orders.rowid DESC LIMIT 1) AS order_id
FROM coursera_enrollments AS enrollment
WHERE enrollment.owner_subject_id=?
ORDER BY enrollment.enrollment_id DESC""",
(subject_id,),
)
]
def get_enrollment(subject_id: str, enrollment_id: int) -> dict[str, Any]:
"""Return one enrollment only when it belongs to the current learner."""
with connection() as opened:
row = opened.execute(
"""SELECT enrollment.*,
(SELECT orders.order_id FROM coursera_orders AS orders
WHERE orders.enrollment_id=enrollment.enrollment_id
AND orders.owner_subject_id=enrollment.owner_subject_id
ORDER BY orders.rowid DESC LIMIT 1) AS order_id
FROM coursera_enrollments AS enrollment
WHERE enrollment.owner_subject_id=? AND enrollment.enrollment_id=?""",
(subject_id, enrollment_id),
).fetchone()
if row is None:
raise LookupError("Enrollment not found")
return _enrollment_dict(row)
def _active_enrollment(
opened: sqlite3.Connection, subject_id: str
) -> sqlite3.Row | None:
return opened.execute(
"""SELECT * FROM coursera_enrollments
WHERE owner_subject_id=? AND course_id=? AND status='active'""",
(subject_id, COURSE_ID),
).fetchone()
def has_active_enrollment(subject_id: str) -> bool:
with connection() as opened:
return _active_enrollment(opened, subject_id) is not None
def _require_active_enrollment(
opened: sqlite3.Connection, subject_id: str
) -> None:
if _active_enrollment(opened, subject_id) is None:
raise LookupError("Active enrollment not found")
def cancel_enrollment(subject_id: str, enrollment_id: int) -> dict[str, Any]:
with connection(transaction=True) as opened:
row = opened.execute(
"""SELECT * FROM coursera_enrollments
WHERE enrollment_id=? AND owner_subject_id=?""",
(enrollment_id, subject_id),
).fetchone()
if row is None:
raise LookupError("Enrollment not found")
if row["track"] == "paid":
raise ValueError("cancel paid enrollment from its paid order detail")
if row["status"] == "active":
opened.execute(
"""UPDATE coursera_enrollments SET status='canceled',canceled_at=?
WHERE enrollment_id=? AND owner_subject_id=?""",
(FROZEN_TIME, enrollment_id, subject_id),
)
row = opened.execute(
"SELECT * FROM coursera_enrollments WHERE enrollment_id=?",
(enrollment_id,),
).fetchone()
return _enrollment_dict(row)
def course_outline() -> list[dict[str, Any]]:
with connection() as opened:
modules = []
for module in opened.execute(
"SELECT * FROM coursera_modules ORDER BY position"
):
lessons = [
dict(row)
for row in opened.execute(
"SELECT * FROM coursera_lessons WHERE module_id=? ORDER BY position",
(module["module_id"],),
)
]
quiz = opened.execute(
"SELECT * FROM coursera_quizzes WHERE module_id=?",
(module["module_id"],),
).fetchone()
modules.append({**dict(module), "lessons": lessons, "quiz": dict(quiz)})
return modules
def get_lesson(lesson_id: str) -> dict[str, Any]:
outline = course_outline()
ordered = [
(module, lesson)
for module in outline
for lesson in module["lessons"]
]
for index, (module, lesson) in enumerate(ordered):
if lesson["lesson_id"] == lesson_id:
return {
**lesson,
"preview": int(lesson_id in PUBLIC_PREVIEW_LESSON_IDS),
"module_position": module["position"],
"module_title": module["title"],
"previous_lesson_id": (
ordered[index - 1][1]["lesson_id"] if index > 0 else None
),
"next_lesson_id": (
ordered[index + 1][1]["lesson_id"]
if index + 1 < len(ordered)
else None
),
"quiz": module["quiz"],
"outline": outline,
}
raise LookupError("Lesson not found")
def set_bookmark(subject_id: str, lesson_id: str, *, bookmarked: bool) -> None:
get_lesson(lesson_id)
with connection(transaction=True) as opened:
_require_active_enrollment(opened, subject_id)
if bookmarked:
opened.execute(
"""INSERT OR IGNORE INTO coursera_bookmarks(
owner_subject_id,lesson_id,created_at) VALUES (?,?,?)""",
(subject_id, lesson_id, FROZEN_TIME),
)
else:
opened.execute(
"DELETE FROM coursera_bookmarks WHERE owner_subject_id=? AND lesson_id=?",
(subject_id, lesson_id),
)
def complete_lesson(subject_id: str, lesson_id: str) -> None:
get_lesson(lesson_id)
with connection(transaction=True) as opened:
_require_active_enrollment(opened, subject_id)
opened.execute(
"""INSERT INTO coursera_lesson_progress(
owner_subject_id,lesson_id,completed,updated_at) VALUES (?,?,1,?)
ON CONFLICT(owner_subject_id,lesson_id) DO NOTHING""",
(subject_id, lesson_id, FROZEN_TIME),
)
completed = {
str(row[0])
for row in opened.execute(
"""SELECT lesson_id FROM coursera_lesson_progress
WHERE owner_subject_id=? AND completed=1""",
(subject_id,),
)
}
resume = next(
(lesson[0] for lesson in LESSONS if lesson[0] not in completed),
LESSONS[-1][0],
)
opened.execute(
"""INSERT INTO coursera_resume_state(owner_subject_id,lesson_id,updated_at)
VALUES (?,?,?) ON CONFLICT(owner_subject_id) DO UPDATE SET
lesson_id=excluded.lesson_id,updated_at=excluded.updated_at""",
(subject_id, resume, FROZEN_TIME),
)
def submit_quiz(subject_id: str, quiz_id: str, answer: str) -> dict[str, Any]:
selected = answer.strip()
with connection(transaction=True) as opened:
_require_active_enrollment(opened, subject_id)
quiz = opened.execute(
"SELECT * FROM coursera_quizzes WHERE quiz_id=?", (quiz_id,)
).fetchone()
if quiz is None:
raise LookupError("Quiz not found")
choices = json.loads(str(quiz["choices_json"]))
if selected not in choices:
raise ValueError("choose one available answer")
score = 100 if selected == quiz["correct_answer"] else 0
feedback = (
quiz["feedback_correct"] if score == 100 else quiz["feedback_incorrect"]
)
cursor = opened.execute(
"""INSERT INTO coursera_quiz_attempts(
owner_subject_id,quiz_id,answer,score,feedback,created_at)
VALUES (?,?,?,?,?,?)""",
(subject_id, quiz_id, selected, score, feedback, FROZEN_TIME),
)
return {
"attempt_id": cursor.lastrowid,
"quiz_id": quiz_id,
"score": score,
"feedback": str(feedback),
}
def get_quiz_attempt(subject_id: str, attempt_id: int) -> dict[str, Any]:
with connection() as opened:
row = opened.execute(
"""SELECT * FROM coursera_quiz_attempts
WHERE attempt_id=? AND owner_subject_id=?""",
(attempt_id, subject_id),
).fetchone()
if row is None:
raise LookupError("Quiz attempt not found")
return dict(row)
def learning_state(subject_id: str) -> dict[str, Any]:
with connection() as opened:
active_enrollment = _active_enrollment(opened, subject_id) is not None
completed = [
row[0]
for row in opened.execute(
"""SELECT lesson_id FROM coursera_lesson_progress
WHERE owner_subject_id=? AND completed=1 ORDER BY lesson_id""",
(subject_id,),
)
]
bookmarks = [
row[0]
for row in opened.execute(
"""SELECT lesson_id FROM coursera_bookmarks
WHERE owner_subject_id=? ORDER BY lesson_id""",
(subject_id,),
)
]
resume = opened.execute(
"SELECT lesson_id FROM coursera_resume_state WHERE owner_subject_id=?",
(subject_id,),
).fetchone()
passed_quizzes = opened.execute(
"""SELECT COUNT(DISTINCT quiz_id) FROM coursera_quiz_attempts
WHERE owner_subject_id=? AND score=100""",
(subject_id,),
).fetchone()[0]
return {
"completed_lessons": completed,
"bookmarks": bookmarks,
"resume_lesson_id": str(resume[0]) if resume else "lesson-neural-intro",
"certificate_available": active_enrollment and len(completed) == len(LESSONS) and passed_quizzes == len(QUIZZES),
}
def upsert_review(subject_id: str, *, rating: int, review_text: str) -> None:
text = review_text.strip()
if rating not in {1, 2, 3, 4, 5} or not text:
raise ValueError("rating from 1 to 5 and review text are required")
with connection(transaction=True) as opened:
_require_active_enrollment(opened, subject_id)
opened.execute(
"""INSERT INTO coursera_reviews(
owner_subject_id,course_id,rating,review_text,updated_at)
VALUES (?,?,?,?,?) ON CONFLICT(owner_subject_id,course_id) DO UPDATE SET
rating=excluded.rating,review_text=excluded.review_text,
updated_at=excluded.updated_at""",
(subject_id, COURSE_ID, rating, text, FROZEN_TIME),
)
def get_review(subject_id: str, course_id: str) -> dict[str, Any] | None:
with connection() as opened:
row = opened.execute(
"""SELECT rating,review_text,updated_at FROM coursera_reviews
WHERE owner_subject_id=? AND course_id=?""",
(subject_id, course_id),
).fetchone()
return dict(row) if row is not None else None
def review_count(subject_id: str) -> int:
with connection() as opened:
return int(
opened.execute(
"SELECT COUNT(*) FROM coursera_reviews WHERE owner_subject_id=?",
(subject_id,),
).fetchone()[0]
)
def update_preferences(
subject_id: str, *, language: str, timezone: str, email_updates: bool
) -> None:
selected_language = language.strip()
selected_timezone = timezone.strip()
if not selected_language or not selected_timezone:
raise ValueError("language and timezone are required")
with connection(transaction=True) as opened:
opened.execute(
"""INSERT INTO coursera_preferences(
owner_subject_id,language,timezone,email_updates,updated_at)
VALUES (?,?,?,?,?) ON CONFLICT(owner_subject_id) DO UPDATE SET
language=excluded.language,timezone=excluded.timezone,
email_updates=excluded.email_updates,updated_at=excluded.updated_at""",
(subject_id, selected_language, selected_timezone, int(email_updates), FROZEN_TIME),
)
def update_update_preferences(
subject_id: str, *, product_updates: bool, course_updates: bool
) -> None:
"""Persist Updates subscriptions without exposing an external mail effect."""
with connection(transaction=True) as opened:
updated = opened.execute(
"""UPDATE coursera_preferences
SET product_updates=?, course_updates=?, updated_at=?
WHERE owner_subject_id=?""",
(int(product_updates), int(course_updates), FROZEN_TIME, subject_id),
)
if updated.rowcount != 1:
raise LookupError("learner preferences were not found")
def get_preferences(subject_id: str) -> dict[str, Any]:
with connection() as opened:
row = opened.execute(
"""SELECT language,timezone,email_updates FROM coursera_preferences
WHERE owner_subject_id=?""",
(subject_id,),
).fetchone()
if row is None:
raise LookupError("Preferences not found")
return {
"language": str(row["language"]),
"timezone": str(row["timezone"]),
"email_updates": bool(row["email_updates"]),
}
def get_update_preferences(subject_id: str) -> dict[str, bool]:
with connection() as opened:
row = opened.execute(
"""SELECT product_updates,course_updates FROM coursera_preferences
WHERE owner_subject_id=?""",
(subject_id,),
).fetchone()
if row is None:
raise LookupError("Preferences not found")
return {
"product_updates": bool(row["product_updates"]),
"course_updates": bool(row["course_updates"]),
}
def save_help_feedback(subject_id: str, *, helpful: bool) -> None:
with connection(transaction=True) as opened:
opened.execute(
"""INSERT INTO coursera_help_feedback(owner_subject_id,helpful,updated_at)
VALUES (?,?,?) ON CONFLICT(owner_subject_id) DO UPDATE SET
helpful=excluded.helpful,updated_at=excluded.updated_at""",
(subject_id, int(helpful), FROZEN_TIME),
)
def get_help_feedback(subject_id: str) -> bool | None:
with connection() as opened:
row = opened.execute(
"SELECT helpful FROM coursera_help_feedback WHERE owner_subject_id=?",
(subject_id,),
).fetchone()
return None if row is None else bool(row["helpful"])
def set_weekly_target(subject_id: str, minutes: int) -> None:
if minutes < 15 or minutes > 1200:
raise ValueError("weekly target must be between 15 and 1200 minutes")
with connection(transaction=True) as opened:
_require_active_enrollment(opened, subject_id)
opened.execute(
"""INSERT INTO coursera_weekly_targets(owner_subject_id,minutes,updated_at)
VALUES (?,?,?) ON CONFLICT(owner_subject_id) DO UPDATE SET
minutes=excluded.minutes,updated_at=excluded.updated_at""",
(subject_id, minutes, FROZEN_TIME),
)
def get_weekly_target(subject_id: str) -> int | None:
with connection() as opened:
row = opened.execute(
"SELECT minutes FROM coursera_weekly_targets WHERE owner_subject_id=?",
(subject_id,),
).fetchone()
return None if row is None else int(row["minutes"])
def set_lesson_reaction(
subject_id: str, lesson_id: str, reaction: str | None
) -> None:
lesson = lesson_id.strip()
if not lesson:
raise ValueError("lesson is required")
if reaction not in {None, "like", "dislike"}:
raise ValueError("reaction must be like or dislike")
with connection(transaction=True) as opened:
_require_active_enrollment(opened, subject_id)
if reaction is None:
opened.execute(
"DELETE FROM coursera_lesson_reactions WHERE owner_subject_id=? AND lesson_id=?",
(subject_id, lesson),
)
else:
opened.execute(
"""INSERT INTO coursera_lesson_reactions(
owner_subject_id,lesson_id,reaction,updated_at)
VALUES (?,?,?,?) ON CONFLICT(owner_subject_id,lesson_id) DO UPDATE SET
reaction=excluded.reaction,updated_at=excluded.updated_at""",
(subject_id, lesson, reaction, FROZEN_TIME),
)
def get_lesson_reaction(subject_id: str, lesson_id: str) -> str | None:
with connection() as opened:
row = opened.execute(
"""SELECT reaction FROM coursera_lesson_reactions
WHERE owner_subject_id=? AND lesson_id=?""",
(subject_id, lesson_id),
).fetchone()
return None if row is None else str(row["reaction"])
def report_lesson_issue(subject_id: str, lesson_id: str, reason: str) -> int:
lesson = lesson_id.strip()
detail = reason.strip()
if not lesson or not detail:
raise ValueError("lesson and issue reason are required")
if len(detail) > 500:
raise ValueError("issue reason is too long")
with connection(transaction=True) as opened:
_require_active_enrollment(opened, subject_id)
cursor = opened.execute(
"""INSERT INTO coursera_lesson_issues(
owner_subject_id,lesson_id,reason,created_at)
VALUES (?,?,?,?)""",
(subject_id, lesson, detail, FROZEN_TIME),
)
return int(cursor.lastrowid)
def latest_lesson_issue(subject_id: str, lesson_id: str) -> dict[str, Any] | None:
with connection() as opened:
row = opened.execute(
"""SELECT issue_id,reason,created_at FROM coursera_lesson_issues
WHERE owner_subject_id=? AND lesson_id=? ORDER BY issue_id DESC LIMIT 1""",
(subject_id, lesson_id),
).fetchone()
return None if row is None else dict(row)
_MUTABLE_TABLES = (
"coursera_assignment_results",
"coursera_assignment_drafts",
"coursera_assignment_attempts",
"coursera_course_notes",
"coursera_enrolled_course_state",
"coursera_quiz_attempts",
"coursera_reviews",
"coursera_bookmarks",
"coursera_lesson_progress",
"coursera_resume_state",
"coursera_enrollments",
"coursera_preferences",
"coursera_help_feedback",
"coursera_weekly_targets",
"coursera_lesson_reactions",
"coursera_lesson_issues",
"coursera_profiles",
"coursera_quizzes",
"coursera_lessons",
"coursera_modules",
)
def reset() -> None:
"""Atomically restore auth and Coursera business state to canonical seeds."""
backend, auth = services()
def site_reset(opened: sqlite3.Connection) -> None:
checkout.reset(opened)
for table in _MUTABLE_TABLES:
opened.execute(f"DELETE FROM {table}")
opened.execute(
"DELETE FROM sqlite_sequence WHERE name IN (?,?,?)",
(
"coursera_enrollments",
"coursera_quiz_attempts",
"coursera_course_notes",
),
)
backend.lifecycle.reset_embedded(opened, confirm_site_id=SITE_ID)
seed(opened)
auth.reset_site_state(site_reset=site_reset, seed_accounts=SEED_ACCOUNTS)
close_services()
def state_snapshot() -> dict[str, Any]:
"""Return deterministic, non-secret auth and business reset semantics."""
queries = {
"modules": "SELECT * FROM coursera_modules ORDER BY module_id",
"lessons": "SELECT * FROM coursera_lessons ORDER BY lesson_id",
"quizzes": "SELECT * FROM coursera_quizzes ORDER BY quiz_id",
"profiles": "SELECT display_name,subject_id,onboarding_complete,current_role,learning_goal,created_at,updated_at FROM coursera_profiles ORDER BY subject_id",
"enrollments": "SELECT * FROM coursera_enrollments ORDER BY enrollment_id",
"progress": "SELECT * FROM coursera_lesson_progress ORDER BY owner_subject_id,lesson_id",
"bookmarks": "SELECT * FROM coursera_bookmarks ORDER BY owner_subject_id,lesson_id",
"resume": "SELECT * FROM coursera_resume_state ORDER BY owner_subject_id",
"attempts": "SELECT * FROM coursera_quiz_attempts ORDER BY attempt_id",
"reviews": "SELECT * FROM coursera_reviews ORDER BY owner_subject_id,course_id",
"preferences": "SELECT * FROM coursera_preferences ORDER BY owner_subject_id",
"help_feedback": "SELECT * FROM coursera_help_feedback ORDER BY owner_subject_id",
"weekly_targets": "SELECT * FROM coursera_weekly_targets ORDER BY owner_subject_id",
"lesson_reactions": "SELECT * FROM coursera_lesson_reactions ORDER BY owner_subject_id,lesson_id",
"lesson_issues": "SELECT * FROM coursera_lesson_issues ORDER BY issue_id",
"enrolled_course_state": "SELECT * FROM coursera_enrolled_course_state ORDER BY owner_subject_id,course_id",
"course_notes": "SELECT * FROM coursera_course_notes ORDER BY note_id",
"assignment_attempts": "SELECT * FROM coursera_assignment_attempts ORDER BY owner_subject_id,attempt_number",
"assignment_drafts": "SELECT * FROM coursera_assignment_drafts ORDER BY owner_subject_id,attempt_id",
"assignment_results": "SELECT * FROM coursera_assignment_results ORDER BY owner_subject_id,attempt_id",
}
queries.update(checkout.snapshot_queries())
with connection() as opened:
snapshot: dict[str, Any] = {
name: [tuple(row) for row in opened.execute(query)]
for name, query in queries.items()
}
session_counts = opened.execute(
"""SELECT
SUM(CASE WHEN revoked_at IS NULL AND account_id IS NULL THEN 1 ELSE 0 END),
SUM(CASE WHEN revoked_at IS NULL AND account_id IS NOT NULL THEN 1 ELSE 0 END),
SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END)
FROM local_auth_sessions"""
).fetchone()
registration_counts = opened.execute(
"""SELECT
SUM(CASE WHEN verified_at IS NULL THEN 1 ELSE 0 END),
SUM(CASE WHEN verified_at IS NOT NULL THEN 1 ELSE 0 END)
FROM local_auth_registration_flows"""
).fetchone()
recovery_counts = opened.execute(
"""SELECT
SUM(CASE WHEN verified_at IS NULL THEN 1 ELSE 0 END),
SUM(CASE WHEN verified_at IS NOT NULL THEN 1 ELSE 0 END)
FROM local_auth_password_reset_flows"""
).fetchone()
snapshot["auth"] = {
"accounts": [
tuple(row)
for row in opened.execute(
"""SELECT subject_id,email_normalized,display_name,email_verified
FROM local_auth_accounts ORDER BY subject_id"""
)
],
"sessions": {
"anonymous": int(session_counts[0] or 0),
"authenticated": int(session_counts[1] or 0),
"revoked": int(session_counts[2] or 0),
},
"registration_challenges": {
"active": int(registration_counts[0] or 0),
"verified": int(registration_counts[1] or 0),
},
"recovery_challenges": {
"active": int(recovery_counts[0] or 0),
"verified": int(recovery_counts[1] or 0),
},
"outbox": [
tuple(row)
for row in opened.execute(
"""SELECT purpose,template,status,COUNT(*)
FROM local_auth_mail_outbox
GROUP BY purpose,template,status
ORDER BY purpose,template,status"""
)
],
"rate_limits": [
tuple(row)
for row in opened.execute(
"""SELECT purpose,scope_type,COUNT(*)
FROM local_auth_mail_rate_limits
GROUP BY purpose,scope_type
ORDER BY purpose,scope_type"""
)
],
}
return snapshot
@contextmanager
def connection(*, transaction: bool = False) -> Iterator[sqlite3.Connection]:
backend, _auth = services()
with backend.lifecycle.connection(transaction=transaction) as opened:
yield opened
|