ai-experiments 2.1.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +13 -1
  3. package/package.json +7 -7
  4. package/src/clickhouse-storage.ts +698 -0
  5. package/src/decide.ts +8 -10
  6. package/src/experiment.ts +12 -12
  7. package/src/index.ts +13 -3
  8. package/src/tracking.ts +3 -3
  9. package/test/cartesian.test.ts +287 -0
  10. package/test/clickhouse-storage.test.ts +470 -0
  11. package/test/decide.test.ts +414 -0
  12. package/test/experiment.test.ts +473 -0
  13. package/test/tracking.test.ts +347 -0
  14. package/vitest.config.ts +34 -0
  15. package/.turbo/turbo-build.log +0 -5
  16. package/dist/cartesian.d.ts +0 -140
  17. package/dist/cartesian.d.ts.map +0 -1
  18. package/dist/cartesian.js +0 -216
  19. package/dist/cartesian.js.map +0 -1
  20. package/dist/decide.d.ts +0 -152
  21. package/dist/decide.d.ts.map +0 -1
  22. package/dist/decide.js +0 -329
  23. package/dist/decide.js.map +0 -1
  24. package/dist/experiment.d.ts +0 -53
  25. package/dist/experiment.d.ts.map +0 -1
  26. package/dist/experiment.js +0 -292
  27. package/dist/experiment.js.map +0 -1
  28. package/dist/index.d.ts +0 -14
  29. package/dist/index.d.ts.map +0 -1
  30. package/dist/index.js +0 -19
  31. package/dist/index.js.map +0 -1
  32. package/dist/tracking.d.ts +0 -159
  33. package/dist/tracking.d.ts.map +0 -1
  34. package/dist/tracking.js +0 -310
  35. package/dist/tracking.js.map +0 -1
  36. package/dist/types.d.ts +0 -198
  37. package/dist/types.d.ts.map +0 -1
  38. package/dist/types.js +0 -5
  39. package/dist/types.js.map +0 -1
  40. package/src/cartesian.js +0 -215
  41. package/src/chdb-storage.js +0 -464
  42. package/src/chdb-storage.ts +0 -565
  43. package/src/decide.js +0 -328
  44. package/src/experiment.js +0 -291
  45. package/src/index.js +0 -20
  46. package/src/tracking.js +0 -309
  47. package/src/types.js +0 -4
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Tests for tracking utilities
3
+ *
4
+ * These tests verify the event tracking functionality including:
5
+ * - Track function basics
6
+ * - Configuration options
7
+ * - Backend implementations
8
+ * - Memory backend
9
+ * - Batch backend
10
+ */
11
+
12
+ import { describe, it, expect, beforeEach, vi } from 'vitest'
13
+ import {
14
+ track,
15
+ flush,
16
+ configureTracking,
17
+ getTrackingConfig,
18
+ createConsoleBackend,
19
+ createMemoryBackend,
20
+ createBatchBackend,
21
+ } from '../src/index.js'
22
+
23
+ describe('tracking configuration', () => {
24
+ beforeEach(() => {
25
+ // Reset to default state
26
+ configureTracking({
27
+ backend: createMemoryBackend(),
28
+ enabled: true,
29
+ metadata: {},
30
+ })
31
+ })
32
+
33
+ it('configures tracking with custom backend', () => {
34
+ const customBackend = createMemoryBackend()
35
+ configureTracking({ backend: customBackend })
36
+
37
+ const config = getTrackingConfig()
38
+ expect(config.backend).toBe(customBackend)
39
+ })
40
+
41
+ it('configures tracking enabled state', () => {
42
+ configureTracking({ enabled: false })
43
+ expect(getTrackingConfig().enabled).toBe(false)
44
+
45
+ configureTracking({ enabled: true })
46
+ expect(getTrackingConfig().enabled).toBe(true)
47
+ })
48
+
49
+ it('configures global metadata', () => {
50
+ configureTracking({ metadata: { project: 'test', env: 'development' } })
51
+
52
+ const config = getTrackingConfig()
53
+ expect(config.metadata).toEqual({ project: 'test', env: 'development' })
54
+ })
55
+
56
+ it('preserves existing config when partial update', () => {
57
+ const backend = createMemoryBackend()
58
+ configureTracking({ backend, enabled: true, metadata: { key: 'value' } })
59
+
60
+ // Update only enabled
61
+ configureTracking({ enabled: false })
62
+
63
+ const config = getTrackingConfig()
64
+ expect(config.backend).toBe(backend)
65
+ expect(config.enabled).toBe(false)
66
+ expect(config.metadata).toEqual({ key: 'value' })
67
+ })
68
+ })
69
+
70
+ describe('track function', () => {
71
+ let backend: ReturnType<typeof createMemoryBackend>
72
+
73
+ beforeEach(() => {
74
+ backend = createMemoryBackend()
75
+ configureTracking({ backend, enabled: true, metadata: {} })
76
+ })
77
+
78
+ it('tracks events to backend', () => {
79
+ track({
80
+ type: 'experiment.start',
81
+ timestamp: new Date(),
82
+ data: { experimentId: 'test-exp' },
83
+ })
84
+
85
+ const events = backend.getEvents()
86
+ expect(events).toHaveLength(1)
87
+ expect(events[0].type).toBe('experiment.start')
88
+ expect(events[0].data.experimentId).toBe('test-exp')
89
+ })
90
+
91
+ it('does not track when disabled', () => {
92
+ configureTracking({ enabled: false })
93
+
94
+ track({
95
+ type: 'experiment.start',
96
+ timestamp: new Date(),
97
+ data: {},
98
+ })
99
+
100
+ const events = backend.getEvents()
101
+ expect(events).toHaveLength(0)
102
+ })
103
+
104
+ it('merges global metadata with event data', () => {
105
+ configureTracking({
106
+ backend,
107
+ metadata: { projectId: 'proj-123', env: 'test' },
108
+ })
109
+
110
+ track({
111
+ type: 'variant.start',
112
+ timestamp: new Date(),
113
+ data: { variantId: 'v1' },
114
+ })
115
+
116
+ const events = backend.getEvents()
117
+ expect(events[0].data.variantId).toBe('v1')
118
+ expect(events[0].data.projectId).toBe('proj-123')
119
+ expect(events[0].data.env).toBe('test')
120
+ })
121
+
122
+ it('tracks all event types', () => {
123
+ const eventTypes = [
124
+ 'experiment.start',
125
+ 'experiment.complete',
126
+ 'variant.start',
127
+ 'variant.complete',
128
+ 'variant.error',
129
+ 'metric.computed',
130
+ 'decision.made',
131
+ ] as const
132
+
133
+ for (const type of eventTypes) {
134
+ track({
135
+ type,
136
+ timestamp: new Date(),
137
+ data: { type },
138
+ })
139
+ }
140
+
141
+ const events = backend.getEvents()
142
+ expect(events).toHaveLength(eventTypes.length)
143
+ })
144
+ })
145
+
146
+ describe('flush function', () => {
147
+ it('calls backend flush when available', async () => {
148
+ const flushMock = vi.fn().mockResolvedValue(undefined)
149
+ const customBackend = {
150
+ track: vi.fn(),
151
+ flush: flushMock,
152
+ }
153
+
154
+ configureTracking({ backend: customBackend })
155
+
156
+ await flush()
157
+
158
+ expect(flushMock).toHaveBeenCalled()
159
+ })
160
+
161
+ it('handles backend without flush method', async () => {
162
+ const customBackend = {
163
+ track: vi.fn(),
164
+ // No flush method
165
+ }
166
+
167
+ configureTracking({ backend: customBackend })
168
+
169
+ // Should not throw
170
+ await expect(flush()).resolves.not.toThrow()
171
+ })
172
+ })
173
+
174
+ describe('createConsoleBackend', () => {
175
+ it('creates a tracking backend', () => {
176
+ const backend = createConsoleBackend()
177
+ expect(backend).toHaveProperty('track')
178
+ expect(typeof backend.track).toBe('function')
179
+ })
180
+
181
+ it('accepts verbose option', () => {
182
+ const verboseBackend = createConsoleBackend({ verbose: true })
183
+ expect(verboseBackend).toHaveProperty('track')
184
+ })
185
+
186
+ it('logs events without throwing', () => {
187
+ const backend = createConsoleBackend()
188
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
189
+
190
+ backend.track({
191
+ type: 'experiment.start',
192
+ timestamp: new Date(),
193
+ data: { experimentId: 'test' },
194
+ })
195
+
196
+ expect(consoleSpy).toHaveBeenCalled()
197
+ consoleSpy.mockRestore()
198
+ })
199
+ })
200
+
201
+ describe('createMemoryBackend', () => {
202
+ it('creates backend with getEvents and clear methods', () => {
203
+ const backend = createMemoryBackend()
204
+
205
+ expect(backend).toHaveProperty('track')
206
+ expect(backend).toHaveProperty('getEvents')
207
+ expect(backend).toHaveProperty('clear')
208
+ })
209
+
210
+ it('stores tracked events', () => {
211
+ const backend = createMemoryBackend()
212
+
213
+ backend.track({
214
+ type: 'experiment.start',
215
+ timestamp: new Date(),
216
+ data: { id: 1 },
217
+ })
218
+
219
+ backend.track({
220
+ type: 'experiment.complete',
221
+ timestamp: new Date(),
222
+ data: { id: 2 },
223
+ })
224
+
225
+ const events = backend.getEvents()
226
+ expect(events).toHaveLength(2)
227
+ expect(events[0].data.id).toBe(1)
228
+ expect(events[1].data.id).toBe(2)
229
+ })
230
+
231
+ it('clears all events', () => {
232
+ const backend = createMemoryBackend()
233
+
234
+ backend.track({
235
+ type: 'experiment.start',
236
+ timestamp: new Date(),
237
+ data: {},
238
+ })
239
+
240
+ expect(backend.getEvents()).toHaveLength(1)
241
+
242
+ backend.clear()
243
+
244
+ expect(backend.getEvents()).toHaveLength(0)
245
+ })
246
+
247
+ it('returns copy of events array', () => {
248
+ const backend = createMemoryBackend()
249
+
250
+ backend.track({
251
+ type: 'experiment.start',
252
+ timestamp: new Date(),
253
+ data: {},
254
+ })
255
+
256
+ const events1 = backend.getEvents()
257
+ const events2 = backend.getEvents()
258
+
259
+ // Should be equal but not same reference
260
+ expect(events1).toEqual(events2)
261
+ expect(events1).not.toBe(events2)
262
+ })
263
+ })
264
+
265
+ describe('createBatchBackend', () => {
266
+ it('creates backend with track and flush methods', () => {
267
+ const backend = createBatchBackend({
268
+ batchSize: 10,
269
+ send: async () => {},
270
+ })
271
+
272
+ expect(backend).toHaveProperty('track')
273
+ expect(backend).toHaveProperty('flush')
274
+ })
275
+
276
+ it('batches events until batchSize reached', async () => {
277
+ const sendMock = vi.fn().mockResolvedValue(undefined)
278
+ const backend = createBatchBackend({
279
+ batchSize: 3,
280
+ send: sendMock,
281
+ })
282
+
283
+ // Track 2 events - should not trigger send yet
284
+ backend.track({ type: 'experiment.start', timestamp: new Date(), data: {} })
285
+ backend.track({ type: 'experiment.start', timestamp: new Date(), data: {} })
286
+
287
+ expect(sendMock).not.toHaveBeenCalled()
288
+
289
+ // Track 3rd event - should trigger batch send
290
+ backend.track({ type: 'experiment.start', timestamp: new Date(), data: {} })
291
+
292
+ // Allow async processing
293
+ await new Promise((r) => setTimeout(r, 10))
294
+
295
+ expect(sendMock).toHaveBeenCalled()
296
+ expect(sendMock.mock.calls[0][0]).toHaveLength(3)
297
+ })
298
+
299
+ it('flushes remaining events on flush call', async () => {
300
+ const sendMock = vi.fn().mockResolvedValue(undefined)
301
+ const backend = createBatchBackend({
302
+ batchSize: 10,
303
+ send: sendMock,
304
+ })
305
+
306
+ backend.track({ type: 'experiment.start', timestamp: new Date(), data: {} })
307
+ backend.track({ type: 'experiment.start', timestamp: new Date(), data: {} })
308
+
309
+ expect(sendMock).not.toHaveBeenCalled()
310
+
311
+ await backend.flush!()
312
+
313
+ expect(sendMock).toHaveBeenCalledTimes(1)
314
+ expect(sendMock.mock.calls[0][0]).toHaveLength(2)
315
+ })
316
+
317
+ it('does not send on flush when batch is empty', async () => {
318
+ const sendMock = vi.fn().mockResolvedValue(undefined)
319
+ const backend = createBatchBackend({
320
+ batchSize: 10,
321
+ send: sendMock,
322
+ })
323
+
324
+ await backend.flush!()
325
+
326
+ expect(sendMock).not.toHaveBeenCalled()
327
+ })
328
+
329
+ it('supports flush interval', async () => {
330
+ const sendMock = vi.fn().mockResolvedValue(undefined)
331
+ const backend = createBatchBackend({
332
+ batchSize: 100,
333
+ flushInterval: 50,
334
+ send: sendMock,
335
+ })
336
+
337
+ backend.track({ type: 'experiment.start', timestamp: new Date(), data: {} })
338
+
339
+ // Wait for flush interval
340
+ await new Promise((r) => setTimeout(r, 100))
341
+
342
+ expect(sendMock).toHaveBeenCalled()
343
+
344
+ // Clean up timer
345
+ await backend.flush!()
346
+ })
347
+ })
@@ -0,0 +1,34 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ // CRITICAL: Limit concurrency to prevent resource exhaustion
6
+ maxConcurrency: 1,
7
+ maxWorkers: 1,
8
+ minWorkers: 1,
9
+ fileParallelism: false,
10
+
11
+ globals: false,
12
+ environment: 'node',
13
+ include: ['test/**/*.test.ts'],
14
+ exclude: ['node_modules/**', 'dist/**'],
15
+ testTimeout: 30000,
16
+ hookTimeout: 10000,
17
+
18
+ // Run tests sequentially
19
+ pool: 'forks',
20
+ poolOptions: {
21
+ forks: {
22
+ singleFork: true,
23
+ },
24
+ },
25
+
26
+ // Coverage configuration
27
+ coverage: {
28
+ provider: 'v8',
29
+ reporter: ['text', 'json', 'html'],
30
+ include: ['src/**/*.ts'],
31
+ exclude: ['**/*.test.ts', '**/__tests__/**', '**/node_modules/**'],
32
+ },
33
+ },
34
+ })
@@ -1,5 +0,0 @@
1
-
2
- 
3
- > ai-experiments@2.0.1 build /Users/nathanclevenger/projects/primitives.org.ai/packages/ai-experiments
4
- > tsc
5
-
@@ -1,140 +0,0 @@
1
- /**
2
- * Cartesian product utilities for parameter exploration
3
- */
4
- import type { CartesianParams, CartesianResult } from './types.js';
5
- /**
6
- * Generate cartesian product of parameter sets
7
- *
8
- * Takes an object where each key maps to an array of possible values,
9
- * and returns all possible combinations as an array of objects.
10
- *
11
- * @example
12
- * ```ts
13
- * import { cartesian } from 'ai-experiments'
14
- *
15
- * const combinations = cartesian({
16
- * model: ['sonnet', 'opus', 'gpt-4o'],
17
- * temperature: [0.3, 0.7, 1.0],
18
- * maxTokens: [100, 500, 1000],
19
- * })
20
- *
21
- * // Returns 27 combinations (3 * 3 * 3):
22
- * // [
23
- * // { model: 'sonnet', temperature: 0.3, maxTokens: 100 },
24
- * // { model: 'sonnet', temperature: 0.3, maxTokens: 500 },
25
- * // { model: 'sonnet', temperature: 0.3, maxTokens: 1000 },
26
- * // { model: 'sonnet', temperature: 0.7, maxTokens: 100 },
27
- * // ...
28
- * // ]
29
- *
30
- * // Use with experiments:
31
- * const variants = combinations.map((config, i) => ({
32
- * id: `variant-${i}`,
33
- * name: `${config.model} T=${config.temperature} max=${config.maxTokens}`,
34
- * config,
35
- * }))
36
- * ```
37
- */
38
- export declare function cartesian<T extends CartesianParams>(params: T): CartesianResult<T>;
39
- /**
40
- * Generate a grid of parameter combinations with filtering
41
- *
42
- * Similar to cartesian(), but allows filtering out invalid combinations.
43
- *
44
- * @example
45
- * ```ts
46
- * import { cartesianFilter } from 'ai-experiments'
47
- *
48
- * const combinations = cartesianFilter(
49
- * {
50
- * model: ['sonnet', 'opus'],
51
- * temperature: [0.3, 0.7, 1.0],
52
- * maxTokens: [100, 500],
53
- * },
54
- * // Filter out combinations where opus uses high temperature
55
- * (combo) => !(combo.model === 'opus' && combo.temperature > 0.7)
56
- * )
57
- * ```
58
- */
59
- export declare function cartesianFilter<T extends CartesianParams>(params: T, filter: (combo: {
60
- [K in keyof T]: T[K][number];
61
- }) => boolean): CartesianResult<T>;
62
- /**
63
- * Generate a random sample from the cartesian product
64
- *
65
- * Useful when the full cartesian product is too large to test all combinations.
66
- *
67
- * @example
68
- * ```ts
69
- * import { cartesianSample } from 'ai-experiments'
70
- *
71
- * // Full product would be 1000 combinations (10 * 10 * 10)
72
- * // Sample just 20 random combinations
73
- * const sample = cartesianSample(
74
- * {
75
- * param1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
76
- * param2: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
77
- * param3: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
78
- * },
79
- * 20
80
- * )
81
- * ```
82
- */
83
- export declare function cartesianSample<T extends CartesianParams>(params: T, sampleSize: number, options?: {
84
- /** Random seed for reproducibility */
85
- seed?: number;
86
- /** Whether to sample without replacement (default: true) */
87
- unique?: boolean;
88
- }): CartesianResult<T>;
89
- /**
90
- * Count the total number of combinations without generating them
91
- *
92
- * Useful for checking if cartesian product is feasible before generating.
93
- *
94
- * @example
95
- * ```ts
96
- * import { cartesianCount } from 'ai-experiments'
97
- *
98
- * const count = cartesianCount({
99
- * model: ['sonnet', 'opus', 'gpt-4o'],
100
- * temperature: [0.3, 0.5, 0.7, 0.9],
101
- * maxTokens: [100, 500, 1000, 2000],
102
- * })
103
- * // Returns 48 (3 * 4 * 4)
104
- *
105
- * if (count > 100) {
106
- * console.log('Too many combinations, use cartesianSample instead')
107
- * }
108
- * ```
109
- */
110
- export declare function cartesianCount<T extends CartesianParams>(params: T): number;
111
- /**
112
- * Generate cartesian product with labels for each dimension
113
- *
114
- * Returns combinations with additional metadata about which dimension each value came from.
115
- *
116
- * @example
117
- * ```ts
118
- * import { cartesianWithLabels } from 'ai-experiments'
119
- *
120
- * const labeled = cartesianWithLabels({
121
- * model: ['sonnet', 'opus'],
122
- * temperature: [0.3, 0.7],
123
- * })
124
- * // [
125
- * // { values: { model: 'sonnet', temperature: 0.3 }, labels: { model: 0, temperature: 0 } },
126
- * // { values: { model: 'sonnet', temperature: 0.7 }, labels: { model: 0, temperature: 1 } },
127
- * // { values: { model: 'opus', temperature: 0.3 }, labels: { model: 1, temperature: 0 } },
128
- * // { values: { model: 'opus', temperature: 0.7 }, labels: { model: 1, temperature: 1 } },
129
- * // ]
130
- * ```
131
- */
132
- export declare function cartesianWithLabels<T extends CartesianParams>(params: T): Array<{
133
- values: {
134
- [K in keyof T]: T[K][number];
135
- };
136
- labels: {
137
- [K in keyof T]: number;
138
- };
139
- }>;
140
- //# sourceMappingURL=cartesian.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cartesian.d.ts","sourceRoot":"","sources":["../src/cartesian.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,eAAe,EAAE,MAAM,EAAE,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,CA0BlF;AA4BD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,eAAe,EACvD,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,CAAC,KAAK,EAAE;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;CAAE,KAAK,OAAO,GAC3D,eAAe,CAAC,CAAC,CAAC,CAGpB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,eAAe,EACvD,MAAM,EAAE,CAAC,EACT,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE;IACP,sCAAsC;IACtC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,4DAA4D;IAC5D,MAAM,CAAC,EAAE,OAAO,CAAA;CACZ,GACL,eAAe,CAAC,CAAC,CAAC,CAqBpB;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,eAAe,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAS3E;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,eAAe,EAC3D,MAAM,EAAE,CAAC,GACR,KAAK,CAAC;IACP,MAAM,EAAE;SAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;KAAE,CAAA;IACxC,MAAM,EAAE;SAAG,CAAC,IAAI,MAAM,CAAC,GAAG,MAAM;KAAE,CAAA;CACnC,CAAC,CA0BD"}