Platform blueprint

A language testing platform, built for the classroom.

A requirements and architecture reference for an offline-capable language test app, with live classroom monitoring, teacher-reviewed AI scoring, and role-aware analytics.

Runtime SvelteKit · Cloudflare WorkersTarget Workers Free planCharts Layer ChartFuture REST routes · mobile app
Document status: requirements only — no application code has been built. Capacity figures and platform limits below are stated as verified in the source document dated 15 Nov 2026.
01 · Product scope

What the platform does

Students complete assigned tests; teachers and administrators review results, written responses, and learning patterns.

Test-taking

Multiple choice, fill-in-the-blank, and written exercises. Students can move between questions and revise answers before final submission.

Human-verified scoring

Objective questions are evaluated immediately on submission. Written responses can be AI-scored in batches, then verified or adjusted by a teacher.

Teaching analytics

Separate views support teacher evaluation, monitoring the current student roster, and administrator-wide comparisons.

Product direction: PWA with offline capability; REST routes and the same hibernating-WebSocket approach are intended to support a future mobile app.
02 · Access model

Three roles, clearly separated

Permissions follow responsibility: platform-wide oversight for admins, assigned-class management for teachers, and personal testing/results for pupils.

AD

Admin

  • Create admins, teachers, and pupils.
  • Assign or reassign pupils to teachers.
  • See all teachers, students, and tests.
  • Evaluate teachers using only tests for which they were responsible.
  • Approve deletion of a pupil who has logged in.
  • Reset any user's password; disable or enable any user.
TE

Teacher

  • Create pupils for themselves; each receives a unique temporary password.
  • Reset or disable their pupils; delete never-logged-in pupils after email confirmation.
  • Request admin approval to delete a pupil who has logged in.
  • View My Teaching and My Students separately.
  • Review and adjust AI scores; see each current pupil’s complete result history.
PU

Pupil

  • Take assigned tests.
  • View their own results.
First-login rule: every user must change their temporary password on first login; users can change their password at any time.
03 · Authentication

Authenticate once, authorize every action

HTTP/API requests use JWT validation. WebSockets authenticate on the first message, then retain the verified identity across Durable Object hibernation.

WebSocket connection lifecycle

1 · Browser

JWT held in JS memory; reconnect resends it.

→

2 · First WS message

{type:'auth', token}

→

3 · Teacher DO

Validates JWT; stores identity with ws.serializeAttachment().

→

4 · Later messages

DO wakes, reads identity from attachment; no repeat JWT validation needed.

Login sequence

  1. Client sends email and password to /api/auth/login.
  2. Server looks up the user in D1 and compares the supplied password with the stored bcrypt hash.
  3. On success, issue HS256 JWT using JWT_SECRET from Workers Secrets.
  4. JWT payload: sub, role, email, optional teacher_id, must_change_password, and exp.
  5. Set an httpOnly cookie and return the token in the response body for WebSocket use.
  6. If password change is required, route to the change-password page.

Token and password policy

  • Password hash: bcrypt, cost factor 10, stored in users.password_hash.
  • must_change_password marks temporary credentials; record password_changed_at.
  • JWT expires after 7 days; refresh by logging in again.
  • Hooks validate JWT from cookie/header on each API request; route handlers enforce role and user authorization.
  • No session table is needed: JWT is self-contained.

Temporary password reset

Teacher / Admin

Generate random temporary password.

→

D1

Hash and store; set must_change_password=true.

→

Student

Credential is communicated in person/by phone; sign in and change it.

WebSocket binding: the DO verifies the JWT, then checks that JWT.sub matches the userId in the start message. Mismatch or invalid/expired JWT closes the connection.
04 · History and responsibility

Keep today’s assignment separate from test-time ownership

A pupil may change teachers. The current roster changes, but historical test responsibility does not.

IMMUTABLE

Test session receipt

At test completion, store the responsible teacher_id as it was at that time. Never rewrite it after a reassignment.

MUTABLE

Current assignment

One current teacher per pupil, course, and test type. Update this row when the pupil moves.

APPEND-ONLY

Assignment history

Record assignment and unassignment timestamps and reason, preserving the full teaching history.

ViewFilter / sourceWhat it includesPurpose
My Teachingtest_sessions.teacher_id = me
R2 weekly JSON (perTeacherSubject)
Only tests for which this teacher was responsible, including tests that remain in their history after a pupil moves away.Admin evaluation of a teacher’s effectiveness.
My StudentsCurrent assignments joined to test sessions in D1Every result belonging to pupils currently assigned to this teacher, including results earned under previous teachers. Show the historical teacher_id.Monitor current pupils and their complete history.
Pupil moves from Teacher A to Teacher B
Weeks 1–4 · Teacher A

Current assignment: X → A
Tests 1–2 record teacher_id=A.

