bulltrackers-module 1.0.738 → 1.0.740

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.
@@ -6,10 +6,18 @@
6
6
  * * V2.3 FIX: "Insufficient History" bug.
7
7
  * - fetchBatched now orders by Entity ID to keep historical rows together.
8
8
  * - Implemented "Entity-Atomic Batching" to prevent splitting a user's history across batches.
9
+ * * V2.4 FIX: Runaway Query Cost Prevention [Fix #3].
10
+ * * V2.5 UPDATE: Super-Entity Monitoring [Safety Valve for Fix #6].
11
+ * - Warns if a single entity exceeds reasonable batch limits (Memory Risk).
9
12
  */
10
13
 
11
14
  const { BigQuery } = require('@google-cloud/bigquery');
12
15
 
16
+ // FIX #3: Hard limit to prevent cost spirals
17
+ const MAX_LOOKBACK_DAYS = 30;
18
+ // FIX #6 (Alternative): Warn if an entity is massive (e.g. > 5x batch size)
19
+ const BATCH_GROWTH_WARNING_THRESHOLD = 5;
20
+
13
21
  class DataFetcher {
14
22
  constructor(config, queryBuilder, logger = null) {
15
23
  this.projectId = config.projectId;
@@ -151,6 +159,12 @@ class DataFetcher {
151
159
 
152
160
  async fetch(options) {
153
161
  const { table, targetDate, lookback = 0, filter = {}, fields = null, entities = null } = options;
162
+
163
+ // FIX #3: Prevent Runaway Costs
164
+ if (lookback > MAX_LOOKBACK_DAYS) {
165
+ throw new Error(`[DataFetcher] COST GUARD: Lookback of ${lookback} days exceeds limit of ${MAX_LOOKBACK_DAYS}. Table: ${table}`);
166
+ }
167
+
154
168
  const tableConfig = this.tables[table] || {};
155
169
  const { dateField, entityField, dataField } = tableConfig;
156
170
 
@@ -168,6 +182,12 @@ class DataFetcher {
168
182
 
169
183
  async *fetchBatched(options, batchSize = 1000) {
170
184
  const { table, targetDate, lookback = 0, filter = {}, fields = null, entities = null } = options;
185
+
186
+ // FIX #3: Prevent Runaway Costs
187
+ if (lookback > MAX_LOOKBACK_DAYS) {
188
+ throw new Error(`[DataFetcher] COST GUARD: Lookback of ${lookback} days exceeds limit of ${MAX_LOOKBACK_DAYS}. Table: ${table}`);
189
+ }
190
+
171
191
  const tableConfig = this.tables[table] || {};
172
192
  const { dateField, entityField, dataField } = tableConfig;
173
193
 
@@ -181,6 +201,7 @@ class DataFetcher {
181
201
 
182
202
  let batch = [];
183
203
  let currentEntity = null;
204
+ let batchHasWarned = false; // Flag to prevent log spam for a single massive batch
184
205
 
185
206
  for await (const row of rowStream) {
186
207
  // FIX #2: Entity-Atomic Batching
@@ -188,12 +209,23 @@ class DataFetcher {
188
209
  if (entityField) {
189
210
  const rowEntity = String(row[entityField]);
190
211
 
191
- // If batch is full AND we have moved to a new entity, yield the batch
192
- // This ensures the current entity (which might have many rows) stays together
212
+ // Check if we should yield
213
+ // Condition: Batch is full AND we are on a NEW entity
193
214
  if (batch.length >= batchSize && rowEntity !== currentEntity && currentEntity !== null) {
194
215
  yield this._transform(batch, { lookback, dateField, entityField, dataField });
195
216
  batch = [];
217
+ batchHasWarned = false;
196
218
  }
219
+
220
+ // SAFETY VALVE (Fix #6 Alternative):
221
+ // If batch grows huge (Super Entity) and we CANNOT split (same entity), warn the admin.
222
+ if (batch.length > batchSize * BATCH_GROWTH_WARNING_THRESHOLD && !batchHasWarned) {
223
+ this._log('WARN', `SUPER ENTITY DETECTED: Entity '${currentEntity}' in table '${table}' has >${batch.length} rows. ` +
224
+ `This exceeds batch size ${batchSize} by ${BATCH_GROWTH_WARNING_THRESHOLD}x. ` +
225
+ `Risk of OOM or Timeouts. Consider filtering this entity.`);
226
+ batchHasWarned = true;
227
+ }
228
+
197
229
  currentEntity = rowEntity;
198
230
  } else {
199
231
  // Fallback for non-entity tables (strict count)
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * @fileoverview Schema Registry - Dynamic schema discovery with caching
3
- *
4
- * Core innovation of v2: No hardcoded schemas. Instead, we:
3
+ * * Core innovation of v2: No hardcoded schemas. Instead, we:
5
4
  * 1. Fetch schemas from BigQuery INFORMATION_SCHEMA on first access
6
5
  * 2. Cache them with configurable TTL
7
6
  * 3. Validate all queries against cached schemas BEFORE sending to BigQuery
8
- *
9
- * This prevents runtime query failures and eliminates schema maintenance burden.
7
+ * * This prevents runtime query failures and eliminates schema maintenance burden.
8
+ * * UPDATE: Implemented Request Coalescing (Fix #5) to prevent "Thundering Herd"
9
+ * on startup or cache expiry.
10
10
  */
11
11
 
12
12
  const { BigQuery } = require('@google-cloud/bigquery');
@@ -45,18 +45,21 @@ class SchemaRegistry {
45
45
 
46
46
  this.client = new BigQuery({ projectId: this.projectId });
47
47
  this.cache = new Map();
48
+ this.pendingFetches = new Map(); // FIX: Track in-flight requests
48
49
 
49
50
  // Track schema fetch stats for monitoring
50
51
  this.stats = {
51
52
  hits: 0,
52
53
  misses: 0,
53
54
  refreshes: 0,
54
- errors: 0
55
+ errors: 0,
56
+ coalesced: 0 // New metric
55
57
  };
56
58
  }
57
59
 
58
60
  /**
59
61
  * Get schema for a table, fetching from BigQuery if not cached.
62
+ * Implements Request Coalescing to handle concurrent access.
60
63
  * @param {string} tableName - Table name (without dataset prefix)
61
64
  * @returns {Promise<TableSchema>}
62
65
  */
@@ -67,6 +70,13 @@ class SchemaRegistry {
67
70
  this.stats.hits++;
68
71
  return cached;
69
72
  }
73
+
74
+ // FIX: Check for pending fetch (Request Coalescing)
75
+ if (this.pendingFetches.has(tableName)) {
76
+ this.stats.coalesced++;
77
+ // this._log('DEBUG', `Coalescing request for ${tableName}`);
78
+ return this.pendingFetches.get(tableName);
79
+ }
70
80
 
71
81
  if (cached) {
72
82
  this.stats.refreshes++;
@@ -76,7 +86,16 @@ class SchemaRegistry {
76
86
  this._log('DEBUG', `Schema cache miss for ${tableName}, fetching...`);
77
87
  }
78
88
 
79
- return await this._fetchAndCacheSchema(tableName);
89
+ // Create the promise and store it
90
+ const fetchPromise = this._fetchAndCacheSchema(tableName);
91
+ this.pendingFetches.set(tableName, fetchPromise);
92
+
93
+ try {
94
+ return await fetchPromise;
95
+ } finally {
96
+ // Always clean up pending map, success or failure
97
+ this.pendingFetches.delete(tableName);
98
+ }
80
99
  }
81
100
 
82
101
  /**
@@ -158,6 +177,8 @@ class SchemaRegistry {
158
177
  async warmCache(tableNames) {
159
178
  const results = { success: [], failed: [] };
160
179
 
180
+ // With request coalescing, we can just map and wait.
181
+ // Simultaneous calls for the same table will automatically merge.
161
182
  await Promise.all(tableNames.map(async (tableName) => {
162
183
  try {
163
184
  await this.getSchema(tableName);
@@ -178,9 +199,11 @@ class SchemaRegistry {
178
199
  clearCache(tableName = null) {
179
200
  if (tableName) {
180
201
  this.cache.delete(tableName);
202
+ this.pendingFetches.delete(tableName); // Also clear pending if forced
181
203
  this._log('DEBUG', `Cleared schema cache for ${tableName}`);
182
204
  } else {
183
205
  this.cache.clear();
206
+ this.pendingFetches.clear();
184
207
  this._log('DEBUG', 'Cleared entire schema cache');
185
208
  }
186
209
  }
@@ -193,6 +216,7 @@ class SchemaRegistry {
193
216
  return {
194
217
  ...this.stats,
195
218
  cachedTables: this.cache.size,
219
+ pendingRequests: this.pendingFetches.size,
196
220
  cacheContents: Array.from(this.cache.keys())
197
221
  };
198
222
  }
@@ -284,4 +308,4 @@ class SchemaRegistry {
284
308
  }
285
309
  }
286
310
 
287
- module.exports = { SchemaRegistry };
311
+ module.exports = { SchemaRegistry };
@@ -9,6 +9,8 @@
9
9
  * * * UPDATE: Includes Global vs Batch Data Split to fix "Identity Crisis".
10
10
  * * * UPDATE: Implemented FORCE logic to bypass "up-to-date" checks for testing.
11
11
  * * * UPDATE: Aggregates performance reporting to prevent log spam.
12
+ * * * FIX: Resolved N+1 Dependency Fetching (Strict Mode in Streaming).
13
+ * * * FIX: Added missing 'skipped' property to return types for type safety.
12
14
  */
13
15
 
14
16
  const crypto = require('crypto');
@@ -316,21 +318,41 @@ class Orchestrator {
316
318
 
317
319
  const { data: batchLocalData, entityIds } = batch;
318
320
  const combinedData = { ...batchLocalData, ...globalData };
321
+
322
+ // STRICT FIX: Prefetch dependencies for the batch.
319
323
  const batchDeps = await this._prefetchBatchDependencies(entry, dateStr, depResults, entityIds);
324
+
320
325
  const { rules } = this.ruleInjector.createContext();
321
326
  const batchResults = {};
322
327
 
323
328
  await Promise.all(entityIds.map(entityId => limit(async () => {
324
329
  const instance = new entry.class();
325
330
  const entityData = this._filterDataForEntity(combinedData, entityId, driverEntityField);
331
+
326
332
  const context = {
327
333
  computation: entry, date: dateStr, entityId, data: entityData,
334
+
335
+ // STRICT FIX: No fallback to _lazyLoadDependency.
328
336
  getDependency: (depName, targetId) => {
329
- if (batchDeps[depName] && batchDeps[depName].has(targetId || entityId)) {
330
- return batchDeps[depName].get(targetId || entityId);
337
+ const id = targetId || entityId;
338
+
339
+ // 1. Look in Batch-Prefetched Dependencies (Priority)
340
+ if (batchDeps[depName] && batchDeps[depName].has(id)) {
341
+ return batchDeps[depName].get(id);
342
+ }
343
+
344
+ // 2. Look in Global/Preloaded Dependencies
345
+ if (depResults[depName]) {
346
+ if (depResults[depName][id] !== undefined) return depResults[depName][id];
331
347
  }
332
- return this._lazyLoadDependency(dateStr, depName, targetId || entityId, depResults);
348
+
349
+ // 3. STRICT MODE: Throw Error
350
+ throw new Error(
351
+ `[Strict Dependency] Dependency '${depName}' (ID: ${id}) not found in batch context. ` +
352
+ `Ensure '${depName}' is listed in ${entry.name}.getConfig().dependencies.`
353
+ );
333
354
  },
355
+
334
356
  previousResult, rules, references: this.referenceDataCache,
335
357
  config: this.config, dataFetcher: this.dataFetcher
336
358
  };
@@ -357,22 +379,18 @@ class Orchestrator {
357
379
  if (cp) await checkpointer.complete(dateStr, entry.name, cp.id);
358
380
  }
359
381
 
360
- return { count: totalCount, hash: rollingHash.digest('hex').substring(0, 16) };
382
+ // FIX: Return valid object shape including skipped: false
383
+ return { count: totalCount, hash: rollingHash.digest('hex').substring(0, 16), skipped: false };
361
384
  }
362
385
 
363
386
  /**
364
387
  * Determine if a computation should use remote workers
365
- *
366
- * @param {Object} entry - Manifest entry
388
+ * * @param {Object} entry - Manifest entry
367
389
  * @param {Object} options - Execution options
368
390
  * @param {boolean} [options.useWorkerPool] - Runtime override (true/false/undefined)
369
391
  * @param {boolean} [options.forceLocal] - Force local execution
370
392
  */
371
393
  _shouldUseRemoteWorkers(entry, options) {
372
- // Runtime override takes precedence (for admin testing)
373
- // useWorkerPool: true -> force use worker pool
374
- // useWorkerPool: false -> force local execution
375
- // useWorkerPool: undefined -> use config
376
394
  if (options.useWorkerPool === true) {
377
395
  if (!this.remoteRunner) {
378
396
  this._log('WARN', 'useWorkerPool=true but remoteRunner not initialized');
@@ -384,30 +402,22 @@ class Orchestrator {
384
402
  return false;
385
403
  }
386
404
 
387
- // No remote runner configured
388
405
  if (!this.remoteRunner) return false;
389
-
390
- // Force local execution via options
391
406
  if (options.forceLocal) return false;
392
407
 
393
408
  const poolConfig = this.config.workerPool || {};
394
409
 
395
- // Exclusion list
396
410
  if (poolConfig.excludeComputations?.includes(entry.name) ||
397
411
  poolConfig.excludeComputations?.includes(entry.originalName)) {
398
412
  return false;
399
413
  }
400
414
 
401
- // Force list (override threshold)
402
415
  if (poolConfig.forceOffloadComputations?.includes(entry.name) ||
403
416
  poolConfig.forceOffloadComputations?.includes(entry.originalName)) {
404
417
  return true;
405
418
  }
406
419
 
407
- // Only per-entity computations can be offloaded
408
420
  if (entry.type !== 'per-entity') return false;
409
-
410
- // Default: use remote if worker pool is enabled
411
421
  return true;
412
422
  }
413
423
 
@@ -492,7 +502,6 @@ class Orchestrator {
492
502
  this._log('WARN', `[Remote] Batch ${batchIndex}: ${errors.length} entities failed`);
493
503
  totalErrors += errors.length;
494
504
 
495
- // Log first few errors for debugging
496
505
  errors.slice(0, 3).forEach(e => {
497
506
  this._log('DEBUG', ` - ${e.entityId}: ${e.error}`);
498
507
  });
@@ -524,7 +533,8 @@ class Orchestrator {
524
533
  this._log('WARN', `[Remote] Completed with ${totalErrors} total errors out of ${totalCount + totalErrors} entities`);
525
534
  }
526
535
 
527
- return { count: totalCount, hash: rollingHash.digest('hex').substring(0, 16) };
536
+ // FIX: Return valid object shape including skipped: false
537
+ return { count: totalCount, hash: rollingHash.digest('hex').substring(0, 16), skipped: false };
528
538
  }
529
539
 
530
540
  async _executeGlobal(entry, dateStr, depResults, previousResult, options, forceEntities) {
@@ -569,7 +579,8 @@ class Orchestrator {
569
579
  await this.storageManager.finalizeResults(dateStr, entry);
570
580
  }
571
581
 
572
- return { count: Object.keys(results || {}).length, hash: finalHash };
582
+ // FIX: Return valid object shape including skipped: false
583
+ return { count: Object.keys(results || {}).length, hash: finalHash, skipped: false };
573
584
  }
574
585
 
575
586
  _printExecutionSummary(summary) {
@@ -668,6 +679,10 @@ class Orchestrator {
668
679
  async _lazyLoadDependency(dateStr, depName, entityId, preloaded) {
669
680
  if (preloaded[depName] && !entityId) return preloaded[depName];
670
681
  if (preloaded[depName] && entityId) return preloaded[depName][entityId];
682
+
683
+ // WARN: This is the slow path that we removed from Streaming
684
+ this._log('WARN', `LAZY LOAD: Fetching single entity '${entityId}' for '${depName}'. This is slow.`);
685
+
671
686
  if (entityId) return this.stateRepository.getEntityResult(dateStr, depName, entityId);
672
687
  return this.stateRepository.getResult(dateStr, depName);
673
688
  }
@@ -1,20 +1,18 @@
1
1
  /**
2
2
  * @fileoverview Remote Task Runner (Serverless Worker Pool Client)
3
- *
4
- * RESPONSIBILITIES:
3
+ * * RESPONSIBILITIES:
5
4
  * 1. Package entity data and context into GCS files
6
5
  * 2. Invoke remote worker functions in parallel
7
6
  * 3. Collect results and errors
8
7
  * 4. Handle retries for transient failures
9
- *
10
- * DATA FLOW:
8
+ * * DATA FLOW:
11
9
  * Orchestrator calls runBatch() -> Upload to GCS -> Invoke Workers -> Collect Results
12
- *
13
- * DESIGN PRINCIPLES:
10
+ * * DESIGN PRINCIPLES:
14
11
  * - Workers are stateless - all context is passed via GCS
15
12
  * - High parallelism - hundreds of concurrent invocations
16
13
  * - Fault isolation - one entity failure doesn't affect others
17
14
  * - Cost efficient - workers scale to zero between runs
15
+ * - RESILIENCE: Implements Circuit Breaker to prevent Retry Cost Spirals [Fix #2]
18
16
  */
19
17
 
20
18
  const { Storage } = require('@google-cloud/storage');
@@ -36,6 +34,13 @@ class RemoteTaskRunner {
36
34
  this.timeout = poolConfig.timeout || 60000; // 60s default
37
35
  this.retries = poolConfig.retries || 2;
38
36
 
37
+ // Circuit Breaker Config [Fix #2]
38
+ this.cbConfig = {
39
+ minInvocations: 20, // Minimum calls before checking rate
40
+ failureThreshold: 0.30, // Trip if failure rate > 30%
41
+ ...poolConfig.circuitBreaker
42
+ };
43
+
39
44
  // Local mode for testing
40
45
  this.localMode = poolConfig.localMode || process.env.WORKER_LOCAL_MODE === 'true';
41
46
 
@@ -53,8 +58,7 @@ class RemoteTaskRunner {
53
58
 
54
59
  /**
55
60
  * Execute a batch of entities remotely (or locally for testing)
56
- *
57
- * @param {Object} entry - Manifest entry for the computation
61
+ * * @param {Object} entry - Manifest entry for the computation
58
62
  * @param {string} dateStr - Target date (YYYY-MM-DD)
59
63
  * @param {Object} baseContext - Shared context (references, config)
60
64
  * @param {string[]} entityIds - Entity IDs to process
@@ -126,11 +130,21 @@ class RemoteTaskRunner {
126
130
  const errors = [];
127
131
  const uploadedPaths = [];
128
132
 
133
+ // Circuit Breaker Stats (scoped to this batch)
134
+ const batchStats = {
135
+ invocations: 0,
136
+ failures: 0,
137
+ tripped: false
138
+ };
139
+
129
140
  // Phase 1: Upload context packages to GCS
130
141
  this._log('INFO', 'Uploading context packages to GCS...');
131
142
  const uploadStart = Date.now();
132
143
 
133
144
  const uploadTasks = entityIds.map(entityId => uploadLimit(async () => {
145
+ // Check tripped status early to save uploads if massive failure occurring
146
+ if (batchStats.tripped) return;
147
+
134
148
  const contextPackage = this._buildContextPackage(
135
149
  entry,
136
150
  entityId,
@@ -158,13 +172,19 @@ class RemoteTaskRunner {
158
172
 
159
173
  const invokeTasks = uploadedPaths.map(({ entityId, path }) =>
160
174
  invokeLimit(async () => {
175
+ // FAIL FAST: If circuit tripped, do not invoke worker
176
+ if (batchStats.tripped) {
177
+ errors.push({ entityId, error: 'Skipped: Circuit Breaker Tripped due to high failure rate' });
178
+ return;
179
+ }
180
+
161
181
  try {
162
182
  const response = await this._invokeWorkerWithRetry({
163
183
  computationName: entry.originalName || entry.name,
164
184
  entityId,
165
185
  date: dateStr,
166
186
  dataUri: { bucket: this.bucketName, path }
167
- });
187
+ }, 1, batchStats); // Pass stats object to retry logic
168
188
 
169
189
  if (response.status === 'success' && response.result !== null) {
170
190
  results[entityId] = response.result;
@@ -174,12 +194,18 @@ class RemoteTaskRunner {
174
194
  // status === 'success' with result === null means skipped (filtered out)
175
195
 
176
196
  } catch (e) {
197
+ // Circuit Breaker errors are thrown here
177
198
  errors.push({ entityId, error: e.message });
178
199
  }
179
200
  })
180
201
  );
181
202
 
182
203
  await Promise.all(invokeTasks);
204
+
205
+ if (batchStats.tripped) {
206
+ this._log('ERROR', `Batch ABORTED by Circuit Breaker. Stats: ${batchStats.failures} failures / ${batchStats.invocations} invocations.`);
207
+ }
208
+
183
209
  this._log('INFO', `Invocations complete in ${Date.now() - invokeStart}ms`);
184
210
 
185
211
  // Phase 3: Cleanup GCS (fire and forget)
@@ -237,12 +263,21 @@ class RemoteTaskRunner {
237
263
  }
238
264
 
239
265
  /**
240
- * Invoke a worker with retry logic
266
+ * Invoke a worker with retry logic and Circuit Breaker
241
267
  */
242
- async _invokeWorkerWithRetry(payload, attempt = 1) {
268
+ async _invokeWorkerWithRetry(payload, attempt = 1, stats = null) {
269
+ // Track Invocation (Cost)
270
+ if (stats) stats.invocations++;
271
+
243
272
  try {
244
273
  return await this._invokeWorker(payload);
245
274
  } catch (e) {
275
+ // Track Failure
276
+ if (stats) {
277
+ stats.failures++;
278
+ this._checkCircuitBreaker(stats);
279
+ }
280
+
246
281
  const isRetryable = this._isRetryableError(e);
247
282
 
248
283
  if (isRetryable && attempt < this.retries) {
@@ -250,14 +285,40 @@ class RemoteTaskRunner {
250
285
  const delay = Math.min(1000 * Math.pow(2, attempt - 1), 10000);
251
286
  await new Promise(r => setTimeout(r, delay));
252
287
 
288
+ // Re-check circuit before retrying (another thread might have tripped it)
289
+ if (stats) this._checkCircuitBreaker(stats);
290
+
253
291
  this._log('DEBUG', `Retrying ${payload.entityId} (attempt ${attempt + 1})`);
254
- return this._invokeWorkerWithRetry(payload, attempt + 1);
292
+ return this._invokeWorkerWithRetry(payload, attempt + 1, stats);
255
293
  }
256
294
 
257
295
  throw e;
258
296
  }
259
297
  }
260
298
 
299
+ /**
300
+ * Check circuit breaker status and throw if tripped
301
+ */
302
+ _checkCircuitBreaker(stats) {
303
+ if (stats.tripped) {
304
+ throw new Error('Circuit Breaker: Batch aborted due to high failure rate');
305
+ }
306
+
307
+ // Only check after minimum invocations (warmup)
308
+ if (stats.invocations >= this.cbConfig.minInvocations) {
309
+ const failureRate = stats.failures / stats.invocations;
310
+
311
+ if (failureRate > this.cbConfig.failureThreshold) {
312
+ stats.tripped = true;
313
+ const msg = `🚨 CIRCUIT BREAKER TRIPPED! Failure rate ${(failureRate * 100).toFixed(1)}% ` +
314
+ `(${stats.failures}/${stats.invocations}) exceeds threshold of ${(this.cbConfig.failureThreshold * 100)}%`;
315
+
316
+ this._log('ERROR', msg);
317
+ throw new Error(msg);
318
+ }
319
+ }
320
+ }
321
+
261
322
  /**
262
323
  * Invoke a single worker via HTTP
263
324
  */
@@ -324,4 +385,4 @@ class RemoteTaskRunner {
324
385
  }
325
386
  }
326
387
 
327
- module.exports = { RemoteTaskRunner };
388
+ module.exports = { RemoteTaskRunner };
@@ -17,8 +17,7 @@
17
17
  * -d '{"action": "run", "computation": "UserPortfolioSummary", "date": "2026-01-25"}'
18
18
  */
19
19
 
20
- const system = require('../index');
21
-
20
+ const system = require('../core-api');
22
21
  /**
23
22
  * Admin test handler.
24
23
  */