# Two tabs, one student: computing class attendance as a union of intervals in Django

By Farhad Rezaei (https://farhad-rezaei.com) · Published 2026-12-02
Canonical: https://farhad-rezaei.com/blog/two-tabs-one-student-attendance-as-interval-union
Product: Talkemi (https://talkemi.com/en)

> Talkemi used to compute attendance by adding up every join-to-leave interval, so a student with two tabs open could be credited with more time than the class lasted: in the test's example, 30 plus 40 minutes became 70 in a 60-minute class. The fix sorts the intervals, merges overlapping ones, sums what's left and keeps real gaps between rejoins. Because both tabs carry the same profile id, the union stays correct even though the leave handler can't tell which tab left.

[Talkemi](https://talkemi.com/en) is a language-learning platform I built. Its live classes run in Jitsi video rooms, and when a class ends the Django backend turns the room's join and leave events into minutes attended for each student. Those minutes decide the enrollment's final status: COMPLETED or ABSENT. An earlier piece in this series, [Two short transactions around an LLM call](https://farhad-rezaei.com/blog/two-short-transactions-around-an-llm-call), covered the AI side; this one is about counting time.

Until a commit in June 2026, the backend added up every join-to-leave interval it had for a student. A student with two tabs open, one for 30 minutes and one for 40, came out at 70 minutes in a 60-minute class. Those numbers come from the test I wrote for the fix, not from a reported case. But the code path was real: any student who opened the class twice could get credit for time they didn't spend.

For the school, that's a status that can be wrong in the student's favour. Attendance passes at 50% of the class by default, so doubled minutes could turn a short visit into a COMPLETED class.

Think of an office with two entrances, where you badge in at both. Count each badge's time separately and you seem to have been there twice as long. The honest number is the time you were inside through any door.

## What happens when a student opens the class twice

Each student's join link carries a JWT, and the JWT's `context.user.id` is the student's profile id. A test, `test_student_link_carries_stable_profile_id`, checks that two links generated for the same student carry the identical id. So a second tab is the same person to the server.

When a tab joins, Prosody sends a `participant.joined` webhook that forwards that id as `user_id`. The handler resolves the enrollment through `registry_by_uid`, a map built at meeting start from profile id to enrollment id. Display names are only a fallback for older payloads. It then appends an entry with `joined_at`.

The second tab does exactly the same, so the student now has two open entries. When a tab leaves, the leave handler finds the first still-open entry with that id and sets its `left_at`. At class end, `sync_attendance_from_jitsi` reads all entries, computes each student's minutes and compares them with the threshold.

![Five steps: a join event carries the profile id from the join JWT, registry_by_uid resolves the enrollment, each join records an interval and a leave closes one still-open entry, intervals are merged and floored to whole minutes, and minutes at or above the threshold mark the enrollment COMPLETED, otherwise ABSENT.](https://farhad-rezaei.com/images/blog/two-tabs-one-student-attendance-as-interval-union/pipeline.svg)

## Why the sum was wrong, and why the union is right

The old `_calculate_student_minutes` did `total_seconds += left_at - joined_at` for every matching entry. That's correct for a student who leaves and rejoins, because the intervals don't overlap. It's wrong the moment two of them overlap, which is exactly what two tabs are: two badges for one door-to-door stay.

The fix treats attendance as the length of the union of the intervals. It collects each matching `(joined_at, left_at)` pair, sorts by start, and walks the list once:

```python
intervals.sort(key=lambda iv: iv[0])
cur_start, cur_end = intervals[0]
for start, end in intervals[1:]:
    if start <= cur_end:  # overlaps current run → extend
        if end > cur_end:
            cur_end = end
    else:  # gap → close current run, open a new one
        total_seconds += (cur_end - cur_start).total_seconds()
        cur_start, cur_end = start, end
total_seconds += (cur_end - cur_start).total_seconds()
```

Older entries could hold naive datetimes, while the class end is timezone-aware, and Python refuses to compare the two. So every parsed time is made aware first, and entries with no positive length are dropped.

There's a quieter reason the union suits this event model. Both tabs share one id, so the leave handler can't tell which tab left and closes the first open entry. A per-session sum would care. The union doesn't: the student is present whenever more joins than leaves have happened, and that count doesn't depend on how leaves were paired with joins.

Nothing refuses a second tab at join time, and that has a benefit: refusing one would also block a student moving from laptop to phone mid-class. The events stay as they arrived, and overlap is resolved once, when the class ends.

![On a 60-minute class: two tabs from 0 to 30 and 0 to 40 minutes summed to 70, while their union is 40. A visit from 0 to 10 and a rejoin from 20 to 30 still count 10 plus 10, 20 minutes, with the gap left out.](https://farhad-rezaei.com/images/blog/two-tabs-one-student-attendance-as-interval-union/union.svg)

## What the fix doesn't know

A merge is only as good as the events behind it. An entry with no `left_at`, say a dropped connection that never sent a leave, runs to the class's actual end. That's an inference, and it gives the student the benefit of the doubt. Legacy entries without an enrollment id are still matched by email or display name. When nothing matches, a fallback uses the enrollment's own `joined_at`, capped at the class length, because that field records when the enrollment was created, not when the student walked in. Totals are floored to whole minutes. And after the sync the raw participant list is replaced by a compact `attendance_summary`, so minutes can't be recomputed later.

## How I verified it

`CalculateStudentMinutesTests` feed the function hand-built intervals: two tabs leaving at 30 and 40 minutes give 40 (`test_overlapping_intervals_counted_once`), 0 to 20 plus 10 to 30 gives 30, a real rejoin stays at 10 plus 10, and an entry with no leave runs to the class end. `WebhookUidMappingTests` cover the identity side: a join resolves the enrollment by `user_id`, and a leave with that id closes the open interval. `RejoinIntervalsTests`, from an earlier fix, check that a second leave doesn't overwrite the first interval's `left_at`.

What they don't prove: no test drives two real browser tabs through Prosody, and the naive-datetime path has no test of its own.

## What carries over

- When several sessions can belong to one person, measure presence as the union of their intervals. Summing is only right when you know they can't overlap.
- Decide identity before you do arithmetic. A stable id from the token is what makes two tabs one student.
- If you can't pair a leave with the right join, prefer a metric that doesn't depend on the pairing.
- Write down every bound you inferred, like an open interval ending at class end, so nobody mistakes it for an observed event.

For a student, a second tab or device no longer changes their record, and leaving and coming back still counts both visits. For the school, COMPLETED now means time actually spent in the room, as far as the events can tell. The interval math is exact; what's left uncertain is missing leave events, and the code says so where it fills them in.

## Further reading

- Wikipedia, Klee's measure problem (the length of a union of intervals): https://en.wikipedia.org/wiki/Klee%27s_measure_problem
- Python documentation, aware and naive datetime objects: https://docs.python.org/3/library/datetime.html
- Django documentation, time zones: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/
- Jitsi Meet handbook: https://jitsi.github.io/handbook/