→
Weeks 5–8 · Teacher B

Current assignment: X → B; history closes A assignment. Tests 3–4 record teacher_id=B.

Teacher A

My Teaching: tests 1–2 remain.
My Students: X no longer appears.

Teacher B

My Teaching: tests 3–4.
My Students: tests 1–4; prior teachers are identified.

Admin evaluating A

Only tests 1–2 are attributed to A.

05 · Testing and grading

Three question types, two scoring paths

Multiple choice

  • One selected option.
  • Score: 0 or 100, immediately evaluated.
  • Choice distribution analytics.
  • Time tracked per question.

Fill in the blank

  • One or more blanks; each may have choices.
  • Score: percentage of blanks correct.
  • Choice distribution per blank.
  • Time tracked per question.

Example: “The ___ cat sat on the ___ mat.”

Written exercise

  • Free-text response; not scored instantly.
  • Rubric criteria such as grammar, vocabulary, and coherence.
  • AI evaluates; a teacher verifies or adjusts.
  • Analytics summarize criteria scores.
Written-response scoring · hourly batch AI, manual grading available anytime

Final test submit

Written answer is queued only now.

→

D1 · pending_ai

Answer and session are persisted.

→

Hourly cron

Batch up to 5 answers per AI call; process pending backlog.

→

pending_review

Teacher reviews or adjusts per-criteria scores.

→

final

Recalculate session score.

Manual path · anytime

Teacher enters per-criteria scores → status becomes final. AI batch skips manually finalized answers.

Quota handling

If a 429 / neuron limit occurs, stop gracefully. Remaining answers stay pending_ai and are picked up on a later hourly run (after daily reset if needed).

Batch economics in the brief

  • Single call: about 9.2 neurons per answer (~500 input + ~150 output tokens).
  • Batching 5 answers: about 40 neurons per batch, approximately 8 neurons per answer.
  • Free-tier daily budget: 10,000 neurons; approximately 1,250 batched answers or 250 tests/day at 5 written exercises per test.
  • Realistic school estimate: 29 tests/day, 145 written answers, ~1,160 neurons (~12% of daily limit).

Model choice noted in source

@cf/meta/llama-3.1-8b-instruct-awq is the recommended model in the requirements; teacher verification remains authoritative. The source warns against models it says were planned for deprecation on 20 Nov 2026.

The source also lists a later 70B upgrade as a possible option, with roughly 2× cost.

Result visibility: during a test, students may navigate freely and change answers. Correctness is not revealed while answering. MC/fill-blank evaluation may feed the teacher’s live board; final results appear only after submit and teacher review. Written answers enter the AI queue only on full submission.
06 · Runtime architecture

One Worker, stateful classroom sessions, durable records

SvelteKit serves pages and APIs. Teacher-scoped Durable Objects manage live WebSocket activity; D1 is the operational record, while scheduled aggregation writes weekly analytics to R2.

Cloudflare Workers environment

SvelteKit app · Worker

  • SSR: login, test, dashboard, admin
  • API: auth, analysis, review, etc.
  • JWT auth hook
  • Static assets via Workers Assets

Teacher Durable Object

  • One per teacher; student + teacher WebSockets
  • Hibernating WebSockets (20:1 ratio in source)
  • SQLite: session state, cached questions, live sessions
  • 16-hour live-session retention
  • Evaluates MC/fill-blank; queues written work

D1 database

  • Users and questions
  • Test sessions and written scores
  • Current assignments and history
  • Deletion requests

Workers Secrets

  • JWT_SECRET
  • HMAC key for signing JWTs
WebSocket upgrade ↙   ·   HTTP/REST ↘   ·   DO writes at test submit

Hourly cron Worker

Reads new sessions, aggregates weekly stats, writes R2, updates KV sync timestamp.

R2 · weekly JSON

Objects such as stats/2026-W46 and stats/2026-W47.

KV · sync state

Stores last_aggregated_at for incremental aggregation.

Workers AI

Batch scoring of written exercises, initiated by hourly cron.

DO SQLite

Transient session state, cached questions, and live classroom board; purge entries older than 16 hours.

Durable Object responsibilities

  • Use a Teacher DO per teacher; students for that teacher connect over WebSocket.
  • Teacher connects to the live board.
  • Store session state, cached questions, and live sessions in DO SQLite.
  • Write to D1 at test submission; the source estimates one test write plus one per written question.
  • Purge entries older than 16 hours.

Analytics storage boundary

  • Operational individual records stay in D1.
  • Weekly aggregates are written to R2.
  • KV stores aggregation sync state.
  • Live board reads its snapshot from the Teacher DO, without D1 or R2 reads.
07 · Live test protocol

Question navigation stays flexible; grading waits for submit

Student test-taking flow

1 · GET /test/A1

Worker validates JWT and serves SSR page.

→

2 · WebSocket connect

Worker upgrades and routes to Teacher DO.

→

3 · Authenticate

Send JWT; DO verifies and stores identity.

→

4 · Start

Check JWT subject; load/cache questions from D1.

→

5 · Navigate / save

Prev, next, jump; saved answers remain editable.

→

6 · Submit

Evaluate objective answers; queue written answers; write D1 session and scores.

After submission: return results, score, and per-question correctness; update the live board and mark the live session completed.
08 · Analytics and live monitoring

Separate the historical dashboard from the live board

HISTORICAL

Analyze dashboard

Hourly aggregation reads new completed sessions from D1, aggregates in Worker memory, merges the weekly JSON in R2, and advances the KV timestamp.

  • My Teaching: read weekly R2 JSON and filter by teacher.
  • My Students: query current assignments and their students’ test sessions from D1; aggregate in Worker memory.
  • Pending reviews: D1 written scores filtered to pending_review and current teacher.
LIVE · LAST 16 HOURS

Teacher board

Read entirely from the Teacher DO’s live_sessions table; no D1 or R2 read is required for the live view.

  • Shows running and recently completed tests.
  • Per-student answer updates are pushed to teacher WebSocket.
  • Completed tests stay visible for 16 hours.
  • On board request, purge expired rows; optional hourly DO alarm is noted.
Aggregation path

Cron / Analyze

Hourly schedule or teacher/admin request.

→

KV checkpoint

Read last_aggregated_at.

→

D1 sessions

Read newer completed sessions (source query uses LIMIT 1000).

→

Worker aggregation

Per-question, per-teacher/subject, question-type/subject; merge weekly data.

→

R2 + KV

Write weekly stats and update sync timestamp.

VisualizationData sourceAudience / view
Tests over time · lineR2 weekly JSONTeaching / Students
Time per question · box plotR2 or D1Teaching / Students
Choice distribution · bar per questionR2 or D1Teaching / Students
Fill-blank choice distribution · grouped bar per blankR2 or D1Teaching / Students
Written criteria scores · radar/barD1 written_scoresTeaching
Teacher comparison by subject type · grouped barR2 weekly JSONAdmin
Correct % by question type × subject · heatmapR2 weekly JSONAdmin
Student lookup · table + answer detailD1 test_sessionsTeaching / Admin

Admin heatmap example from the requirements

Question typePast / presentFuture tenseAdjectivesArticles
Multiple choice85%72%90%68%
Fill in the blank78%65%82%70%
Written exercise70%58%75%55%

Illustrative values copied from the requirements, not live application data. The source describes ≥80%, 60–79%, 40–59%, and <40% bands. Suggested drill-down: find which teachers contribute to weak areas via perTeacherSubject.

Live board row semantics
StudentStartedDurationQuestion states (example)Session
Alice14:0212:34Correct Wrong Correct AwaitingRunning
Bob14:0508:12Correct Correct AwaitingRunning
Carol13:5521:07Correct Wrong CorrectCompleted

Written exercises use a pending-review state. Completed or abandoned sessions are marked with timestamps; stale running sessions are purged after 16 hours of inactivity.

09 · Persistence

D1 schema at a glance

The source defines seven tables covering identity, assessment, scoring, assignments, and approval workflow.

users

Students, teachers, admins

id PK, email unique, password_hash, role, teacher_id, must_change_password, password_changed_at, disabled, created_at, created_by.

questions

Question bank

id PK, test_type, language, level, question_type, subject_type, prompt, choices/correct answer fields, blank definitions, criteria, position.

test_sessions

Immutable test receipt; teacher frozen at test time

id PK, user_id, teacher_id, test_type, language, level, score, question count, status, start/completion timestamps, duration, answers_json.

written_scores

Async written scoring

Composite PK: (session_id, question_id). Includes user/teacher IDs, response text, per-criteria AI/final score and feedback JSON, overall AI/final scores, status, AI evaluation and human verification timestamps, verifier.

student_teacher_assignments

Current roster; mutable

PK: (student_id, course, test_type). Stores current teacher_id and assigned_at.

assignment_history

Append-only audit trail

id PK, student/teacher IDs, course, test type, assigned/unassigned times, reason.

deletion_requests

Admin approval for pupil deletion

id PK, student ID, requester, request time, pending/approved/rejected status, approver, approval time.

10 · Free-plan sizing

AI is the first expected bottleneck

The source models a 30-question test with 20 multiple-choice, 5 fill-blank (3 blanks each), and 5 written exercises. Figures below reflect that model and the source’s Nov 2026 limits.

~217
tests/day from AI neurons at ~46 neurons per test
~16.7k
tests/day from D1 writes at 6 writes per test
~29
tests/day in the realistic 200-student school scenario

Approximate daily test capacity by resource

