Repository navigation
Conversation
Adds GET /cohorts/metrics (TA/Admin) returning retention, attendance, and completion metrics for every cohort in a single response. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
| @Get('metrics') | ||
| @ApiOperation({ | ||
| summary: | ||
| 'Get retention, attendance, and completion metrics for every cohort', | ||
| }) | ||
| @Roles(UserRole.TEACHING_ASSISTANT, UserRole.ADMIN) | ||
| async getAllCohortsMetrics(): Promise<CohortMetricsDto[]> { | ||
| return this.cohortsService.getAllCohortsMetrics(); | ||
| } |
There was a problem hiding this comment.
I'd make this per-cohort — GET /cohorts/:cohortId/metrics returning a single CohortMetricsDto — rather than every cohort in one shot.
The UI only ever displays one cohort's metrics at a time, so as written every request pays to compute and serialise data nobody looks at, and both the query cost and the response size grow with every cohort we ever run. Scoping to one cohort also lets the underlying queries be bounded by where: { cohort: { id: cohortId } }, which removes most of the over-fetching I've flagged in the service.
A few things that come with the change:
:cohortId/metricsis two segments, so unlike the current literalmetricsit can't be shadowed by@Get(':id')on line 122 — placement stops being load-bearing, and it reads consistently with the other:cohortId/...routes.- Add
@Param('cohortId', new ParseUUIDPipe())to match every other id param in this controller, and aNotFoundExceptionfor an unknown cohort likegetCohortdoes. - Rename to
getCohortMetricsand update the summary, which currently says "for every cohort".
If a cross-cohort comparison view does turn up later, that's a good argument for a separate aggregate endpoint with its own (bounded, probably GROUP BY) query — not for making the common case pay for it.
| const [cohorts, attendances] = await Promise.all([ | ||
| this.cohortRepository.find({ | ||
| relations: { weeks: true, memberships: true }, | ||
| }), | ||
| this.attendanceRepository.find({ | ||
| select: { | ||
| id: true, | ||
| attended: true, | ||
| cohortWeek: { id: true }, | ||
| }, | ||
| relations: { cohortWeek: true }, | ||
| }), | ||
| ]); |
There was a problem hiding this comment.
Scoping this to one cohort (see the controller comment) fixes the biggest problem here — attendanceRepository.find() currently has no where at all, so it transfers every attendance row ever created, one per member per week per cohort, forever. Three things worth fixing on top of that, since they survive the rescoping:
- Add
attended: trueto thewhere. Line 1203 throws away the unattended rows in JS;feedback.service.ts:67-74already pushes the same filter into SQL:where: { user: { id: user.id }, cohort: { id: cohortId }, attended: true }
select.idfetches a UUID nothing reads.relations: { cohortWeek: true }forces a join tocohort_weekpurely to readcohortWeek.id— which is already thecohortWeekIdFK on the attendance row. Selectingattendance.cohortWeekIdvia QueryBuilder drops the join entirely.
The cohort query has its own version of this, and it doesn't go away with one cohort either: joining weeks and memberships in a single find gives a cartesian product (weeks × memberships), and every duplicated week row hydrates the questions, bonusQuestions, readingMaterial and exercise jsonb blobs — when all we use is id, week, type and scheduledDate. Could you select those four columns, and get the participant count without hydrating membership entities (loadRelationCountAndMap, or a COUNT over cohort_membership)?
Reducing in JS is fine and matches the house style — scores.service.ts:245-322 is the same shape — the ask is just to bound what gets pulled into memory.
| const completedGdWeeks = gdWeeks.filter( | ||
| (week) => week.scheduledDate <= now, | ||
| ); |
There was a problem hiding this comment.
scheduledDate <= now means the session has started, not that it's over, but the names (completedGdWeeks, lastCompletedWeek) assert the stronger claim.
That gap is load-bearing here: attendance rows are pre-created for every member at enrollment (cohorts.service.ts:1015-1020) and attended is boolean NOT NULL DEFAULT false (attendance.entity.ts:20-21), so "not yet marked by a TA" and "was absent" are indistinguishable. The instant a week's scheduledDate passes it joins completedGdWeeks contributing zero attended — retainedStudents/retentionRate read only that week and drop to 0, and avgAttendanceRate loses a full week's worth. A live cohort will show 0% retention from the moment each session begins until someone records attendance.
Could we gate on the session actually being finished — scheduledDate + <grace> in the past, with the grace period as a named constant alongside the other cohort constants — and rename these to match the predicate?
There was a problem hiding this comment.
I think this is over-engineering a very simple endpoint on the assumption that the student will remain unmarked by the TA, in my opinion
| const completedStudents = | ||
| totalParticipants && | ||
| finalGdWeek && | ||
| finalGdWeek.scheduledDate <= now | ||
| ? (attendedCountByWeek.get(finalGdWeek.id) ?? 0) | ||
| : 0; | ||
| const completionRate = totalParticipants | ||
| ? completedStudents / totalParticipants | ||
| : 0; |
There was a problem hiding this comment.
I think this is always identical to retentionRate. Once finalGdWeek.scheduledDate <= now, finalGdWeek is lastCompletedWeek (line 1222) — same week's attendance count, same denominator. Before that it's hard-coded 0. So the field adds no information beyond retentionRate plus "has the last session happened yet".
It will also contradict the definition of "completed the cohort" we already have, in certificate eligibility (certificates.service.ts:71-76):
entry.totalGroupDiscussionAttendance >=
entry.maxGroupDiscussionAttendance - absenceThresholdDayswith per-cohort-type thresholds in certificates.constants.ts:49. An admin comparing this dashboard against certificates issued for the same cohort would see two different completion numbers.
Suggest defining this as the share of members whose attended-GD-week count is within ABSENCE_THRESHOLD_DAYS[cohort.type] of the cohort's total GD week count. That needs attendance grouped by user as well as by week — one more map in the same pass — and it makes the metric genuinely independent of retentionRate.
| startDate!: string; | ||
| totalParticipants!: number; | ||
| retainedStudents!: number; | ||
| retentionRate!: number; |
There was a problem hiding this comment.
All three rate fields return 0 for a cohort that hasn't started yet, has no members, or has no group-discussion weeks — the same value as a cohort where attendance was genuinely zero. Those are very different facts on a dashboard and the client can't tell them apart.
Could these be number | null, returning null when the metric isn't applicable yet, so the UI can render "—" instead of a misleading 0%?
| cohortId!: string; | ||
| cohortType!: CohortType; | ||
| seasonNumber!: number; | ||
| startDate!: string; |
There was a problem hiding this comment.
Related to the nullability point on retentionRate: the response has startDate but nothing indicating whether the cohort has finished, so a client can't interpret a low completionRate — still running, or people genuinely didn't complete?
cohort.getEndDate() (cohort.entity.ts:54-66) already answers this and the service loads the weeks relation, so it's available and currently unused. Adding endDate (or a derived hasEnded) would make these metrics interpretable client-side.
| totalParticipants!: number; | ||
| retainedStudents!: number; | ||
| retentionRate!: number; | ||
| avgAttendanceRate!: number; |
There was a problem hiding this comment.
Worth an explicit decision on unit and precision for all three rate fields. Nothing states these are 0–1 fractions rather than percentages, and they're unrounded, so values like 0.6333333333333333 will go over the wire.
No existing *Rate field in the codebase to set precedent, but the two places that do normalize a ratio both round it — exercise-score.entity.ts:61-65 and group-discussion-score.entity.ts:127-131:
return Math.round((this.totalScore / this.maxScore) * SCALING_FACTOR.EXERCISE);and everywhere a proportion is communicated, the codebase ships numerator and denominator as separate ints rather than a ratio (LeaderboardEntryDto, scores.response.dto.ts:224-227: totalGroupDiscussionAttendance / maxGroupDiscussionAttendance).
Either follow that and expose the counts, or keep fractions but round them and document the unit on the field.
Introduce a strongly-typed, single-row-per-type store for precomputed metrics (ComputedMetric<T> + MetricType/MetricDataMap), modeled on the APITask<T> payload pattern. The versioned CohortMetricsData payload is intentionally duplicated from CohortMetricsDto so the stored schema stays pinned to COHORT_METRICS_VERSION as the API DTO evolves. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
5d5f12e to
64ef49f
Compare
Move the retention/attendance/completion computation off the request path: a self-rescheduling COMPUTE_COHORT_METRICS task recomputes once a day and upserts the single stored row, and GET /cohorts/metrics becomes a cheap read of that row (plus a computedAt timestamp). A migration creates computed_metric and seeds the first task so the store populates on deploy. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
completionRate was effectively retentionRate (or 0 before the final session), carrying no independent signal. Redefine it to match certificate eligibility (certificates.service.ts): the share of members who attended all but ABSENCE_THRESHOLD_DAYS[type] of the cohort's GD weeks, computed once the cohort has ended. Guard getEndDate() against weekless cohorts so one unscheduled cohort can't fail the daily batch. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
64ef49f to
36bf076
Compare
…certificates Retention now averages each completed GD week's attendance against the first GD week's, instead of an absence-threshold headcount that made it numerically identical to completion once a cohort ended. Completion now counts issued Certificate rows over registered members instead of recomputing certificate-eligibility live.
…ek attendance The first-week-baseline average could exceed 100% whenever a later week out-drew week one, and said nothing about how many of totalParticipants were still showing up. Retention is now last-completed-GD-week attendance over totalParticipants — bounded, and independent of completion (actual certificates issued).
…t week Retention now averages each completed GD week's attendance against the cohort's best-attended week (whichever week that was), rather than just the most recent week's headcount. Still bounded 0-100% since every week is compared against the max, and reflects the whole attendance trend instead of a single snapshot.
Multi-line relations object was on one line, failing the lint CI check. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

Summary
GET /cohorts/metrics(TA/Admin only), returningCohortMetricsDto[]— retention, attendance, and completion metrics for every cohort in one call.avgAttendanceRate= mean over completed weeks of (attended / registered).retentionRate= attendance rate of the most recently completed week (last point in the attendance trend), withretainedStudentsas the underlying count.completionRate= fraction of registered members who attended the cohort'sGRADUATIONweek (0 until the cohort actually reaches it).computeCohortMetrics()helper (src/cohorts/cohort-metrics.util.ts) for reuse/readability.Test plan
tsc --noEmitpasseseslintpasses on changed filesGET /cohorts/metricsas a TA/Admin user against a seeded DB and spot-check numbers against a known cohort🤖 Generated with Claude Code