Back to Blog

Why Your AI's Hours Worked Are Longer Than the Shift

Asked how long the agent was on the clock and got 5 hours. One session ran 9:00 to 12:00 and another 11:00 to 13:00. SUM of the lengths counts the overlap twice. The clock time is 4 hours.

You ask: "How long was this agent on the clock yesterday?" The AI says 5 hours. One session is 9:00–12:00. Another is 11:00–13:00. From the first start to the last end is 4 hours.

SELECT SUM(EXTRACT(EPOCH FROM (ended_at - started_at))) / 3600.0 AS hours
FROM sessions
WHERE user_id = 42
  AND ended_at IS NOT NULL

Each length is right. 3 hours plus 2 hours is 5. The hour from 11:00 to 12:00 is in both sessions, so it is in the total twice. The agent was present from 9:00 to 13:00.

Adding durations counts every session, including the overlap

SUM does not know that two ranges cover one clock. It adds whatever number you hand it. That number is the right answer for "how many session-hours did we bill?" and the wrong answer for "how long were they here?"

The merged time is the union of the ranges. In Postgres, range_agg merges overlaps:

SELECT SUM(EXTRACT(EPOCH FROM (upper(r) - lower(r)))) / 3600.0 AS hours_present
FROM (
  SELECT unnest(range_agg(tstzrange(started_at, ended_at, '[)'))) AS r
  FROM sessions
  WHERE user_id = 42
    AND ended_at IS NOT NULL
) s

That is 4. Keep the plain SUM when each session is a separate billable unit, and say so. "5 session-hours, 4 hours on the clock" is a complete answer. "5 hours worked" is not.

This is not a join that repeats the row. Count the session ids. Unique ids mean each call was summed once. The minutes inside the calls are what overlap. An open session, with ended_at NULL, is the other direction: SUM skips it, so a call still in progress adds nothing unless you decide it ends at now().

How to catch it

SELECT COUNT(*) AS overlapping_pairs
FROM sessions a
JOIN sessions b
  ON a.user_id = b.user_id
 AND a.id < b.id
 AND a.started_at < b.ended_at
 AND b.started_at < a.ended_at
WHERE a.user_id = 42

Any pair here was double-counted by a sum of lengths. Limit it to the person and the day before you run it on the whole table. If the summed hours are also greater than MAX(ended_at) - MIN(started_at), the overlap is large enough to stick out of the span.

The prompt that heads this off

When I ask how long someone worked, or how long something was busy,
merge overlapping sessions and sum the merged time. Do not sum the raw
lengths. If I ask for billed session-hours, sum the lengths and say that
overlaps are counted twice. Tell me both if they differ.

The short version

The sum of session lengths counts a shared hour once per session. That is billed time. Time on the clock is the merged range. If two sessions of the same person cross, the plain SUM is the larger number.


Read-only MCP gateway: mcpserver.design.

Related reading: