OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
session: return the newest sessions, and stop dropping the last day
Carl-Gerhard Lindesvärd3304948b6c74
diff --git a/packages/core/src/modules/session/session.service.ts b/packages/core/src/modules/session/session.service.tsindex 3e6d914d2..05d9d517b 100644--- a/packages/core/src/modules/session/session.service.ts+++ b/packages/core/src/modules/session/session.service.ts@@ -21,6 +21,7 @@ import { getSafeJson, resolveDateRange } from '@openpanel/shared';import { cacheablePerDeps } from '../../cacheable-per-deps';import { chQuery } from '../../ch-query';import type { ServiceDeps, Services } from '../../services';+import { toRangeBoundaryLiteral } from '../../shared/ch-dates';import { buildFilterWhere } from '../chart/src/table-filter-where';import type { IServiceProfile } from '../profile/profile.service';import type { IChartEventFilter } from '../report/report.constants';@@ -448,11 +449,6 @@ export interface QuerySessionsInput {limit?: number;}-/** `clix.datetime`: any date input to a UTC `YYYY-MM-DD HH:mm:ss`. */-function toClixDatetime(date: string): string {- return new Date(date).toISOString().slice(0, 19).replace('T', ' ');-}-export async function querySessionsCore(deps: ServiceDeps,input: QuerySessionsInput@@ -462,17 +458,27 @@ export async function querySessionsCore(input.endDate);+ // MCP sends a bare `YYYY-MM-DD`. The local `clix.datetime` helper this+ // replaces flattened that to midnight before the query builder could widen+ // it, so the whole last day was dropped, and it read an explicit datetime in+ // the server's local zone on the way through.+ const from = toRangeBoundaryLiteral(startDate, 'start');+ const to = toRangeBoundaryLiteral(endDate, 'end');+return chQuery<IClickhouseSession>(deps,querySessionsQuery({...input,- startDate: toClixDatetime(startDate),- endDate: toClixDatetime(endDate),+ startDate: from,+ endDate: to,limit: input.limit ?? QUERY_SESSIONS_DEFAULT_LIMIT,filterClauses: await compileSessionFilters(input.filters,input.projectId,- { startDate: new Date(startDate), endDate: new Date(endDate) }+ {+ startDate: convertClickhouseDateToJs(from),+ endDate: convertClickhouseDateToJs(to),+ }),}),CLIX_SESSION_TIMEZONEdiff --git a/packages/core/src/modules/session/src/sql.test.ts b/packages/core/src/modules/session/src/sql.test.tsindex 4894476d6..56b89c161 100644--- a/packages/core/src/modules/session/src/sql.test.ts+++ b/packages/core/src/modules/session/src/sql.test.ts@@ -217,7 +217,7 @@ describe('querySessionsQuery', () => {}).toStatement();expect(collapse(query)).toBe(- 'SELECT * FROM sessions WHERE project_id = {p1:String} AND sign = 1 AND profile_id = {p2:String} AND country = {p3:String} AND browser = {p4:String} AND created_at BETWEEN {p5:String} AND {p6:String} LIMIT {p7:UInt64}'+ 'SELECT * FROM sessions WHERE project_id = {p1:String} AND sign = 1 AND profile_id = {p2:String} AND country = {p3:String} AND browser = {p4:String} AND created_at BETWEEN {p5:String} AND {p6:String} ORDER BY created_at DESC LIMIT {p7:UInt64}');expect(query_params).toEqual({p1: PROJECT_ID,@@ -229,6 +229,40 @@ describe('querySessionsQuery', () => {p7: 20,});});++ // `query_sessions` labels its rows `created_at desc`, so the cut has to+ // happen after the sort rather than wherever the scan starts. Without this+ // the seeded August window returned the five OLDEST sessions (ISSUES.md H8b).+ test('takes the newest sessions, not an arbitrary slice', () => {+ const { query } = querySessionsQuery({+ projectId: PROJECT_ID,+ startDate: '2026-07-01 00:00:00',+ endDate: '2026-07-31 00:00:00',+ limit: 20,+ }).toStatement();++ expect(query.indexOf('ORDER BY created_at DESC')).toBeGreaterThan(-1);+ expect(query.indexOf('ORDER BY')).toBeLessThan(query.indexOf('LIMIT'));+ });++ // `query_sessions` is reached from MCP with bare `YYYY-MM-DD`, which bound+ // straight through as midnight and dropped the whole last day — 7,245+ // sessions on the seeded 31 Aug (ISSUES.md H8a, missed in 60d96d8d).+ test('widens a bare end date to the end of that day', () => {+ const { query_params } = querySessionsQuery({+ projectId: PROJECT_ID,+ startDate: '2026-08-01',+ endDate: '2026-08-31',+ limit: 20,+ }).toStatement();++ const bounds = Object.values(query_params).filter(+ (value): value is string =>+ typeof value === 'string' && value.startsWith('2026-08-')+ );+ expect(bounds).toContain('2026-08-01 00:00:00');+ expect(bounds).toContain('2026-08-31 23:59:59');+ });});describe('sessionEventsQuery', () => {diff --git a/packages/core/src/modules/session/src/sql.ts b/packages/core/src/modules/session/src/sql.tsindex a3055d97b..14a549593 100644--- a/packages/core/src/modules/session/src/sql.ts+++ b/packages/core/src/modules/session/src/sql.ts@@ -16,6 +16,7 @@// query is not the place to change its cluster semantics.import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';+import { toRangeBoundaryLiteral } from '../../../shared/ch-dates';import { formatClickhouseDate } from './dates';import {type CompiledFilterClauses,@@ -296,6 +297,11 @@ export interface QuerySessionsQueryfilterClauses?: CompiledFilterClauses;}+/**+ * Without an explicit order ClickHouse returns whatever it reads first, so a+ * bare LIMIT hands back the oldest sessions in the window while the MCP tool+ * labels them `created_at desc`. The events twin took the same fix in #476.+ */export function querySessionsQuery(query: QuerySessionsQuery): SqlFragment {const equalities = QUERY_SESSIONS_EQUALITY_COLUMNS.filter(([key]) => query[key]@@ -310,8 +316,9 @@ export function querySessionsQuery(query: QuerySessionsQuery): SqlFragment {WHERE project_id = ${sql.string(query.projectId)}AND sign = 1${sql.join(equalities, ' ')}- AND created_at BETWEEN ${sql.string(query.startDate)} AND ${sql.string(query.endDate)}+ AND created_at BETWEEN ${sql.string(toRangeBoundaryLiteral(query.startDate, 'start'))} AND ${sql.string(toRangeBoundaryLiteral(query.endDate, 'end'))}${spliceCompiledFilters(query.filterClauses ?? {})}+ ORDER BY created_at DESCLIMIT ${sql.uint64(query.limit)}`;}diff --git a/packages/core/test/midnight-window.test.ts b/packages/core/test/midnight-window.test.tsindex b11d33883..7810c471a 100644--- a/packages/core/test/midnight-window.test.ts+++ b/packages/core/test/midnight-window.test.ts@@ -15,7 +15,11 @@ const MIDNIGHT_FLAKE_SUITES = ['src/modules/chart/chart.service.test.ts','src/modules/mcp/src/integration/tools.test.ts',];-const MIDNIGHT_FLAKE_SUITE_TEST_COUNT = 54;+// A floor, not an exact count: this asserted `54 pass` and went red the moment+// someone added a test to either child suite, which says nothing about the+// midnight window. The floor still proves both suites actually ran.+const MIDNIGHT_FLAKE_SUITE_MIN_TESTS = 54;+const PASS_COUNT = /(\d+) pass/;// 00:01 is inside the chart pair's window, 00:10 and 00:19 inside charlie's.// Only the TIME of day is the subject here; the date must track the calendar.// `inactiveDays` and the last-seen buckets compare against ClickHouse's own@@ -66,7 +70,9 @@ describe('mcp/chart fixture suites inside the midnight window', () => {() => {const { exitCode, output } = runSuitesAt(wallClockIso);expect(output).toContain(`${WALL_CLOCK_PINNED_MARKER} ${wallClockIso}`);- expect(output).toContain(` ${MIDNIGHT_FLAKE_SUITE_TEST_COUNT} pass`);+ expect(+ Number(PASS_COUNT.exec(output)?.[1] ?? 0)+ ).toBeGreaterThanOrEqual(MIDNIGHT_FLAKE_SUITE_MIN_TESTS);expect(output).toContain(' 0 fail');expect(exitCode).toBe(0);},