How Exam Attempts Are Tracked and Validated in freeCodeCamp’s Exam Environment
Exam attempts in freeCodeCamp are tracked through a multi-stage process that generates unique exam instances, validates submissions against generated question sets, and applies moderation checks to ensure integrity before final scoring.
The freeCodeCamp Exam Environment is a self-contained service that manages the entire lifecycle of a certification exam attempt. From the moment a user clicks "Start Exam" to the final score calculation, the system records every interaction, validates data integrity against tampering, and determines whether the attempt requires human review. This article breaks down the exact mechanisms used to track and validate exam attempts based on the source code in the freeCodeCamp/freeCodeCamp repository.
The Five Stages of Exam Attempt Tracking
The exam attempt flow splits into five distinct stages, each handled by specific functions in api/src/exam-environment/utils/exam-environment.ts and api/src/exam-environment/routes/exam-environment.ts.
Stage 1: Generating the Exam Instance
When a user starts an exam, the server creates or retrieves an ExamEnvironmentGeneratedExam record. This entity contains the exact subset of question IDs and answer IDs that the user is authorized to see, effectively freezing the exam content for that specific attempt.
The generateExam function handles this logic, storing the generated exam in the examEnvironmentGeneratedExam table and linking it to the user’s ExamEnvironmentExamAttempt record.
Stage 2: Recording the Attempt
The postExamAttemptHandler function in api/src/exam-environment/routes/exam-environment.ts handles POST requests to /exam-environment/exam/attempt. It inserts a new row into ExamEnvironmentExamAttempt containing:
- questionSets: An array of question IDs, chosen answer IDs, and per-question
submissionTimetimestamps - generatedExamId: A foreign key linking to the generated exam instance
- userId: The authenticated user’s identifier
Stage 3: Validating the Submission
Before saving the attempt, the server runs validateAttempt to ensure the submitted data matches the generated exam exactly. This function performs a triple-nested verification:
- Confirms every
questionSetID exists in the generated exam - Confirms every
questionID exists within its respective question set - Confirms every
answerID exists within its respective question
If any mismatch is detected, the system creates an ExamEnvironmentExamModeration record with status Pending and links it to the attempt via examModerationId. The client receives a 400 error indicating validation failure.
Stage 4: Determining Final Status
The constructEnvExamAttempt function resolves the attempt’s final state by checking:
- Time window: If the exam duration has not elapsed →
InProgress - Expiration: If time elapsed with no moderation record →
Expired - Moderation status:
Pending→PendingModerationDenied→DeniedApprovedor no moderation →Approved
These statuses are defined in the ExamAttemptStatus enum.
Stage 5: Calculating the Score
Once an attempt reaches Approved status, calculateScore compares the user’s selected answer IDs against the correct answers defined in the original exam (accessed via the generated exam). It returns a percentage score and a boolean pass/fail flag, which are stored in the attempt’s result field.
Data Models Behind Exam Tracking
The tracking system relies on five core Prisma models defined in api/prisma/exam-environment.prisma:
- ExamEnvironmentExam: The master exam definition containing question sets, configuration, and prerequisites.
- ExamEnvironmentGeneratedExam: A deterministic snapshot of the master exam containing specific question and answer IDs for a single user session.
- ExamEnvironmentExamAttempt: Records the user’s answers, submission times, and links to the generated exam and moderation records.
- ExamEnvironmentExamModeration: Stores moderation status (
Pending,Approved,Denied) and reviewer feedback when validation fails. - ExamEnvironmentAuthorizationToken: Grants the desktop application permission to access exam environment routes.
Validation Flow in Detail
The validateAttempt function in api/src/exam-environment/utils/exam-environment.ts implements a strict integrity check to prevent tampering. When the client submits an attempt payload, the server executes the following nested iteration:
for (const attemptQuestionSet of questionSets) {
const generatedQuestionSet = generatedExam.questionSets.find(
qs => qs.id === attemptQuestionSet.id
);
// throws if missing …
for (const attemptQuestion of attemptQuestionSet.questions) {
const generatedQuestion = generatedQuestionSet.questions.find(
q => q.id === attemptQuestion.id
);
// throws if missing …
for (const attemptAnswer of attemptQuestion.answers) {
const generatedAnswer = generatedQuestion.answers.find(
a => a === attemptAnswer
);
// throws if missing …
}
}
}
If any check fails, the route handler catches the error and creates a moderation record using examEnvironmentExamModeration.upsert, setting the examModerationId on the attempt. This triggers the PendingModeration status, queueing the attempt for human review.
Client-Side Integration
The freeCodeCamp client consumes these endpoints through specific UI components:
- finish-exam-modal.tsx: Located at
client/src/templates/Challenges/exam/components/finish-exam-modal.tsx, this component triggers the final POST request to/exam-environment/exam/attemptwhen the user clicks "Finish Exam". - exam-results-modal.tsx: Found at
client/src/components/SolutionViewer/exam-results-modal.tsx, this component polls the GET endpoint/exam-environment/exam/attempt/:attemptIdto retrieve thestatusandresultfields, displaying the final score or moderation message.
The desktop application must include a valid exam-environment-authorization-token header obtained through the ExamEnvironmentAuthorizationToken flow.
Summary
- Exam attempts are tracked through a five-stage pipeline: generation, recording, validation, status resolution, and scoring.
- Validation occurs via
validateAttemptinapi/src/exam-environment/utils/exam-environment.ts, which cross-references submitted answers against theExamEnvironmentGeneratedExamto detect tampering. - Moderation is triggered automatically when validation fails, creating an
ExamEnvironmentExamModerationrecord and setting the attempt status toPendingModeration. - Final status is determined by
constructEnvExamAttempt, which checks time windows and moderation records to returnInProgress,Expired,PendingModeration,Approved, orDenied. - Scoring only occurs for
Approvedattempts viacalculateScore, comparing user selections against correct answers in the generated exam.
Frequently Asked Questions
What happens if a user submits answers that don't match the generated exam?
If the submitted question IDs, question set IDs, or answer IDs do not exist in the ExamEnvironmentGeneratedExam associated with the attempt, the validateAttempt function throws an error. The route handler catches this and creates an ExamEnvironmentExamModeration record with status Pending, linking it to the attempt. The attempt status then becomes PendingModeration, queueing it for human review.
How does the system prevent users from continuing an exam after the time limit expires?
The constructEnvExamAttempt function checks the elapsed time against the exam duration defined in the ExamEnvironmentExam configuration. If the time window has elapsed and no moderation record exists, the function returns status Expired. The client-side components, such as finish-exam-modal.tsx, use this status to prevent further submissions and display the appropriate UI state.
What is the difference between ExamEnvironmentExam and ExamEnvironmentGeneratedExam?
ExamEnvironmentExam is the master template containing all possible question sets, configuration, and prerequisites for a certification exam. ExamEnvironmentGeneratedExam is a deterministic snapshot created when a user starts an exam, containing only the specific question IDs and answer IDs assigned to that user session. This separation ensures that each user receives a consistent, frozen set of questions while the master exam can be updated independently.
When is the exam score calculated and how is it determined?
The score is calculated only when an attempt reaches Approved status. The calculateScore function in api/src/exam-environment/utils/exam-environment.ts compares the user's selected answer IDs stored in ExamEnvironmentExamAttempt against the correct answers defined in the original ExamEnvironmentExam (accessed via the generated exam). It returns a percentage score and a boolean pass/fail flag, which are stored in the attempt's result field and displayed to the user via exam-results-modal.tsx.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →