diff --git a/apps/sim/lib/sim-search/live/activity-page.ts b/apps/sim/lib/sim-search/live/activity-page.ts index 6c5f23d82aa..0b676486171 100644 --- a/apps/sim/lib/sim-search/live/activity-page.ts +++ b/apps/sim/lib/sim-search/live/activity-page.ts @@ -3,6 +3,8 @@ import { hmacSha256Hex } from '@sim/security/hmac' import { canonicalJson } from '@sim/utils/object' import { compareStrings } from '@sim/utils/string' import { z } from 'zod' +import { fingerprint } from '@/lib/api/cursor-binding' +import type { NativeActivityEvent } from '@/lib/sim-search/live/types' /** People named on one activity entry, besides the person whose activity it is. */ const MAX_ACTIVITY_COLLABORATORS = 10 @@ -22,6 +24,20 @@ export function collaboratorNames(names: readonly string[]): string[] { ) } +/** + * The seen-key of an entry: short and opaque, since a cursor carries it. Providers compute it too, + * to pass over the entries at a bound an earlier page returned before spending work on them. + */ +export function activityEntryKey(event: NativeActivityEvent): string { + return fingerprint( + JSON.stringify([ + event.action, + event.document.container, + event.document.dedupeKey ?? event.document.id, + ]) + ).slice(0, 16) +} + /** The earliest of the valid instants, as ISO, or undefined when none parses. */ export function oldestInstant(values: readonly (string | undefined)[]): string | undefined { let oldest: number | undefined diff --git a/apps/sim/lib/sim-search/live/activity-providers.test.ts b/apps/sim/lib/sim-search/live/activity-providers.test.ts index 6c5eab5895b..6c1a476545f 100644 --- a/apps/sim/lib/sim-search/live/activity-providers.test.ts +++ b/apps/sim/lib/sim-search/live/activity-providers.test.ts @@ -2,6 +2,11 @@ * @vitest-environment node */ import { describe, expect, it, vi } from 'vitest' +import { + type ActivityBound, + activityEntryKey, + mergeActivityPage, +} from '@/lib/sim-search/live/activity-page' import { atlassianActivity } from '@/lib/sim-search/live/atlassian' import { githubActivity } from '@/lib/sim-search/live/github' import { gitLabActivity, gitLabMemberActivity } from '@/lib/sim-search/live/gitlab-activity' @@ -689,7 +694,7 @@ describe('GitLab activity', () => { ).toEqual([ ['merge_requests', '3', 'created', 'https://git.example.com/team/p42/-/merge_requests/3'], ['merge_requests', '3', 'commented', 'https://git.example.com/team/p42/-/merge_requests/3'], - ['merge_requests', '3', 'involved', 'https://git.example.com/team/p42/-/merge_requests/3'], + ['merge_requests', '3', 'edited', 'https://git.example.com/team/p42/-/merge_requests/3'], [ 'commits', 'a'.repeat(40), @@ -701,11 +706,115 @@ describe('GitLab activity', () => { expect(stream?.more).toBe(false) }) - it('reads past events newer than the bound and reports where it stopped when it reaches none', async () => { - const newer = Array.from({ length: 20 }, (_, index) => + /** + * A GitLab events listing as the API serves it: newest first, `after` and `before` whole days + * (exclusive), `per_page` rows of page `page`. + */ + const eventsApi = (rows: Record[]) => { + const requests: string[] = [] + const api = client((path, options) => { + requests.push(path) + if (path === '/api/v4/user') return { id: 7 } + const project = /^\/api\/v4\/projects\/(\d+)$/.exec(path)?.[1] + if (project) return { web_url: `https://git.example.com/team/p${project}` } + if (path !== '/api/v4/users/7/events') return undefined + const query = options?.query ?? {} + const after = Date.parse(`${query.after}T00:00:00Z`) + 86_400_000 + const before = Date.parse(`${query.before}T00:00:00Z`) + const size = Number(query.per_page) + return rows + .filter((row) => { + const time = Date.parse(String(row.created_at)) + return time >= after && time < before + }) + .slice((Number(query.page) - 1) * size, Number(query.page) * size) + }) + return { api, requests } + } + + /** Follows the listing's continuation for one GitLab account, as `list_my_activity` does. */ + const pageAll = async (api: NativeClient, limit: number, topK: number, maxPages = 30) => { + let bound: ActivityBound | undefined = { end: WINDOW.end, seen: [] } + const returned: string[] = [] + const stopped: string[] = [] + for (let page = 0; bound && page < maxPages; page++) { + const current: ActivityBound = bound + const read = await gitLabMemberActivity(api, { + ...WINDOW, + end: current.end, + seen: current.seen, + limit, + }) + const result = mergeActivityPage( + [ + { + accountId: 'gitlab', + bound: current, + read: true, + streams: read.streams.map((stream) => ({ + more: stream.more, + scannedTo: stream.scannedTo, + entries: stream.events.map((entry) => ({ + at: entry.at, + key: activityEntryKey(entry), + id: `${entry.document.container}:${entry.document.id}`, + })), + })), + }, + ], + { start: WINDOW.start }, + topK + ) + returned.push(...result.entries.map((entry) => entry.id)) + stopped.push(...result.stopped.map(({ reason }) => reason)) + bound = result.next?.gitlab + } + return { returned, stopped } + } + + it('pages through a busy day to the end, returning every event exactly once', async () => { + /** More events on one day than a GitLab page holds, two to a second so pages split an instant. */ + const rows = Array.from({ length: 150 }, (_, index) => + event( + 1000 - index, + new Date(Date.parse('2026-11-05T20:00:00Z') - Math.floor(index / 2) * 1000).toISOString(), + 42, + { + action_name: 'opened', + target_type: 'Issue', + target_iid: index + 1, + } + ) + ) + const { api, requests } = eventsApi(rows) + const { returned, stopped } = await pageAll(api, 15, 10, 40) + expect(stopped).toEqual([]) + expect(returned).toHaveLength(150) + expect(new Set(returned)).toEqual(new Set(rows.map((_, index) => `42:${index + 1}`))) + expect(requests.filter((path) => path === '/api/v4/projects/42').length).toBeLessThanOrEqual( + requests.filter((path) => path === '/api/v4/user').length + ) + }) + + it('passes over events at the bound an earlier page returned before looking up their projects', async () => { + /** Six events at one instant in six projects: one more project than a call looks up. */ + const rows = [42, 43, 44, 45, 46, 47].map((project, index) => + event(100 - index, '2026-11-05T20:00:00Z', project, { + action_name: 'opened', + target_type: 'Issue', + target_iid: index + 1, + }) + ) + const { returned, stopped } = await pageAll(eventsApi(rows).api, 5, 5) + expect(stopped).toEqual([]) + expect(returned).toHaveLength(6) + }) + + it('reports where it stopped past the bound when every page it may read is newer', async () => { + const rows = Array.from({ length: 900 }, (_, index) => event( - 100 - index, - `2026-11-08T0${Math.floor(index / 10)}:00:${String(index % 10).padStart(2, '0')}Z`, + 5000 - index, + new Date(Date.parse('2026-11-07T23:00:00Z') - index * 1000).toISOString(), 42, { action_name: 'updated', @@ -714,18 +823,12 @@ describe('GitLab activity', () => { } ) ) - const api = gitlab([newer.slice(0, 15), newer.slice(15, 20)]) - const [stream] = ( - await gitLabMemberActivity(api, { ...WINDOW, end: '2026-11-07T23:59:59.000Z', limit: 15 }) - ).streams + const { api } = eventsApi(rows) + const end = '2026-11-07T00:00:00.000Z' + const [stream] = (await gitLabMemberActivity(api, { ...WINDOW, end, limit: 15 })).streams expect(stream?.events).toEqual([]) - expect(stream?.more).toBe(false) - const full = gitlab([newer.slice(0, 15), newer.slice(0, 15), newer.slice(0, 15)]) - const [capped] = ( - await gitLabMemberActivity(full, { ...WINDOW, end: '2026-11-07T23:59:59.000Z', limit: 15 }) - ).streams - expect(capped?.more).toBe(true) - expect(Date.parse(capped?.scannedTo ?? '')).toBeGreaterThan(Date.parse('2026-11-07T23:59:59Z')) + expect(stream?.more).toBe(true) + expect(Date.parse(stream?.scannedTo ?? '')).toBeGreaterThan(Date.parse(end)) }) it('stops at an event whose project it cannot look up yet, so the next page resumes there', async () => { diff --git a/apps/sim/lib/sim-search/live/activity.ts b/apps/sim/lib/sim-search/live/activity.ts index a6eb8fed033..18f6987c183 100644 --- a/apps/sim/lib/sim-search/live/activity.ts +++ b/apps/sim/lib/sim-search/live/activity.ts @@ -31,6 +31,7 @@ import { type ActivityBound, type ActivityEntry, type ActivityStopReason, + activityEntryKey, mergeActivityPage, readActivityCursor, writeActivityCursor, @@ -142,17 +143,6 @@ interface Entry extends ActivityEntry { documentId: string } -/** The seen-key of an entry: short and opaque, since a cursor carries it. */ -function entryKey(event: NativeActivityEvent): string { - return fingerprint( - JSON.stringify([ - event.action, - event.document.container, - event.document.dedupeKey ?? event.document.id, - ]) - ).slice(0, 16) -} - /** One account's page: what it read for the merge, or why it could not be read. */ type AccountRead = AccountActivity & ({ read: true; partial: boolean; message?: string } | { read: false; error: NativeSearchError }) @@ -345,6 +335,7 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ const page = await session.activity({ start: window.start, end: bound.end, + seen: bound.seen, windowEnd: window.end, limit: streamItems, scopes: account.scopes, @@ -373,7 +364,9 @@ export const listMyActivity = defineAuthorizedKnowledgeUseCase({ scannedTo: stream.scannedTo, entries: stream.events.flatMap((event): Entry[] => { const documentId = documentIds.get(event) - return documentId ? [{ at: event.at, key: entryKey(event), event, documentId }] : [] + return documentId + ? [{ at: event.at, key: activityEntryKey(event), event, documentId }] + : [] }), })), } diff --git a/apps/sim/lib/sim-search/live/gitlab-activity.ts b/apps/sim/lib/sim-search/live/gitlab-activity.ts index d14f04aee83..4d19f24a501 100644 --- a/apps/sim/lib/sim-search/live/gitlab-activity.ts +++ b/apps/sim/lib/sim-search/live/gitlab-activity.ts @@ -1,4 +1,4 @@ -import { oldestInstant } from '@/lib/sim-search/live/activity-page' +import { activityEntryKey } from '@/lib/sim-search/live/activity-page' import { gitLabDocumentUrl } from '@/lib/sim-search/live/gitlab' import { array, NativeSearchError, object, string } from '@/lib/sim-search/live/http' import type { @@ -8,10 +8,13 @@ import type { NativeClient, } from '@/lib/sim-search/live/types' -/** Event pages one call reads to reach the window, bounding a person with heavy recent activity. */ -const GITLAB_EVENT_PAGES = 3 -/** Events per page; each surviving event costs its verification a request, within the budget. */ -const GITLAB_EVENT_PAGE_SIZE = 15 +/** + * Event pages one call reads at most, including pages of events newer than the bound: GitLab's + * `before` is a whole day, so a continuation re-lists the newer events of its bound's day. + */ +const GITLAB_EVENT_MAX_REQUESTS = 8 +/** GitLab's largest page, so a busy day's newer events are passed in few requests. */ +const GITLAB_EVENT_PAGE_SIZE = 100 /** Projects a member account looks up per call to link its events; later events wait a page. */ const GITLAB_ACTIVITY_PROJECT_LOOKUPS = 5 @@ -27,7 +30,7 @@ const GITLAB_ACTIONS: Record = { updated: 'edited', merged: 'edited', accepted: 'edited', - approved: 'involved', + approved: 'edited', 'commented on': 'commented', } @@ -105,10 +108,12 @@ function activityEvent(row: Record): NativeActivityEvent | null /** * The person's own GitLab contributions, newest first by when they acted: one stream read from - * GitLab's events, at most a few pages a call. Events newer than the bound are read past; a call - * that reads only those reports where it stopped, past the bound, so the listing stops this - * account instead of reading the same events again. A call that stops at an event whose project - * it cannot look up yet reports that event's instant, so the next page reads it again. + * GitLab's events. A call returns at most `limit` events and stops at the first event it does not + * return, reporting that event's instant, so the next page reads it again; events at that instant + * an earlier page returned (`seen`) are passed over before any lookup. Events newer than the bound + * are read past without counting, up to {@link GITLAB_EVENT_MAX_REQUESTS} pages; a call that reads + * only those reports where it stopped, past the bound, so the listing stops this account instead + * of reading the same events again. */ export async function gitLabActivity( client: NativeClient, @@ -117,55 +122,44 @@ export async function gitLabActivity( ): Promise { const start = Date.parse(input.start) const end = Date.parse(input.end) - const pageSize = Math.min(GITLAB_EVENT_PAGE_SIZE, Math.max(1, input.limit)) + const limit = Math.max(1, input.limit) + const seen = new Set(input.seen) const events: NativeActivityEvent[] = [] - const read: string[] = [] - let more = false - let reachedBound = false - let stoppedAt: string | undefined - for (let page = 1; page <= GITLAB_EVENT_PAGES && !reachedBound; page++) { + let oldest: string | undefined + for (let page = 1; page <= GITLAB_EVENT_MAX_REQUESTS; page++) { const response = await client.json(source.path, { query: { after: day(start - DAY_MS), before: day(end + DAY_MS), sort: 'desc', - per_page: String(pageSize), + per_page: String(GITLAB_EVENT_PAGE_SIZE), page: String(page), }, signal: input.signal, }) - if (!Array.isArray(response) || response.length > pageSize) + if (!Array.isArray(response) || response.length > GITLAB_EVENT_PAGE_SIZE) throw new NativeSearchError('unavailable', 'GitLab returned an invalid event listing.') const rows = array(response) - more = rows.length === pageSize for (const row of rows) { const at = Date.parse(string(row.created_at)) if (!Number.isFinite(at)) continue - read.push(string(row.created_at)) + oldest = new Date(at).toISOString() if (at > end) continue - reachedBound = true - if (at < start) { - more = false - break - } + if (at < start) return { streams: [{ events, more: false }] } const event = activityEvent(row) if (!event || (source.kinds && !source.kinds.has(event.document.kind ?? ''))) continue + if (at === end && seen.has(activityEntryKey(event))) continue + if (events.length >= limit) return { streams: [{ events, more: true, scannedTo: event.at }] } const projectUrl = await source.projectUrl(event.document.container ?? '') - if (projectUrl === null) { - stoppedAt = event.at - break - } + if (projectUrl === null) return { streams: [{ events, more: true, scannedTo: event.at }] } if (!projectUrl) continue event.document.url = gitLabDocumentUrl(projectUrl, event.document.kind, event.document.id) events.push(event) } - if (stoppedAt) return { streams: [{ events, more: true, scannedTo: stoppedAt }] } - if (!more) break - } - const scannedTo = oldestInstant(read) - return { - streams: [{ events, more: more && Boolean(scannedTo), ...(scannedTo ? { scannedTo } : {}) }], + if (rows.length < GITLAB_EVENT_PAGE_SIZE) return { streams: [{ events, more: false }] } } + /** The request ceiling ended the read: what remains sorts at or before the oldest event read. */ + return { streams: [{ events, more: Boolean(oldest), ...(oldest ? { scannedTo: oldest } : {}) }] } } /** diff --git a/apps/sim/lib/sim-search/live/types.ts b/apps/sim/lib/sim-search/live/types.ts index 8c7e43fda1b..ff247794f6a 100644 --- a/apps/sim/lib/sim-search/live/types.ts +++ b/apps/sim/lib/sim-search/live/types.ts @@ -195,6 +195,11 @@ export interface NativeActivityInput { * is earlier never picks an older moment of the same item. */ windowEnd: string + /** + * Keys (`activityEntryKey`) of the entries at exactly `end` that an earlier page returned; + * the merge drops them, so a provider may pass over them before doing work for them. + */ + seen?: readonly string[] /** Raw provider items one stream reads per call. */ limit: number scopes: readonly string[]