Skip to content
This repository was archived by the owner on Aug 19, 2026. It is now read-only.

feat: add cross-cohort metrics endpoint - #90

Open
Vayras wants to merge 9 commits into
mainfrom
feat/cohort-metrics-endpoint
Open

Vayras wants to merge 9 commits into
mainfrom
feat/cohort-metrics-endpoint

Conversation

@Vayras

@Vayras Vayras commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Adds GET /cohorts/metrics (TA/Admin only), returning CohortMetricsDto[] — 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), with retainedStudents as the underlying count.
  • completionRate = fraction of registered members who attended the cohort's GRADUATION week (0 until the cohort actually reaches it).
  • Calculation logic extracted into a pure computeCohortMetrics() helper (src/cohorts/cohort-metrics.util.ts) for reuse/readability.

Test plan

  • tsc --noEmit passes
  • eslint passes on changed files
  • Manually hit GET /cohorts/metrics as a TA/Admin user against a seeded DB and spot-check numbers against a known cohort

🤖 Generated with Claude Code

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>
@Vayras
Vayras marked this pull request as ready for review July 31, 2026 11:44
Comment on lines +102 to +110
@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();
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/metrics is two segments, so unlike the current literal metrics it 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 a NotFoundException for an unknown cohort like getCohort does.
  • Rename to getCohortMetrics and 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UI displays all cohorts together in a graph, so having them in a single endpoint makes sense to me. Having them on a per-cohort basis would increase the number of calls made to get the same data this returns in a single api
Screenshot 2026-08-02 at 11 06 04 PM

Comment on lines +1187 to +1199
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 },
}),
]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: true to the where. Line 1203 throws away the unattended rows in JS; feedback.service.ts:67-74 already pushes the same filter into SQL:
    where: { user: { id: user.id }, cohort: { id: cohortId }, attended: true }
  • select.id fetches a UUID nothing reads.
  • relations: { cohortWeek: true } forces a join to cohort_week purely to read cohortWeek.id — which is already the cohortWeekId FK on the attendance row. Selecting attendance.cohortWeekId via 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.

Comment on lines +1218 to +1220
const completedGdWeeks = gdWeeks.filter(
(week) => week.scheduledDate <= now,
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/cohorts/cohorts.service.ts Outdated
Comment on lines +1243 to +1251
const completedStudents =
totalParticipants &&
finalGdWeek &&
finalGdWeek.scheduledDate <= now
? (attendedCountByWeek.get(finalGdWeek.id) ?? 0)
: 0;
const completionRate = totalParticipants
? completedStudents / totalParticipants
: 0;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 - absenceThresholdDays

with 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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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%?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be fixed

cohortId!: string;
cohortType!: CohortType;
seasonNumber!: number;
startDate!: string;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

theanmolsharma and others added 2 commits August 10, 2026 09:55
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>
@theanmolsharma
theanmolsharma force-pushed the feat/cohort-metrics-endpoint branch from 5d5f12e to 64ef49f Compare August 10, 2026 04:26
theanmolsharma and others added 2 commits August 10, 2026 12:28
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>
@theanmolsharma
theanmolsharma force-pushed the feat/cohort-metrics-endpoint branch from 64ef49f to 36bf076 Compare August 10, 2026 06:58
Vayras and others added 4 commits August 10, 2026 15:09
…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>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants