Attributing Screenshots to Tasks With a Merge Sweep: How a 35-Second Sprint Report Stopped Waiting

Happy Tracker’s project report has an Advanced tab that answers one question per sprint: where did the hours go, and who spent them? For every task it shows the tracked time, the estimate, a Who worked column, and how many screenshots were captured while that task was running. That last number sounds trivial. It is not, because a screenshot does not know which task it belongs to. It only knows who took it and when.
The first version of the attribution code was correct and took about 35 seconds on a real month of data. This post is about why, and about the small change that removed the problem: treating attribution as a merge of two sorted lists instead of a search. Along the way it covers the other decisions in the same endpoint that keep it fast: scoping a sprint by its tasks rather than its dates, loading only the screenshots that can matter, skipping model hydration for the big result set, and a hard cap as a safety valve.
What the report has to compute
The inputs are two tables. Time entries have a user, a task, a start and an end (or no end, if the timer is still running). Screenshots have a user and a timestamp. The desktop app takes captures on a schedule while someone is clocked in, so in a busy month an organization can have tens of thousands of them.
The rule for attribution is simple. A screenshot belongs to the task whose entry was open, for that user, at the moment the screenshot was taken. If no entry was open, it belongs to nothing in this report. That rule matters for correctness: a person who switched from a bug fix to a code review at 11:40 should have their 11:42 capture counted against the review, not the bug.

Step one: choose the entries by sprint, not by calendar
Before attributing anything, the endpoint decides which entries are in scope. For a month view, that is every entry that started in the month. For a sprint, it is different on purpose:
$entries = $organization->timeEntries()->work()
->with('task:id,title,external_key,estimate_minutes,project_id,sprint_id', 'project:id,name', 'user:id,name')
// Sprint scope = every entry on this sprint's tasks (regardless of when logged);
// month scope = every entry started within the month.
->when($sprintId, fn ($q) => $q->whereHas('task', fn ($t) => $t->where('sprint_id', $sprintId)))
->when(! $sprintId, fn ($q) => $q->whereBetween('started_at', [$from, $to]))
->when($projectId, fn ($q) => $q->where('project_id', $projectId))
->get();
A sprint is a set of tasks with planned dates, and work does not respect planned dates. Someone finishes a sprint task the morning after the sprint ends. Someone starts a card two days early because they had a gap. If the report filtered by the sprint’s dates, those hours would vanish from the sprint and appear nowhere useful. Filtering by “entries on this sprint’s tasks” gives the cost of the sprint’s work, which is what a sprint review is asking for.
That choice has a knock-on effect on the screenshot query. The sprint’s planned dates no longer bound the entries, so they cannot bound the captures either. The endpoint widens the screenshot window to the real span of the entries it found:
// For a sprint, widen the screenshot window to the actual span of its entries so
// captures logged outside the planned dates are still attributed.
if ($sprintId && $entries->isNotEmpty()) {
$from = $entries->min(fn ($e) => $e->started_at)->copy();
$to = $entries->max(fn ($e) => $e->ended_at ?? now())->copy();
}
// Screenshots only for the people who actually logged time in range: without that
// the query fans out across the whole organization for a one-project view.
$userIds = $entries->pluck('user_id')->unique()->values();
// ->toBase() keeps these as plain rows. A busy month is tens of thousands of
// captures, and hydrating a model per row costs more than everything else here.
$shots = $userIds->isEmpty()
? collect()
: $organization->screenshots()
->whereBetween('taken_at', [$from, $to])
->whereIn('user_id', $userIds)
->orderBy('user_id')->orderBy('taken_at')
->toBase()
->get(['user_id', 'phash', 'taken_at']);
Three details in that block do more for performance than any clever algorithm:
- Only users who logged time. A one-project report for a 40-person company might involve six people. Without
whereIn('user_id', $userIds), the query would read every capture in the organization for the period and throw most of them away in PHP. - Ordered by user, then time. The database is much better at sorting than PHP, and with an index that covers the user and the capture time, the rows come back in the order the sweep needs at very little cost. This ordering is the whole basis of the algorithm below.
toBase()and three columns. Eloquent models are convenient and expensive. Hydrating twenty thousandScreenshotobjects, each with casts, attributes and relations, costs more memory and time than the rest of the request combined. The report needs a user id, a timestamp and a hash. Plain row objects are enough.
The slow version
The obvious way to attribute captures is to ask, for each capture, “which entry contains this moment?” The original code did exactly that. Simplified, it looked like this:
// Roughly what the first version did: for every capture, search for the entry that contains it.
foreach ($shots as $shot) {
$entry = $entries->first(fn ($e) =>
$e->user_id === $shot->user_id
&& $e->started_at->lte(Carbon::parse($shot->taken_at))
&& ($e->ended_at ?? now())->gte(Carbon::parse($shot->taken_at))
);
if ($entry) {
$rows[$keyFor($entry->task_id)]['captures']++;
}
}
It reads well and it is correct. It is also O(captures × entries). For each of the twenty thousand captures, first() walks the entry collection from the start until it finds a match, and on average that is a long walk. On top of that, every comparison parses a timestamp into a Carbon object and compares Carbon instances, which is several method calls and an object allocation per comparison. Multiply those and you get the 35 seconds we measured on a real month, inside a request that a manager expects to load while they wait.
Two separate costs are hiding in there, and they need two separate fixes. One is algorithmic: comparing every capture against every entry. The other is constant-factor: doing date maths with objects inside the hottest loop in the request.
The constant factor: integers, not Carbon
The fix for the second cost is to convert everything to Unix timestamps once, before the loop, and compare integers inside it. The entries become small arrays per user, sorted by start:
$nowTs = now()->getTimestamp();
$ranges = [];
foreach ($entries as $entry) {
$ranges[$entry->user_id][] = [
'start' => $entry->started_at->getTimestamp(),
'end' => ($entry->ended_at?->getTimestamp() ?? $nowTs), // a running entry ends "now"
'key' => $keyFor($entry->task_id),
];
}
foreach ($ranges as &$list) {
usort($list, fn ($a, $b) => $a['start'] <=> $b['start']);
}
unset($list);
Two things to notice. A running entry (no ended_at yet) is treated as ending now, so a capture taken a minute ago lands on the task that is currently open. And the sort happens per user, because the sweep runs per user: one person’s entries never need to be compared with another’s.
On the capture side, strtotime($shot->taken_at) turns the raw string into an integer. That is one C function call per capture, with no object created.
The algorithm: one pointer per user
Now both lists are sorted by time within each user. That is exactly the setup for a merge sweep, the same idea as the merge step in merge sort. Keep a pointer into the user’s entries. For each capture, move the pointer forward past every entry that ended before the capture. Then the entry under the pointer is the only one that can contain the capture:
// Attribution is a merge sweep, not a search. Both sides are ordered by
// (user, time), so one monotonic pointer per user walks each list once.
$cursor = [];
foreach ($shots as $shot) {
$uid = $shot->user_id;
if (! isset($ranges[$uid])) {
continue;
}
$list = $ranges[$uid];
$count = count($list);
$ts = strtotime($shot->taken_at);
$i = $cursor[$uid] ?? 0;
while ($i < $count && $list[$i]['end'] < $ts) {
$i++; // this entry ended before the capture: never look at it again
}
$cursor[$uid] = $i;
// A capture outside every in-scope entry belongs to work we are not reporting on.
if ($i >= $count || $list[$i]['start'] > $ts) {
continue;
}
$rows[$list[$i]['key']]['captures']++;
}
The key property is that the pointer only ever moves forward. Captures arrive in time order, so an entry that ended before this capture also ended before every later capture. Once the pointer passes it, it never needs to be looked at again. Each user’s entry list is walked once in total, and each capture is handled once, so the whole attribution is O(captures + entries) instead of O(captures × entries).
The continue branch handles the gaps. If the pointer has run off the end, or the entry under it starts after the capture, the capture fell between entries: the person had stopped the timer, or was on a break, or the capture belongs to work outside the project being reported. It is not counted. That is deliberate. Guessing the nearest task would inflate captures on whatever task happened to be next to a gap.