Workers AI neurons
~217 tests
DO SQLite writes
~12,500 tests
D1 writes
~16,666 tests
Worker requests
~33,333 tests
DO requests
~39,215 tests
Other listed limits
>100k tests

Bar lengths are normalized for visual ranking, not a linear common-capacity scale. Per-test capacity values are shown exactly as provided in the source model.

ResourceFree limit stated in sourceReset / scope
Worker requests100,000 / dayMidnight UTC
Durable Object requests100,000 / dayMidnight UTC
DO duration13,000 GB-s / dayMidnight UTC
DO SQLite rows read / written5,000,000 read / 100,000 written per dayMidnight UTC
DO SQLite storage5 GBTotal
D1 rows read / written5,000,000 read / 100,000 written per dayMidnight UTC
D1 storage5 GBTotal
R2 Class A / B1,000,000 writes / 10,000,000 readsMonthly
R2 storage10 GBTotal
KV reads / writes100,000 reads / 1,000 writes per dayMidnight UTC
Workers AI neurons10,000 / dayMidnight UTC
Queues operations10,000 / dayMidnight UTC

Per-test model

  • Worker requests: 3 (login, page load, WebSocket).
  • DO requests: 2.55; duration: about 0.04 GB-s.
  • D1: 6 writes; 31 reads.
  • DO SQLite: 8 writes and 32 reads in the per-test table; another realistic-scenario table in the source lists 32 writes—reconcile before implementation.
  • Workers AI: ~46 neurons, using five individual calls in the per-test estimate.

Realistic school model

200 students, 10 teachers, 3 admins; each student takes one test per week: about 29 tests/day.

The source concludes the scenario fits the free tier; Workers AI is the highest listed use at 13.3%, while KV writes are listed at 2.4% and cron D1 reads at 8.9%.

The source separately describes a batched-AI strategy of ~8 neurons per answer, or ~250 tests/day with 5 written answers per test. Keep these estimates distinct: the capacity table’s ~217/day uses ~46 neurons/test.

Optimization directions in the source

  • Use the recommended smaller model for short rubric scoring.
  • Batch written answers: source estimates ~20 neurons/test and capacity near 500 tests/day under one optimization scenario; reconcile against the later 5-answer batch estimate (~8 neurons/answer) before sizing.
  • Save DO SQLite state every five answers rather than each answer; source estimates 6 writes/test.
  • Consider skipping AI on responses under 20 characters and scoring them zero (a proposed optimization, not a validated policy).
  • Above batched AI capacity, manually grade overflow or increase capacity.
11 · Account lifecycle

Creation, disablement, deletion, reassignment

Create accounts

Admin creates teacher

Admin dashboard → POST /api/admin/users with email and role → SvelteKit writes to D1 → temporary password returned and communicated verbally.

Teacher creates pupil

Teacher dashboard → POST /api/teacher/pupils with email → D1 user + assignment rows → temporary password returned and communicated; pupil is assigned to creator.

Disable vs. delete

Disable

Set users.disabled=1; login is blocked by auth hook. Data is retained; user can be re-enabled.

Never logged in

Teacher requests deletion and types the pupil’s email to confirm. Delete user and related assignment/test/score data; no admin approval needed.

Has logged in

Create pending deletion request. Admin approves to delete related data or rejects to retain pupil. Teacher cannot unilaterally delete a pupil with history.

Reassignment sequence

Admin request

POST /api/assignments with student, new teacher, course, test type.

→

Close old history row

Set unassigned_at to now for current assignment.

→

Replace current row

Delete old assignment; insert new current assignment.

→

Append history

Insert new teacher with assigned_at=now.

After reassignment: old teacher’s My Students no longer includes the pupil; new teacher’s view includes all their tests; historical test_sessions.teacher_id is unchanged; admin can inspect full assignment history.
12 · Security controls

Threats and specified mitigations

ThreatMitigation in requirements
Student takes a test as another studentTeacher DO requires JWT sub to match start.userId.
Teacher sees another teacher’s studentsCheck JWT role and teacher_id in every API route.
Student accesses admin dashboardRole check in auth hook; admin routes reject non-admin JWTs.
Teacher deletes a pupil with history without approvalRequire admin approval if the pupil has logged in.
Password exposureBcrypt hash (cost 10); keep JWT_SECRET in Workers Secrets.
WebSocket hijackJWT is the first WebSocket message; DO validates before accepting other messages.
Disabled user signs inAuth hook checks users.disabled=0.
JWT replay after disable7-day JWT expiry plus a disabled-flag check before starting a test or opening a new WebSocket connection (one D1 read).
Authorization invariants: students cannot impersonate another test-taker; teachers cannot observe another teacher’s class; admins may observe any class. Subsequent WebSocket messages use the verified identity stored in the connection attachment.