Split agent events into sessions by idle gap and report sessions per user

HardSQLPro

Product analytics for an AI assistant groups raw events into sessions: a new session starts when a user has been idle too long. This is a classic gaps-and-islands query built from two window functions.

Write query() returning a SQLite SQL string. Table events(user_id INTEGER, ts INTEGER), ts in seconds; a user may have several events at different times and rows are in no particular order.

For each user, sort events by ts. An event starts a new session if it is the user's first event or if it comes MORE THAN 1800 seconds after the user's previous event (exactly 1800 stays in the same session).

Return (user_id, sessions, longest_seconds) per user: the number of sessions, and the largest (last ts minus first ts) over that user's sessions (a one-event session lasts 0).

Order by user_id ascending.

Signaturedef query()

Example

user 1 at ts 0, 600, 5000. Result: [(1, 2, 600)].

Understand the idea

Session analysis groups raw events into visits: a new session starts at a user's first event or after more than 30 minutes (1800 seconds) of silence. It is a gaps-and-islands problem solved in steps. Worked example: user 2 has events at 100, 1900, 4000, 4100. Gaps: 1900 - 100 = 1800, not more than 1800, so same session; 4000 - 1900 = 2100, new session; 4100 - 4000 = 100, same. Sessions: [100, 1900] lasting 1800 and [4000, 4100] lasting 100. Answer (2, 2, 1800). A user with a single event has 1 session of length 0. Rule in words: use LAG to get each event's previous timestamp for the same user; flag 1 when there is no previous event or the gap exceeds 1800, else 0; a running SUM of the flags in time order gives a session number; group by user and session to get max ts minus min ts; then group by user to count sessions and take the longest. Sort by user_id. This is the standard way product teams measure how people use an AI assistant.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: example_run1(query())
  • Sample 2: several users, exact 1800 gaps_run2(query())