What it assumes
A sweep is only correct if its inputs really are sorted, and only simple if entries for one user do not overlap. Both are worth stating rather than hoping:
- Captures are sorted by the query, by user and then time. If someone later removes the
orderByto “simplify” the query, the sweep will silently skip captures. A comment next to the query saying the loop depends on it is cheap insurance. - Entries are sorted in PHP per user, so their order from the database does not matter.
- Overlapping entries. A person normally has one timer running at a time, so entries for one user should not overlap. If an edited entry does overlap another, the sweep attributes the capture to the earlier entry whose end has not passed. That is a reasonable tie-break, and it never double-counts a capture.
Prove the fast version agrees with the slow one
A rewrite like this has an unusual advantage: the slow version is still the clearest statement of what the answer should be. Keep it, in the test suite, and use it as the reference. Generate random days of entries and captures, run both, and require identical results:
it('the sweep attributes exactly like the slow search', function () {
mt_srand(42); // reproducible random data
for ($round = 0; $round < 200; $round++) {
[$entries, $shots] = randomDay(users: 3, entries: rand(1, 12), shots: rand(0, 80));
$expected = attributeBySearch($entries, $shots); // the old, obviously-correct version
$actual = attributeBySweep($entries, $shots); // the new one
expect($actual)->toBe($expected, "round {$round}");
}
});
// randomDay() builds non-overlapping entries per user with random gaps between them,
// sometimes leaves the last one running, and scatters captures across the whole day,
// including inside the gaps and exactly on entry boundaries.
The random generator is where the value is. Hand-written fixtures tend to test the cases the author already thought about. A generator that places captures in gaps, on the exact second an entry starts or ends, and after a still-running entry finds the off-by-one mistakes that a sweep invites. The most likely one is using <= where the original used < on an entry’s end time, which moves boundary captures to the next task. Two hundred rounds with a fixed seed take well under a second and make the test reproducible when it does fail.
It is worth keeping the boundary rule explicit in both versions. Here a capture taken at exactly the second an entry ends still belongs to that entry, because the sweep only skips entries whose end is strictly before the capture. Whichever rule you choose, the equivalence test makes sure the fast code and the reference agree on it.
Who worked: the same pass, a different sum
The Who worked column needs no extra query. While the endpoint sums tracked seconds per task, it also sums them per task per person. At the end, each row gets its people sorted by time, the top three, and a total count so the interface can show “and 2 more”:
// While summing tracked time per task, also sum it per person.
$name = $entry->user?->name ?? ('User '.$entry->user_id);
$workerSeconds[$key][$name] = ($workerSeconds[$key][$name] ?? 0) + $entry->seconds();
// ...later, per row: who worked on this task, most time first.
$workers = collect($workerSeconds[$key] ?? [])
->map(fn ($seconds, $name) => ['name' => $name, 'seconds' => (int) $seconds])
->sortByDesc('seconds')->values();
$row['workers'] = $workers->take(3)->all();
$row['worker_count'] = $workers->count();
Sending the top three instead of everyone keeps the payload small for the table. The full list only matters when a manager expands one row, and that is a separate request.
Load the drill-down only when asked
Expanding a task row shows two short lists: every person who worked on it with their hours, and the time split by activity category (coding, meetings, browsing and so on). That data comes from a second endpoint, called only for the row being expanded. The main table stays one request regardless of how many tasks the sprint has, and the expensive per-category grouping runs for one task at a time, when a person has actually asked to see it.
This is the same idea as the screenshot query, applied at the interface level: do the work for what is on screen, not for everything that could be.
Why not do the join in SQL?
A fair question is why the attribution happens in PHP at all. A range join, screenshots joined to entries on user and “taken_at between started_at and ended_at”, expresses the same rule in one query. It works, and for a small month it is fine. Three things pushed us towards the sweep instead.
First, MySQL handles range joins poorly. Without a specialised index, the planner falls back to comparing each capture against many entries, which is the same quadratic shape we were trying to escape, just moved into the database. Second, running entries have no end time, so the join needs a COALESCE(ended_at, NOW()) on the indexed side of the comparison, which defeats the index. Third, the endpoint needs the entries in PHP anyway, to sum tracked time and build Who worked. Loading the captures once, sorted, and walking both lists in memory uses data the request already has.
If your data is much larger, or your database is PostgreSQL with range types and GiST indexes, the trade-off can come out differently. The point is to choose deliberately, not to assume that SQL is always faster than code.
A cap as a safety valve
Even with a linear sweep, the cost of the report grows with the number of captures, and the number of captures grows with the length of the window. A team that set up a three-month “sprint” as a container for a whole phase would make the endpoint do three months of work in one request. So there is a hard limit:
if ($sprint->start_date && $sprint->end_date
&& $sprint->start_date->diffInDays($sprint->end_date) > 31) {
abort(422, 'This sprint spans more than a month. The detailed report is limited to one-month sprints.');
}
A 422 with a clear sentence is better than a request that times out after thirty seconds with no explanation. The interface shows the message, and the person knows exactly what to change. Two-week sprints, which is what most teams run, are far inside the limit.
The cap is a product decision as much as a performance one. A report covering a three-month sprint is rarely what a sprint review needs. When someone hits the limit, it is usually a sign the sprint should have been split.
What changed, in numbers
The 35-second figure came from one real month. We have not published a benchmark beyond that, and the honest summary is about shape rather than a single number:
- The algorithmic cost went from captures × entries to captures + entries. Doubling the data now roughly doubles the work, instead of quadrupling it.
- The inner loop does integer comparisons instead of creating Carbon objects.
- The screenshot query reads only the users and the window that can matter, already sorted, without hydrating models.
Any one of these helps. Together they turn a report people waited for into one they can open during the review meeting itself.
Takeaways for your own reports
- Scope by meaning, not by convenience. A sprint is its tasks, not its dates. Then make sure every dependent query follows that choice.
- Push sorting and filtering into SQL. Ask only for the rows that can matter, in the order your code needs.
- Skip hydration for bulk rows.
toBase()and a column list are the cheapest optimisation in Laravel. - When you see “for each X, find the Y that contains it”, look for an order. If both sides can be sorted by the same key, a merge sweep is usually the answer.
- Keep date objects out of hot loops. Convert once, compare integers.
- Write down what the fast version assumes. A sweep that depends on an
orderByneeds a comment saying so. - Put a clear limit on the expensive path and say why in the error message.
Happy Coders builds web apps, SaaS products and websites, including our own time tracker. Tell us what you are building.



