Elffuss BraidHub

kikocis/continue public

Merge pull request #7369 from continuedev/posthog-event-batching

Batch tokens generated events
Changeset4b606125a2699ef58a12afefac12ae33ee63daf807fb1f7e7349330ea5aef708
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-08-27 22:28 -07:00
CommitterGitHub <noreply@github.com> · 2025-08-27 22:28 -07:00
Parents06370262b995, 1f4a56f3e948

Browse the files at this changeset

5 files changed

modified core/context/providers/index.ts +0 −6
@@ -1,6 +1,5 @@
11 import { BaseContextProvider } from "../";
22 import { ContextProviderName } from "../../";
3-import { Telemetry } from "../../util/posthog";
43
54 import ClipboardContextProvider from "./ClipboardContextProvider";
65 import CodebaseContextProvider from "./CodebaseContextProvider";
@@ -80,10 +79,5 @@
8079 ): typeof BaseContextProvider | undefined {
8180 const provider = Providers.find((cls) => cls.description.title === name);
8281
83- void Telemetry.capture("context_provider_load", {
84- providerName: name,
85- found: !!provider, // also capture those which user expected to be present
86- });
87-
8882 return provider;
8983 }
modified core/indexing/CodebaseIndexer.ts +0 −9
@@ -12,7 +12,6 @@
1212 import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
1313 import { Logger } from "../util/Logger.js";
1414 import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
15-import { Telemetry } from "../util/posthog.js";
1615 import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
1716
1817 import { ConfigResult } from "@continuedev/config-yaml";
@@ -667,14 +666,6 @@
667666 update.desc,
668667 update.debugInfo,
669668 );
670- void Telemetry.capture(
671- "indexing_error",
672- {
673- error: update.desc,
674- stack: update.debugInfo,
675- },
676- false,
677- );
678669 }
679670
680671 /**
modified core/llm/index.ts +6 −10
@@ -34,7 +34,7 @@
3434 import mergeJson from "../util/merge.js";
3535 import { renderChatMessage } from "../util/messageContent.js";
3636 import { isOllamaInstalled } from "../util/ollamaHelper.js";
37-import { Telemetry } from "../util/posthog.js";
37+import { TokensBatchingService } from "../util/TokensBatchingService.js";
3838 import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
3939
4040 import {
@@ -346,15 +346,11 @@
346346 let generatedTokens = this.countTokens(completion);
347347 let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
348348
349- void Telemetry.capture(
350- "tokens_generated",
351- {
352- model: model,
353- provider: this.providerName,
354- promptTokens: promptTokens,
355- generatedTokens: generatedTokens,
356- },
357- true,
349+ TokensBatchingService.getInstance().addTokens(
350+ model,
351+ this.providerName,
352+ promptTokens,
353+ generatedTokens,
358354 );
359355
360356 void DevDataSqliteDb.logTokensGenerated(
added core/util/TokensBatchingService.ts +106 −0
@@ -0,0 +1,106 @@
1+import { Telemetry } from "./posthog.js";
2+
3+interface TokenBatch {
4+ model: string;
5+ provider: string;
6+ count: number;
7+ totalPromptTokens: number;
8+ totalGeneratedTokens: number;
9+ lastEventTime: number;
10+}
11+
12+export class TokensBatchingService {
13+ private static instance: TokensBatchingService;
14+ private batches = new Map<string, TokenBatch>();
15+ private flushTimer: NodeJS.Timeout | null = null;
16+
17+ private readonly BATCH_SIZE_LIMIT = 25;
18+ private readonly FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
19+
20+ static getInstance(): TokensBatchingService {
21+ if (!TokensBatchingService.instance) {
22+ TokensBatchingService.instance = new TokensBatchingService();
23+ }
24+ return TokensBatchingService.instance;
25+ }
26+
27+ private constructor() {
28+ this.startFlushTimer();
29+ }
30+
31+ addTokens(
32+ model: string,
33+ provider: string,
34+ promptTokens: number,
35+ generatedTokens: number,
36+ ): void {
37+ const key = `${provider}:${model}`;
38+
39+ if (!this.batches.has(key)) {
40+ this.batches.set(key, {
41+ model,
42+ provider,
43+ count: 0,
44+ totalPromptTokens: 0,
45+ totalGeneratedTokens: 0,
46+ lastEventTime: Date.now(),
47+ });
48+ }
49+
50+ const batch = this.batches.get(key)!;
51+ batch.count++;
52+ batch.totalPromptTokens += promptTokens;
53+ batch.totalGeneratedTokens += generatedTokens;
54+ batch.lastEventTime = Date.now();
55+
56+ // Flush if batch is full
57+ if (batch.count >= this.BATCH_SIZE_LIMIT) {
58+ this.flushBatch(key, batch);
59+ }
60+ }
61+
62+ private flushBatch(key: string, batch: TokenBatch): void {
63+ if (batch.count === 0) return;
64+
65+ void Telemetry.capture(
66+ "tokens_generated_batch",
67+ {
68+ model: batch.model,
69+ provider: batch.provider,
70+ eventCount: batch.count,
71+ totalPromptTokens: batch.totalPromptTokens,
72+ totalGeneratedTokens: batch.totalGeneratedTokens,
73+ avgPromptTokens: Math.round(batch.totalPromptTokens / batch.count),
74+ avgGeneratedTokens: Math.round(
75+ batch.totalGeneratedTokens / batch.count,
76+ ),
77+ },
78+ true,
79+ );
80+
81+ this.batches.delete(key);
82+ }
83+
84+ private startFlushTimer(): void {
85+ this.flushTimer = setInterval(() => {
86+ this.flushAllBatches();
87+ }, this.FLUSH_INTERVAL_MS);
88+ // Allow the process to exit if this timer is the only thing keeping it alive
89+ // This prevents test hangs and allows graceful shutdown
90+ this.flushTimer.unref();
91+ }
92+
93+ private flushAllBatches(): void {
94+ for (const [key, batch] of this.batches.entries()) {
95+ this.flushBatch(key, batch);
96+ }
97+ }
98+
99+ shutdown(): void {
100+ if (this.flushTimer) {
101+ clearInterval(this.flushTimer);
102+ this.flushTimer = null;
103+ }
104+ this.flushAllBatches();
105+ }
106+}
modified core/util/posthog.ts +2 −0
@@ -5,6 +5,7 @@
55
66 import type { PostHog as PostHogType } from "posthog-node";
77 import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
8+import { TokensBatchingService } from "./TokensBatchingService.js";
89
910 export enum PosthogFeatureFlag {
1011 AutocompleteTimeout = "autocomplete-timeout",
@@ -99,6 +100,7 @@
99100 }
100101
101102 static shutdownPosthogClient() {
103+ TokensBatchingService.getInstance().shutdown();
102104 Telemetry.client?.shutdown();
103105 }
104106