@rasputin-ai/node 0.13.0 → 0.14.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 (72) hide show
  1. package/dist/auto-instrumentation/bun-plugin.d.ts.map +1 -1
  2. package/dist/auto-instrumentation/instrument-compiled-esm.d.ts.map +1 -1
  3. package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts.map +1 -1
  4. package/dist/auto-instrumentation/node-hooks.d.ts.map +1 -1
  5. package/dist/auto-instrumentation/transform-disk-cache.d.ts.map +1 -1
  6. package/dist/execution-metrics/bind-execution-metrics.d.ts +20 -0
  7. package/dist/execution-metrics/bind-execution-metrics.d.ts.map +1 -0
  8. package/dist/execution-metrics/encode-execution-metrics-upload.d.ts +14 -0
  9. package/dist/execution-metrics/encode-execution-metrics-upload.d.ts.map +1 -0
  10. package/dist/execution-metrics/execution-metrics-batches.d.ts +34 -0
  11. package/dist/execution-metrics/execution-metrics-batches.d.ts.map +1 -0
  12. package/dist/execution-metrics/execution-metrics-collector.d.ts +44 -0
  13. package/dist/execution-metrics/execution-metrics-collector.d.ts.map +1 -0
  14. package/dist/execution-metrics/execution-metrics-exporter.d.ts +23 -0
  15. package/dist/execution-metrics/execution-metrics-exporter.d.ts.map +1 -0
  16. package/dist/execution-recorder/adaptive-recording-options.d.ts +0 -2
  17. package/dist/execution-recorder/adaptive-recording-options.d.ts.map +1 -1
  18. package/dist/execution-recorder/bind-adaptive-recorder.d.ts +8 -2
  19. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -1
  20. package/dist/execution-recorder/execution-identity.d.ts +6 -0
  21. package/dist/execution-recorder/execution-identity.d.ts.map +1 -1
  22. package/dist/execution-recorder/execution-journal.d.ts +1 -0
  23. package/dist/execution-recorder/execution-journal.d.ts.map +1 -1
  24. package/dist/execution-recorder/execution-recorder-hooks.d.ts +9 -0
  25. package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -1
  26. package/dist/execution-recorder/execution-recorder-types.d.ts +1 -12
  27. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  28. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  29. package/dist/execution-recorder/execution-recording-sync.d.ts +2 -2
  30. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -1
  31. package/dist/execution-recorder/function-plan.d.ts +3 -1
  32. package/dist/execution-recorder/function-plan.d.ts.map +1 -1
  33. package/dist/function-metrics/bind-function-metrics.d.ts +20 -0
  34. package/dist/function-metrics/bind-function-metrics.d.ts.map +1 -0
  35. package/dist/function-metrics/create-metrics-only-runtime.d.ts +10 -0
  36. package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -0
  37. package/dist/function-metrics/encode-function-metrics-upload.d.ts +14 -0
  38. package/dist/function-metrics/encode-function-metrics-upload.d.ts.map +1 -0
  39. package/dist/function-metrics/function-metric-declaration-registry.d.ts +9 -0
  40. package/dist/function-metrics/function-metric-declaration-registry.d.ts.map +1 -0
  41. package/dist/function-metrics/function-metrics-batches.d.ts +36 -0
  42. package/dist/function-metrics/function-metrics-batches.d.ts.map +1 -0
  43. package/dist/function-metrics/function-metrics-collector.d.ts +60 -0
  44. package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -0
  45. package/dist/function-metrics/function-metrics-exporter.d.ts +23 -0
  46. package/dist/function-metrics/function-metrics-exporter.d.ts.map +1 -0
  47. package/dist/function-metrics/install-function-metric-declaration-sink.d.ts +2 -0
  48. package/dist/function-metrics/install-function-metric-declaration-sink.d.ts.map +1 -0
  49. package/dist/function-metrics/intern-prepared-metrics.d.ts +6 -0
  50. package/dist/function-metrics/intern-prepared-metrics.d.ts.map +1 -0
  51. package/dist/function-metrics/send-function-metrics-batch.d.ts +25 -0
  52. package/dist/function-metrics/send-function-metrics-batch.d.ts.map +1 -0
  53. package/dist/function-metrics/settle-function-metrics.d.ts +8 -0
  54. package/dist/function-metrics/settle-function-metrics.d.ts.map +1 -0
  55. package/dist/index.js +3530 -671
  56. package/dist/instrument/build.js +450 -140
  57. package/dist/instrument/bun.js +454 -132
  58. package/dist/instrument/node.js +452 -132
  59. package/dist/internal.d.ts +5 -0
  60. package/dist/internal.d.ts.map +1 -1
  61. package/dist/internal.js +3836 -1009
  62. package/dist/rasputin-init.d.ts +37 -4
  63. package/dist/rasputin-init.d.ts.map +1 -1
  64. package/dist/runtime-timing/call-duration.d.ts +13 -0
  65. package/dist/runtime-timing/call-duration.d.ts.map +1 -0
  66. package/dist/{execution-recorder → runtime-timing}/dynamic-duration-sampling.d.ts +6 -4
  67. package/dist/runtime-timing/dynamic-duration-sampling.d.ts.map +1 -0
  68. package/dist/runtime-timing/execution-duration.d.ts +5 -0
  69. package/dist/runtime-timing/execution-duration.d.ts.map +1 -0
  70. package/dist/sdk-meta.d.ts +1 -1
  71. package/package.json +2 -2
  72. package/dist/execution-recorder/dynamic-duration-sampling.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -3,7 +3,8 @@ import { join } from "node:path";
3
3
  import {
4
4
  copyRedactKeys as copyRedactKeys2,
5
5
  createClient,
6
- isClientEnabled
6
+ isClientEnabled,
7
+ resolveClientActivation as resolveClientActivation2
7
8
  } from "@rasputin-ai/core";
8
9
 
9
10
  // src/auto-instrumentation/instrumentation-manifest-registry.ts
@@ -220,8 +221,12 @@ var snapshotInstrumentationManifest = (options = {}) => {
220
221
  if (registry.snapshotCache && registry.snapshotCache.generation === registry.generation && registry.snapshotCache.optionsKey === optionsKey) {
221
222
  return registry.snapshotCache.manifest;
222
223
  }
223
- const functions = [];
224
- const callSites = [];
224
+ const functions = new Map(
225
+ registry.prebuilt?.functions.map((fn) => [fn.functionId, fn])
226
+ );
227
+ const callSites = new Map(
228
+ registry.prebuilt?.callSites.map((site) => [site.id, site])
229
+ );
225
230
  const remember = (manifest) => {
226
231
  registry.snapshotCache = {
227
232
  generation: registry.generation,
@@ -234,7 +239,11 @@ var snapshotInstrumentationManifest = (options = {}) => {
234
239
  for (const fn of delta.functions) {
235
240
  const definition = definitionFromEncodedPlan(fn.plan);
236
241
  if (!definition.source) continue;
237
- functions.push({
242
+ if (!fn.metricsDeclaration) {
243
+ throw new Error(`Missing function metrics declaration: ${fn.functionId}`);
244
+ }
245
+ functions.set(definition.functionId, {
246
+ ...functions.get(definition.functionId),
238
247
  functionId: definition.functionId,
239
248
  source: {
240
249
  packageRelativePath: definition.source.packageRelativePath,
@@ -246,21 +255,23 @@ var snapshotInstrumentationManifest = (options = {}) => {
246
255
  startColumn: fn.startColumn,
247
256
  endLine: fn.endLine,
248
257
  endColumn: fn.endColumn,
258
+ metricsDeclaration: fn.metricsDeclaration,
249
259
  ...fn.instrumented === false ? { instrumented: false, skipReason: fn.skipReason } : {}
250
260
  });
251
261
  }
252
262
  for (const site of delta.callSites) {
253
263
  const source = sourceAt(site.filePath, site.line, site.column);
254
264
  if (!source) continue;
255
- callSites.push({
256
- id: stableId(
257
- "cs",
258
- site.callerFunctionId,
259
- source.packageName ?? "",
260
- source.packageRelativePath,
261
- site.line,
262
- site.column
263
- ),
265
+ const id = stableId(
266
+ "cs",
267
+ site.callerFunctionId,
268
+ source.packageName ?? "",
269
+ source.packageRelativePath,
270
+ site.line,
271
+ site.column
272
+ );
273
+ callSites.set(id, {
274
+ id,
264
275
  callerFunctionId: site.callerFunctionId,
265
276
  calleeName: site.calleeName,
266
277
  calleeText: site.calleeText,
@@ -282,20 +293,21 @@ var snapshotInstrumentationManifest = (options = {}) => {
282
293
  }
283
294
  });
284
295
  }
285
- if (functions.length === 0 && callSites.length === 0) {
296
+ if (functions.size === 0 && callSites.size === 0) {
286
297
  return remember(void 0);
287
298
  }
288
- const packages = { ...options.sourceRoots ?? {} };
299
+ const packages = { ...registry.prebuilt?.sourceRoots?.packages, ...options.sourceRoots };
300
+ const sourceRoot = options.sourceRoot ?? registry.prebuilt?.sourceRoots?.default;
289
301
  return remember({
290
302
  schema_version: INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
291
- ...options.sourceRoot || Object.keys(packages).length > 0 ? {
303
+ ...sourceRoot || Object.keys(packages).length > 0 ? {
292
304
  sourceRoots: {
293
- ...options.sourceRoot ? { default: options.sourceRoot } : {},
305
+ ...sourceRoot ? { default: sourceRoot } : {},
294
306
  packages
295
307
  }
296
308
  } : {},
297
- functions,
298
- callSites
309
+ functions: [...functions.values()],
310
+ callSites: [...callSites.values()]
299
311
  });
300
312
  };
301
313
  var collectParamsByFunctionId = () => {
@@ -666,176 +678,1574 @@ var scheduleInstrumentationManifestUpload = (options) => {
666
678
  };
667
679
  };
668
680
 
669
- // src/execution-recorder/execution-recorder.ts
670
- import { AsyncLocalStorage } from "node:async_hooks";
681
+ // src/execution-metrics/bind-execution-metrics.ts
682
+ import { randomUUID as randomUUID2 } from "node:crypto";
671
683
  import {
672
- rasputinOmitted,
673
- rasputinTagKind,
674
- runtimeFunctionId as runtimeFunctionId2
684
+ defaultIngestFetch,
685
+ resolveEndpointUrls as resolveEndpointUrls2
675
686
  } from "@rasputin-ai/core";
676
687
 
677
- // src/execution-recorder/adaptive-recording-options.ts
678
- var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
679
- var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
680
- var MAX_FULL_CAPTURE_DURATION_MS = 7 * 24 * 60 * 60 * 1e3;
681
- var sanitizeFullCaptureDurationMs = (value) => {
682
- if (typeof value !== "number" || !Number.isFinite(value)) {
683
- return DEFAULT_FULL_CAPTURE_DURATION_MS;
688
+ // src/execution-metrics/execution-metrics-collector.ts
689
+ import {
690
+ durationHistogramBucket,
691
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
692
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES,
693
+ FUNCTION_METRICS_MAX_BUFFERED_MS,
694
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES,
695
+ FUNCTION_METRICS_MAX_MINUTE_ROWS,
696
+ FUNCTION_METRICS_MAX_STATE_BYTES,
697
+ FUNCTION_METRICS_MEASUREMENT_FORMAT,
698
+ FUNCTION_METRICS_MINUTE_MS,
699
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT,
700
+ isCanonicalFunctionMetricsExecutionKey
701
+ } from "@rasputin-ai/core";
702
+
703
+ // src/execution-metrics/execution-metrics-batches.ts
704
+ import { randomUUID } from "node:crypto";
705
+ import {
706
+ EXECUTION_METRICS_SCHEMA_VERSION
707
+ } from "@rasputin-ai/core";
708
+ var emptyCoverage = (buckets) => ({
709
+ covered_bucket_starts: buckets,
710
+ skipped_unresolved_execution_type: 0,
711
+ dropped_active_series: 0,
712
+ dropped_byte_budget: 0,
713
+ dropped_queue_budget: 0,
714
+ dropped_late_completion: 0,
715
+ dropped_unexportable: 0
716
+ });
717
+ var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
718
+ var sparseHistogram = (histogram) => {
719
+ const cells = [];
720
+ for (let index = 0; index < histogram.length; index += 1) {
721
+ const count = histogram[index] ?? 0;
722
+ if (count > 0) cells.push([index, count]);
684
723
  }
685
- return Math.min(
686
- MAX_FULL_CAPTURE_DURATION_MS,
687
- Math.max(MIN_FULL_CAPTURE_DURATION_MS, Math.floor(value))
724
+ return cells;
725
+ };
726
+ var toMinute = (unit, executionTypeIndex) => ({
727
+ execution_type_index: executionTypeIndex,
728
+ bucket_start: bucketStart(unit.minute),
729
+ started_executions: unit.series.started,
730
+ completed_executions: unit.series.completed,
731
+ failed_executions: unit.series.failed,
732
+ duration_sample_count: unit.series.sampleCount,
733
+ duration_sample_sum_us: unit.series.sampleSumUs,
734
+ duration_sample_min_us: unit.series.sampleMinUs,
735
+ duration_sample_max_us: unit.series.sampleMaxUs,
736
+ duration_histogram: sparseHistogram(unit.series.histogram),
737
+ invalid_timing_count: unit.series.invalidTiming
738
+ });
739
+ var unitsFromQueue = (queued) => {
740
+ const units = [];
741
+ for (const queuedMinute of queued) {
742
+ for (const [executionHandle, series] of queuedMinute.series) {
743
+ units.push({ minute: queuedMinute.minute, executionHandle, series });
744
+ }
745
+ }
746
+ units.sort((left, right) => {
747
+ if (left.minute !== right.minute) return left.minute - right.minute;
748
+ return left.executionHandle - right.executionHandle;
749
+ });
750
+ return units;
751
+ };
752
+ var unitMarks = (series) => {
753
+ const next = series.started + series.completed;
754
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
755
+ };
756
+ var chunkUnits = (units, maxExecutionTypes, maxMinuteRows) => {
757
+ const chunks = [];
758
+ let current = [];
759
+ let executionTypes = /* @__PURE__ */ new Set();
760
+ let droppedUnexportable = 0;
761
+ const flush = () => {
762
+ if (current.length === 0) return;
763
+ chunks.push(current);
764
+ current = [];
765
+ executionTypes = /* @__PURE__ */ new Set();
766
+ };
767
+ for (const unit of units) {
768
+ if (maxMinuteRows < 1) {
769
+ droppedUnexportable += unitMarks(unit.series);
770
+ continue;
771
+ }
772
+ const nextTypes = executionTypes.has(unit.executionHandle) ? executionTypes.size : executionTypes.size + 1;
773
+ if (current.length >= maxMinuteRows || nextTypes > maxExecutionTypes) flush();
774
+ current.push(unit);
775
+ executionTypes.add(unit.executionHandle);
776
+ }
777
+ flush();
778
+ return { chunks, droppedUnexportable };
779
+ };
780
+ var batchForChunk = (draft, units, coverage) => {
781
+ const executionIndexes = /* @__PURE__ */ new Map();
782
+ const executionTypes = [];
783
+ const minutes = [];
784
+ for (const unit of units) {
785
+ let executionTypeIndex = executionIndexes.get(unit.executionHandle);
786
+ if (executionTypeIndex === void 0) {
787
+ const executionKey = draft.executionKeys[unit.executionHandle];
788
+ if (!executionKey) continue;
789
+ executionTypeIndex = executionTypes.length;
790
+ executionIndexes.set(unit.executionHandle, executionTypeIndex);
791
+ executionTypes.push({ execution_key: executionKey });
792
+ }
793
+ minutes.push(toMinute(unit, executionTypeIndex));
794
+ }
795
+ const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
796
+ return {
797
+ schema_version: EXECUTION_METRICS_SCHEMA_VERSION,
798
+ measurement_format: draft.measurementFormat,
799
+ producer_id: draft.producerId,
800
+ batch_id: draft.batchId(),
801
+ environment: draft.environment,
802
+ release: draft.release,
803
+ execution_types: executionTypes,
804
+ minutes,
805
+ coverage: { ...coverage, covered_bucket_starts: covered }
806
+ };
807
+ };
808
+ var lossOnlyBatch = (draft, coverage) => ({
809
+ schema_version: EXECUTION_METRICS_SCHEMA_VERSION,
810
+ measurement_format: draft.measurementFormat,
811
+ producer_id: draft.producerId,
812
+ batch_id: draft.batchId(),
813
+ environment: draft.environment,
814
+ release: draft.release,
815
+ execution_types: [],
816
+ minutes: [],
817
+ coverage
818
+ });
819
+ var executionMetricsBatchesFromQueue = (draft) => {
820
+ const units = unitsFromQueue(draft.queued);
821
+ const { chunks, droppedUnexportable } = chunkUnits(
822
+ units,
823
+ draft.maxExecutionTypes,
824
+ draft.maxMinuteRows
825
+ );
826
+ const coverage = {
827
+ ...draft.coverage,
828
+ dropped_unexportable: draft.coverage.dropped_unexportable + droppedUnexportable
829
+ };
830
+ if (chunks.length === 0) {
831
+ const hasLoss = Object.entries(coverage).some(([key, value]) => {
832
+ return key !== "covered_bucket_starts" && typeof value === "number" && value > 0;
833
+ });
834
+ return hasLoss ? [lossOnlyBatch(draft, coverage)] : [];
835
+ }
836
+ return chunks.map(
837
+ (chunk, index) => batchForChunk(draft, chunk, index === 0 ? coverage : emptyCoverage([]))
688
838
  );
689
839
  };
690
- var sanitizeDynamicDurationSampling = (value) => value === true;
840
+ var newExecutionMetricsBatchId = () => randomUUID();
691
841
 
692
- // src/execution-recorder/dynamic-duration-sampling.ts
693
- var DYNAMIC_DURATION_SAMPLE_STAGES = [
694
- { below: 10, divisor: 1 },
695
- { below: 30, divisor: 2 },
696
- { below: 100, divisor: 3 },
697
- { below: 500, divisor: 11 },
698
- { below: 1e3, divisor: 23 },
699
- { below: 5e3, divisor: 53 }
700
- ];
701
- var DYNAMIC_DURATION_SAMPLE_TAIL_AFTER = 5e3;
702
- var DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR = 100;
703
- var DYNAMIC_DURATION_SAMPLE_RESET_MS = 60 * 60 * 1e3;
704
- var MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS = 4096;
705
- var dynamicDurationSampleDivisor = (index) => {
706
- for (const stage of DYNAMIC_DURATION_SAMPLE_STAGES) {
707
- if (index < stage.below) return stage.divisor;
842
+ // src/execution-metrics/execution-metrics-collector.ts
843
+ var SERIES_BYTES = 256;
844
+ var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
845
+ var MAX_ELAPSED_NS = BigInt(Number.MAX_SAFE_INTEGER);
846
+ var defaultLimits = () => ({
847
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES,
848
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES,
849
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS / FUNCTION_METRICS_MINUTE_MS,
850
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
851
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
852
+ });
853
+ var defaultClock = () => ({
854
+ monotonicNs: () => process.hrtime.bigint(),
855
+ wallTimeMs: () => Date.now()
856
+ });
857
+ var emptyCoverage2 = () => ({
858
+ covered_bucket_starts: [],
859
+ skipped_unresolved_execution_type: 0,
860
+ dropped_active_series: 0,
861
+ dropped_byte_budget: 0,
862
+ dropped_queue_budget: 0,
863
+ dropped_late_completion: 0,
864
+ dropped_unexportable: 0
865
+ });
866
+ var note = (coverage, counter, amount = 1) => {
867
+ const next = coverage[counter] + amount;
868
+ coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
869
+ };
870
+ var countSeries = (table) => table.size;
871
+ var tableBytes = (table) => {
872
+ let bytes = 0;
873
+ for (const series of table.values()) bytes += series.bytes;
874
+ return bytes;
875
+ };
876
+ var discardedMarks = (table) => {
877
+ let marks = 0;
878
+ for (const series of table.values()) {
879
+ const next = marks + series.started + series.completed;
880
+ marks = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
708
881
  }
709
- return DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
882
+ return marks;
710
883
  };
711
- var shouldSampleDynamicDuration = (index) => {
712
- return index % dynamicDurationSampleDivisor(index) === 0;
884
+ var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
885
+ var copySeries = (series) => ({
886
+ ...series,
887
+ histogram: series.histogram.slice()
888
+ });
889
+ var resetSeries = (series) => {
890
+ series.started = 0;
891
+ series.completed = 0;
892
+ series.failed = 0;
893
+ series.sampleCount = 0;
894
+ series.sampleSumUs = 0;
895
+ series.sampleMinUs = null;
896
+ series.sampleMaxUs = null;
897
+ series.invalidTiming = 0;
898
+ series.histogram.fill(0);
713
899
  };
714
- var nextDurationSampleIndex = (index) => {
715
- if (index < Number.MAX_SAFE_INTEGER) return index + 1;
716
- return DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + (index - DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + 1) % DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
900
+ var snapshotAndReset = (table) => {
901
+ const snapshot = /* @__PURE__ */ new Map();
902
+ for (const [executionHandle, series] of table) {
903
+ if (seriesHasMarks(series)) snapshot.set(executionHandle, copySeries(series));
904
+ resetSeries(series);
905
+ }
906
+ return snapshot;
717
907
  };
718
- var createDynamicDurationSampleBuckets = (options) => {
719
- const buckets = /* @__PURE__ */ new Map();
720
- const maxBuckets = options.maxBuckets ?? MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS;
721
- const resetMs = options.resetMs ?? DYNAMIC_DURATION_SAMPLE_RESET_MS;
722
- let lastResetAtMs = options.nowMs();
723
- const reset = () => {
724
- buckets.clear();
725
- lastResetAtMs = options.nowMs();
908
+ var createExecutionMetricsCollector = (options) => {
909
+ const limits = { ...defaultLimits(), ...options.limits };
910
+ const clock = options.clock ?? defaultClock();
911
+ const batchId = options.batchId ?? newExecutionMetricsBatchId;
912
+ const measurementFormat = options.sampledMeasurementFormat ? FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT : FUNCTION_METRICS_MEASUREMENT_FORMAT;
913
+ const coverage = emptyCoverage2();
914
+ const executionKeys = [];
915
+ const executionHandleByKey = /* @__PURE__ */ new Map();
916
+ const active = /* @__PURE__ */ new Map();
917
+ const queue = [];
918
+ let lastClosedMinute = Number.NEGATIVE_INFINITY;
919
+ let lastSeenMinute = Number.NEGATIVE_INFINITY;
920
+ let stateBytes = 0;
921
+ let activeSeries = 0;
922
+ let sealed = false;
923
+ const reserve = (bytes) => {
924
+ if (stateBytes > limits.maxStateBytes - bytes) {
925
+ note(coverage, "dropped_byte_budget");
926
+ return false;
927
+ }
928
+ stateBytes += bytes;
929
+ return true;
726
930
  };
727
- const resetTimer = setInterval(reset, resetMs);
728
- resetTimer.unref?.();
729
- return {
730
- take: (executionType, callerFunctionId, functionId) => {
731
- if (options.nowMs() - lastResetAtMs >= resetMs) reset();
732
- const key = `${executionType}\0${callerFunctionId}\0${functionId}`;
733
- const existing = buckets.get(key);
734
- if (existing !== void 0) {
735
- buckets.delete(key);
736
- buckets.set(key, nextDurationSampleIndex(existing));
737
- return shouldSampleDynamicDuration(existing);
738
- }
739
- while (buckets.size >= maxBuckets) {
740
- const oldest = buckets.keys().next().value;
741
- if (oldest === void 0) break;
742
- buckets.delete(oldest);
931
+ const internExecutionKey = (key) => {
932
+ if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
933
+ const existing = executionHandleByKey.get(key);
934
+ if (existing !== void 0) return existing;
935
+ if (executionKeys.length >= limits.maxExecutionTypes) {
936
+ note(coverage, "dropped_unexportable");
937
+ return void 0;
938
+ }
939
+ if (!reserve(key.length)) return void 0;
940
+ const handle = executionKeys.length;
941
+ executionKeys.push(key);
942
+ executionHandleByKey.set(key, handle);
943
+ return handle;
944
+ };
945
+ const ensureSeries = (minute, executionHandle) => {
946
+ let byExecution = active.get(minute);
947
+ if (!byExecution) {
948
+ byExecution = /* @__PURE__ */ new Map();
949
+ active.set(minute, byExecution);
950
+ }
951
+ const existing = byExecution.get(executionHandle);
952
+ if (existing) return existing;
953
+ if (activeSeries >= limits.maxActiveSeries) {
954
+ note(coverage, "dropped_active_series");
955
+ return void 0;
956
+ }
957
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
958
+ const series = {
959
+ started: 0,
960
+ completed: 0,
961
+ failed: 0,
962
+ sampleCount: 0,
963
+ sampleSumUs: 0,
964
+ sampleMinUs: null,
965
+ sampleMaxUs: null,
966
+ invalidTiming: 0,
967
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
968
+ bytes: SERIES_BYTES + HISTOGRAM_BYTES
969
+ };
970
+ byExecution.set(executionHandle, series);
971
+ activeSeries += 1;
972
+ return series;
973
+ };
974
+ const appendQueue = (entry) => {
975
+ if (discardedMarks(entry.series) === 0) {
976
+ stateBytes -= entry.bytes;
977
+ if (stateBytes < 0) stateBytes = 0;
978
+ return;
979
+ }
980
+ queue.push(entry);
981
+ queue.sort((left, right) => left.minute - right.minute);
982
+ while (queue.length > limits.maxQueuedMinutes) {
983
+ const dropped = queue.shift();
984
+ if (!dropped) break;
985
+ stateBytes -= dropped.bytes;
986
+ if (stateBytes < 0) stateBytes = 0;
987
+ note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
988
+ }
989
+ };
990
+ const closeMinute = (minute, table) => {
991
+ active.delete(minute);
992
+ activeSeries -= countSeries(table);
993
+ if (minute > lastClosedMinute) lastClosedMinute = minute;
994
+ appendQueue({ minute, series: table, bytes: tableBytes(table) });
995
+ };
996
+ const rotate = (currentMinute2) => {
997
+ for (const minute of [...active.keys()]) {
998
+ if (minute >= currentMinute2) continue;
999
+ const table = active.get(minute);
1000
+ if (table) closeMinute(minute, table);
1001
+ }
1002
+ const closedThrough = currentMinute2 - 1;
1003
+ if (closedThrough > lastClosedMinute) lastClosedMinute = closedThrough;
1004
+ };
1005
+ const rotateIfNeeded = (minute) => {
1006
+ if (minute === lastSeenMinute) return;
1007
+ lastSeenMinute = minute;
1008
+ rotate(minute);
1009
+ };
1010
+ const snapshotActive = () => {
1011
+ for (const [minute, table] of active) {
1012
+ appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
1013
+ }
1014
+ };
1015
+ const moveAllActive = () => {
1016
+ for (const minute of [...active.keys()]) {
1017
+ const table = active.get(minute);
1018
+ if (table) closeMinute(minute, table);
1019
+ }
1020
+ };
1021
+ const currentMinute = (allowClosed) => {
1022
+ if (sealed) {
1023
+ note(coverage, "dropped_unexportable");
1024
+ return void 0;
1025
+ }
1026
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
1027
+ rotateIfNeeded(minute);
1028
+ if (minute <= lastClosedMinute && (!allowClosed || !active.has(minute))) {
1029
+ note(coverage, "dropped_late_completion");
1030
+ return void 0;
1031
+ }
1032
+ return minute;
1033
+ };
1034
+ const rememberSample = (series, durationUs, bucket) => {
1035
+ const sampleCount = series.sampleCount + 1;
1036
+ const sampleSumUs = series.sampleSumUs + durationUs;
1037
+ const previous = series.histogram[bucket];
1038
+ if (previous === void 0) return false;
1039
+ const cell = previous + 1;
1040
+ const sumFits = Number.isFinite(sampleSumUs) && sampleSumUs >= 0 && sampleSumUs <= Number.MAX_SAFE_INTEGER;
1041
+ if (!Number.isSafeInteger(sampleCount) || !Number.isSafeInteger(cell) || !sumFits) return false;
1042
+ series.histogram[bucket] = cell;
1043
+ series.sampleCount = sampleCount;
1044
+ series.sampleSumUs = sampleSumUs;
1045
+ series.sampleMinUs = series.sampleMinUs === null ? durationUs : Math.min(series.sampleMinUs, durationUs);
1046
+ series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
1047
+ return true;
1048
+ };
1049
+ const rememberStart = (handle) => {
1050
+ const minute = currentMinute(false);
1051
+ if (minute === void 0) return false;
1052
+ const series = ensureSeries(minute, handle);
1053
+ if (!series) return false;
1054
+ const started = series.started + 1;
1055
+ if (!Number.isSafeInteger(started)) {
1056
+ note(coverage, "dropped_unexportable");
1057
+ return false;
1058
+ }
1059
+ series.started = started;
1060
+ return true;
1061
+ };
1062
+ const bindIdentity = (state, key) => {
1063
+ if (state.finished || state.dropped || state.handle !== void 0) return;
1064
+ if (!key) return;
1065
+ const handle = internExecutionKey(key);
1066
+ if (handle === void 0) {
1067
+ state.dropped = true;
1068
+ return;
1069
+ }
1070
+ state.handle = handle;
1071
+ if (state.started) return;
1072
+ if (rememberStart(handle)) state.started = true;
1073
+ };
1074
+ const finishExecution = (state, input) => {
1075
+ if (state.finished) return;
1076
+ state.finished = true;
1077
+ if (state.dropped) return;
1078
+ if (state.handle === void 0) {
1079
+ note(coverage, "skipped_unresolved_execution_type");
1080
+ return;
1081
+ }
1082
+ if (!state.started) {
1083
+ if (!rememberStart(state.handle)) return;
1084
+ state.started = true;
1085
+ }
1086
+ const minute = currentMinute(true);
1087
+ if (minute === void 0) return;
1088
+ const series = ensureSeries(minute, state.handle);
1089
+ if (!series) return;
1090
+ const completed = series.completed + 1;
1091
+ const failed = series.failed + (input.failed ? 1 : 0);
1092
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failed)) {
1093
+ note(coverage, "dropped_unexportable");
1094
+ return;
1095
+ }
1096
+ if (input.measure) {
1097
+ if (input.startedNs === void 0 || input.endedNs === void 0) {
1098
+ const invalidTiming = series.invalidTiming + 1;
1099
+ if (!Number.isSafeInteger(invalidTiming)) {
1100
+ note(coverage, "dropped_unexportable");
1101
+ return;
1102
+ }
1103
+ series.invalidTiming = invalidTiming;
1104
+ } else {
1105
+ const elapsed = input.endedNs - input.startedNs;
1106
+ const durationUs = Number(elapsed) / 1e3;
1107
+ const placed = durationHistogramBucket(durationUs);
1108
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
1109
+ const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
1110
+ if (!sampled) {
1111
+ const invalidTiming = series.invalidTiming + 1;
1112
+ if (!Number.isSafeInteger(invalidTiming)) {
1113
+ note(coverage, "dropped_unexportable");
1114
+ return;
1115
+ }
1116
+ series.invalidTiming = invalidTiming;
1117
+ }
743
1118
  }
744
- buckets.set(key, nextDurationSampleIndex(0));
745
- return shouldSampleDynamicDuration(0);
746
- },
747
- stop: () => {
748
- clearInterval(resetTimer);
1119
+ }
1120
+ series.completed = completed;
1121
+ series.failed = failed;
1122
+ };
1123
+ const drain = (drainOptions) => {
1124
+ if (!sealed) {
1125
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
1126
+ if (drainOptions?.flushAll) snapshotActive();
1127
+ }
1128
+ const batches = executionMetricsBatchesFromQueue({
1129
+ environment: options.environment,
1130
+ release: options.release,
1131
+ producerId: options.producerId,
1132
+ batchId,
1133
+ maxExecutionTypes: limits.maxExecutionTypes,
1134
+ maxMinuteRows: limits.maxMinuteRows,
1135
+ executionKeys,
1136
+ queued: queue,
1137
+ coverage: { ...coverage, covered_bucket_starts: [] },
1138
+ measurementFormat
1139
+ });
1140
+ if (batches.length === 0) return [];
1141
+ for (const queued of queue) stateBytes -= queued.bytes;
1142
+ if (stateBytes < 0) stateBytes = 0;
1143
+ queue.length = 0;
1144
+ coverage.skipped_unresolved_execution_type = 0;
1145
+ coverage.dropped_active_series = 0;
1146
+ coverage.dropped_byte_budget = 0;
1147
+ coverage.dropped_queue_budget = 0;
1148
+ coverage.dropped_late_completion = 0;
1149
+ coverage.dropped_unexportable = 0;
1150
+ return batches;
1151
+ };
1152
+ return {
1153
+ createState: () => ({
1154
+ handle: void 0,
1155
+ started: false,
1156
+ finished: false,
1157
+ dropped: false
1158
+ }),
1159
+ bindIdentity,
1160
+ finishExecution,
1161
+ drain,
1162
+ seal: () => {
1163
+ if (sealed) return;
1164
+ sealed = true;
1165
+ moveAllActive();
749
1166
  }
750
1167
  };
751
1168
  };
752
1169
 
753
- // src/execution-recorder/error-observation.ts
754
- var bindings = /* @__PURE__ */ new WeakMap();
755
- var mintErrorObservation = (binding) => {
756
- const observation = Object.freeze(/* @__PURE__ */ Object.create(null));
757
- bindings.set(observation, binding);
758
- return observation;
1170
+ // src/function-metrics/send-function-metrics-batch.ts
1171
+ var REQUEST_TIMEOUT_MS = 2e4;
1172
+ var abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
1173
+ var retryAfterMs = (response) => {
1174
+ const header = response.headers.get("retry-after");
1175
+ if (!header) return null;
1176
+ const seconds = Number(header);
1177
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
1178
+ const date = Date.parse(header);
1179
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
759
1180
  };
760
- var bindingForObservation = (value) => {
761
- if (typeof value !== "object" || value === null) return void 0;
762
- return bindings.get(value);
1181
+ var backoffMs = (attempt, random) => {
1182
+ const base = Math.min(3e4, 500 * 2 ** attempt);
1183
+ return Math.floor(base * (0.5 + random()));
763
1184
  };
764
- var inertErrorObservation = () => {
765
- return Object.freeze(/* @__PURE__ */ Object.create(null));
1185
+ var fetchUntilAborted = (fetchFn, url, init) => new Promise((resolve, reject) => {
1186
+ const onAbort = () => reject(abortError());
1187
+ init.signal.addEventListener("abort", onAbort, { once: true });
1188
+ if (init.signal.aborted) {
1189
+ init.signal.removeEventListener("abort", onAbort);
1190
+ reject(abortError());
1191
+ return;
1192
+ }
1193
+ void fetchFn(url, init).then(
1194
+ (value) => {
1195
+ init.signal.removeEventListener("abort", onAbort);
1196
+ resolve(value);
1197
+ },
1198
+ (error) => {
1199
+ init.signal.removeEventListener("abort", onAbort);
1200
+ reject(error);
1201
+ }
1202
+ );
1203
+ });
1204
+ var sendFunctionMetricsBatch = async (input) => {
1205
+ if (input.signal.aborted) return { outcome: "aborted" };
1206
+ const nowMs = input.nowMs ?? Date.now;
1207
+ if (input.upload.expiresAtMs <= nowMs())
1208
+ return { outcome: "terminal", status: null, halt: false };
1209
+ const request = new AbortController();
1210
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS);
1211
+ timer.unref?.();
1212
+ const onParentAbort = () => request.abort();
1213
+ input.signal.addEventListener("abort", onParentAbort, { once: true });
1214
+ if (input.signal.aborted) request.abort();
1215
+ const headers = {
1216
+ Authorization: `Bearer ${input.ingestToken}`,
1217
+ "Content-Type": "application/json",
1218
+ Accept: "application/json"
1219
+ };
1220
+ if (input.upload.gzip) headers["Content-Encoding"] = "gzip";
1221
+ try {
1222
+ const response = await fetchUntilAborted(input.fetch, input.url, {
1223
+ method: "POST",
1224
+ headers,
1225
+ body: input.upload.body,
1226
+ signal: request.signal
1227
+ });
1228
+ if (response.ok) return { outcome: "ok" };
1229
+ if (response.status === 429) {
1230
+ return {
1231
+ outcome: "retry",
1232
+ waitMs: retryAfterMs(response) ?? backoffMs(input.attempt, input.random ?? Math.random)
1233
+ };
1234
+ }
1235
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
1236
+ return { outcome: "terminal", status: response.status, halt: true };
1237
+ }
1238
+ if (response.status >= 400 && response.status < 500) {
1239
+ return { outcome: "terminal", status: response.status, halt: false };
1240
+ }
1241
+ return {
1242
+ outcome: "retry",
1243
+ waitMs: backoffMs(input.attempt, input.random ?? Math.random)
1244
+ };
1245
+ } catch {
1246
+ if (input.signal.aborted) return { outcome: "aborted" };
1247
+ return { outcome: "retry", waitMs: backoffMs(input.attempt, input.random ?? Math.random) };
1248
+ } finally {
1249
+ clearTimeout(timer);
1250
+ input.signal.removeEventListener("abort", onParentAbort);
1251
+ }
766
1252
  };
767
1253
 
768
- // src/execution-recorder/execution-identity.ts
769
- var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
770
- var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
771
- var trimmed = (value) => typeof value === "string" ? value.trim() : "";
772
- var boundedKey = (key) => {
773
- return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
1254
+ // src/execution-metrics/encode-execution-metrics-upload.ts
1255
+ import {
1256
+ encodeJsonRequestBodyAsync,
1257
+ FUNCTION_METRICS_BUCKET_LATENESS_MS,
1258
+ FUNCTION_METRICS_MAX_DECODED_BYTES,
1259
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS2,
1260
+ parseFunctionMetricsBucketStart
1261
+ } from "@rasputin-ai/core";
1262
+ var minuteMarks = (minute) => {
1263
+ const next = minute.started_executions + minute.completed_executions;
1264
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
774
1265
  };
775
- var executionTypeKey = (metadata) => {
776
- if (metadata.kind === "http") {
777
- const method = trimmed(metadata.request?.method).toUpperCase();
778
- const route = trimmed(metadata.request?.route);
779
- if (!method || !route) return void 0;
780
- if (route.includes("?") || route.includes("://")) return void 0;
781
- return boundedKey(`http:${method}:${route}`);
1266
+ var expiresAtMsFor = (batch, nowMs) => {
1267
+ let oldest;
1268
+ for (const start of batch.coverage.covered_bucket_starts) {
1269
+ const bucket = parseFunctionMetricsBucketStart(start);
1270
+ if (bucket === void 0) continue;
1271
+ if (oldest === void 0 || bucket < oldest) oldest = bucket;
782
1272
  }
783
- if (!NAMED_KINDS.has(metadata.kind)) return void 0;
784
- const name = trimmed(metadata.name);
785
- if (!name) return void 0;
786
- return boundedKey(`${metadata.kind}:${name}`);
1273
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1274
+ return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
787
1275
  };
788
- var isHttpClientErrorStatus = (status) => {
789
- return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
1276
+ var zeroLossCoverage = (coverage) => ({
1277
+ ...coverage,
1278
+ skipped_unresolved_execution_type: 0,
1279
+ dropped_active_series: 0,
1280
+ dropped_byte_budget: 0,
1281
+ dropped_queue_budget: 0,
1282
+ dropped_late_completion: 0,
1283
+ dropped_unexportable: 0
1284
+ });
1285
+ var projectMinutes = (source, minutes, coverage, batchId) => {
1286
+ const typeIndexes = /* @__PURE__ */ new Map();
1287
+ const executionTypes = [];
1288
+ const remappedMinutes = [];
1289
+ for (const minute of minutes) {
1290
+ let executionTypeIndex = typeIndexes.get(minute.execution_type_index);
1291
+ if (executionTypeIndex === void 0) {
1292
+ const entry = source.execution_types[minute.execution_type_index];
1293
+ if (!entry) continue;
1294
+ executionTypeIndex = executionTypes.length;
1295
+ typeIndexes.set(minute.execution_type_index, executionTypeIndex);
1296
+ executionTypes.push(entry);
1297
+ }
1298
+ remappedMinutes.push({ ...minute, execution_type_index: executionTypeIndex });
1299
+ }
1300
+ const covered = [...new Set(remappedMinutes.map((minute) => minute.bucket_start))].sort();
1301
+ return {
1302
+ ...source,
1303
+ batch_id: batchId,
1304
+ execution_types: executionTypes,
1305
+ minutes: remappedMinutes,
1306
+ coverage: { ...coverage, covered_bucket_starts: covered }
1307
+ };
790
1308
  };
791
-
792
- // src/execution-recorder/execution-journal.ts
793
- var KIND_ENTER = 1;
794
- var KIND_EXIT = 2;
795
- var KIND_THROW = 3;
796
- var KIND_SUPPRESSED = 4;
797
- var ARGS_OMITTED = Symbol("rasputin.argsOmitted");
798
- var NO_PARENT = 4294967295;
799
- var NO_SUPPRESSION = 4294967295;
800
- var TIMING_UNAVAILABLE = -1n;
801
- var MAX_POOLED_JOURNALS = 8;
802
- var MAX_POOLED_JOURNAL_CAPACITY = 4096;
803
- var INITIAL_JOURNAL_STORAGE = 32;
804
- var BYTES_PER_EVENT = Uint8Array.BYTES_PER_ELEMENT + Uint32Array.BYTES_PER_ELEMENT * 4 + BigInt64Array.BYTES_PER_ELEMENT * 2;
805
- var DEFAULT_MAX_EVENTS_PER_EXECUTION = 1500;
806
- var MAX_JOURNAL_EVENTS = 16384;
807
- var elapsedMs = (startedAtNs, endedAtNs) => Number(endedAtNs - startedAtNs) / 1e6;
808
- var roundedMilliseconds = (nanoseconds) => Math.round(Number(nanoseconds) / 1e6 * 1e4) / 1e4;
809
- var relativeMs = (relativeNs) => Number(relativeNs) / 1e6;
810
- var measuredRelativeMs = (relativeNs) => relativeNs === TIMING_UNAVAILABLE ? void 0 : relativeMs(relativeNs);
811
- var sanitizeJournalCapacity = (value) => {
812
- const requested = value ?? DEFAULT_MAX_EVENTS_PER_EXECUTION;
813
- if (!Number.isFinite(requested)) return DEFAULT_MAX_EVENTS_PER_EXECUTION;
814
- return Math.min(MAX_JOURNAL_EVENTS, Math.max(2, Math.floor(requested)));
1309
+ var withLoss = (batch, loss) => ({
1310
+ ...batch,
1311
+ coverage: {
1312
+ ...batch.coverage,
1313
+ dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
1314
+ dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
1315
+ }
1316
+ });
1317
+ var encodeOne = async (batch, nowMs, signal) => {
1318
+ const decodedBytes = new TextEncoder().encode(JSON.stringify(batch));
1319
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES) return void 0;
1320
+ const encoded = await encodeJsonRequestBodyAsync(decodedBytes, void 0, signal);
1321
+ return {
1322
+ decodedBytes,
1323
+ body: encoded.body,
1324
+ gzip: encoded.gzip,
1325
+ batchId: batch.batch_id,
1326
+ expiresAtMs: expiresAtMsFor(batch, nowMs)
1327
+ };
815
1328
  };
816
- var ExecutionJournal = class {
817
- dropped = 0;
818
- allocatedBytes = 0;
819
- onGrow;
820
- length = 0;
821
- kind = new Uint8Array(0);
822
- planId = new Uint32Array(0);
823
- callId = new Uint32Array(0);
824
- parentCallId = new Uint32Array(0);
825
- timestampNs = new BigInt64Array(0);
826
- durationNs = new BigInt64Array(0);
827
- suppressionIndex = new Uint32Array(0);
828
- payloads = [];
829
- suppressions = [];
830
- openCallIds = /* @__PURE__ */ new Set();
831
- notedPlanIds = [];
832
- notedPlanSet = /* @__PURE__ */ new Set();
833
- maxCapacity;
834
- constructor(capacity) {
835
- this.maxCapacity = sanitizeJournalCapacity(capacity);
836
- this.reallocate(Math.min(this.maxCapacity, INITIAL_JOURNAL_STORAGE));
1329
+ var encodeFitting = async (batch, nowMs, signal) => {
1330
+ const encoded = await encodeOne(batch, nowMs, signal);
1331
+ if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
1332
+ if (batch.minutes.length <= 1) {
1333
+ return {
1334
+ uploads: [],
1335
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
1336
+ };
837
1337
  }
838
- get capacity() {
1338
+ const mid = Math.ceil(batch.minutes.length / 2);
1339
+ const first = projectMinutes(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
1340
+ const rest = projectMinutes(
1341
+ batch,
1342
+ batch.minutes.slice(mid),
1343
+ zeroLossCoverage(batch.coverage),
1344
+ newExecutionMetricsBatchId()
1345
+ );
1346
+ const left = await encodeFitting(first, nowMs, signal);
1347
+ const right = await encodeFitting(rest, nowMs, signal);
1348
+ return {
1349
+ uploads: [...left.uploads, ...right.uploads],
1350
+ droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
1351
+ };
1352
+ };
1353
+ var encodeExecutionMetricsUploads = async (batches, input) => {
1354
+ const uploads = [];
1355
+ let extra = {
1356
+ dropped_unexportable: 0,
1357
+ dropped_queue_budget: input.queueDrops ?? 0
1358
+ };
1359
+ for (const batch of batches) {
1360
+ const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
1361
+ extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
1362
+ uploads.push(...fitted.uploads);
1363
+ }
1364
+ return uploads;
1365
+ };
1366
+
1367
+ // src/execution-metrics/execution-metrics-exporter.ts
1368
+ var MAX_QUEUE_ITEMS = 32;
1369
+ var MAX_QUEUE_BYTES = 4 * 1024 * 1024;
1370
+ var DEFAULT_SCHEDULE_MS = 6e4;
1371
+ var FLUSH_MS = 1e4;
1372
+ var SHUTDOWN_FLUSH_MS = 2e3;
1373
+ var MAX_ATTEMPTS = 8;
1374
+ var sleep = (ms, signal) => new Promise((resolve) => {
1375
+ if (ms <= 0 || signal.aborted) {
1376
+ resolve();
1377
+ return;
1378
+ }
1379
+ const timer = setTimeout(finish, ms);
1380
+ timer.unref?.();
1381
+ const onAbort = () => {
1382
+ clearTimeout(timer);
1383
+ finish();
1384
+ };
1385
+ function finish() {
1386
+ signal.removeEventListener("abort", onAbort);
1387
+ resolve();
1388
+ }
1389
+ signal.addEventListener("abort", onAbort);
1390
+ if (signal.aborted) onAbort();
1391
+ });
1392
+ var createExecutionMetricsExporter = (input) => {
1393
+ const nowMs = input.nowMs ?? Date.now;
1394
+ const random = input.random ?? Math.random;
1395
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
1396
+ const queue = [];
1397
+ let queueBytes = 0;
1398
+ let queueDrops = 0;
1399
+ let timer;
1400
+ let closed = false;
1401
+ let halted = false;
1402
+ let stopped = false;
1403
+ let workAbort;
1404
+ let work;
1405
+ let sent = 0;
1406
+ let dropped = 0;
1407
+ let warnedHalt = null;
1408
+ const dropOldest = () => {
1409
+ const oldest = queue.shift();
1410
+ if (!oldest) return;
1411
+ queueBytes -= oldest.upload.decodedBytes.byteLength;
1412
+ if (queueBytes < 0) queueBytes = 0;
1413
+ queueDrops += 1;
1414
+ dropped += 1;
1415
+ };
1416
+ const enqueue = (upload) => {
1417
+ queue.push({ upload, attempt: 0 });
1418
+ queueBytes += upload.decodedBytes.byteLength;
1419
+ while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
1420
+ };
1421
+ const drainAndEnqueue = async (flushAll2) => {
1422
+ if (halted || stopped) return;
1423
+ const batches = input.collector.drain({ flushAll: flushAll2 });
1424
+ if (batches.length === 0) return;
1425
+ const encoded = await encodeExecutionMetricsUploads(batches, {
1426
+ nowMs: nowMs(),
1427
+ queueDrops
1428
+ });
1429
+ if (encoded.length === 0 || halted || stopped) return;
1430
+ queueDrops = 0;
1431
+ for (const upload of encoded) enqueue(upload);
1432
+ };
1433
+ const warnHalt = (status) => {
1434
+ if (warnedHalt === status) return;
1435
+ warnedHalt = status;
1436
+ if (status === 401 || status === 403) {
1437
+ console.warn("[rasputin] execution metrics export stopped: authentication failed");
1438
+ return;
1439
+ }
1440
+ if (status === 404) {
1441
+ console.warn("[rasputin] execution metrics export stopped: ingest route is unavailable");
1442
+ }
1443
+ };
1444
+ const pump = async (signal) => {
1445
+ while (queue.length > 0 && !halted && !stopped && !signal.aborted) {
1446
+ const item = queue[0];
1447
+ if (!item) return;
1448
+ if (item.upload.expiresAtMs <= nowMs()) {
1449
+ queue.shift();
1450
+ queueBytes -= item.upload.decodedBytes.byteLength;
1451
+ dropped += 1;
1452
+ continue;
1453
+ }
1454
+ if (item.attempt >= MAX_ATTEMPTS) {
1455
+ queue.shift();
1456
+ queueBytes -= item.upload.decodedBytes.byteLength;
1457
+ dropped += 1;
1458
+ continue;
1459
+ }
1460
+ const result = await sendFunctionMetricsBatch({
1461
+ url: input.url,
1462
+ ingestToken: input.ingestToken,
1463
+ upload: item.upload,
1464
+ fetch: input.fetch,
1465
+ signal,
1466
+ attempt: item.attempt,
1467
+ random,
1468
+ nowMs
1469
+ });
1470
+ if (result.outcome === "aborted") return;
1471
+ if (result.outcome === "ok") {
1472
+ queue.shift();
1473
+ queueBytes -= item.upload.decodedBytes.byteLength;
1474
+ sent += 1;
1475
+ continue;
1476
+ }
1477
+ if (result.outcome === "terminal") {
1478
+ queue.shift();
1479
+ queueBytes -= item.upload.decodedBytes.byteLength;
1480
+ dropped += 1;
1481
+ if (result.halt) {
1482
+ halted = true;
1483
+ warnHalt(result.status);
1484
+ }
1485
+ continue;
1486
+ }
1487
+ item.attempt += 1;
1488
+ await sleep(result.waitMs, signal);
1489
+ }
1490
+ };
1491
+ const abortCurrent = () => {
1492
+ workAbort?.abort();
1493
+ };
1494
+ const raceUntilAborted = async (running, signal) => {
1495
+ if (signal.aborted) return;
1496
+ await new Promise((resolve) => {
1497
+ let settled = false;
1498
+ const finish = () => {
1499
+ if (settled) return;
1500
+ settled = true;
1501
+ signal.removeEventListener("abort", finish);
1502
+ resolve();
1503
+ };
1504
+ signal.addEventListener("abort", finish);
1505
+ if (signal.aborted) {
1506
+ finish();
1507
+ return;
1508
+ }
1509
+ void running.then(finish, finish);
1510
+ });
1511
+ };
1512
+ const runWork = async (signal, task) => {
1513
+ const onAbort = () => abortCurrent();
1514
+ signal.addEventListener("abort", onAbort);
1515
+ if (signal.aborted) abortCurrent();
1516
+ try {
1517
+ while (work) {
1518
+ const previous = work;
1519
+ await raceUntilAborted(previous, signal);
1520
+ if (signal.aborted || halted) return;
1521
+ if (work === previous) return;
1522
+ }
1523
+ if (halted) return;
1524
+ const inner = new AbortController();
1525
+ workAbort = inner;
1526
+ if (signal.aborted) {
1527
+ workAbort = void 0;
1528
+ return;
1529
+ }
1530
+ const running = task(inner.signal).finally(() => {
1531
+ if (workAbort === inner) workAbort = void 0;
1532
+ if (work === running) work = void 0;
1533
+ });
1534
+ work = running;
1535
+ await raceUntilAborted(running, signal);
1536
+ } finally {
1537
+ signal.removeEventListener("abort", onAbort);
1538
+ }
1539
+ };
1540
+ const tick = async () => {
1541
+ if (closed || halted) return;
1542
+ try {
1543
+ await runWork(new AbortController().signal, async (signal) => {
1544
+ if (closed || halted) return;
1545
+ await drainAndEnqueue(false);
1546
+ await pump(signal);
1547
+ });
1548
+ } catch {
1549
+ }
1550
+ if (!closed && !halted) arm();
1551
+ };
1552
+ const arm = () => {
1553
+ if (closed || halted) return;
1554
+ const delay = Math.max(1e3, Math.floor(scheduleMs * (0.85 + random() * 0.3)));
1555
+ timer = setTimeout(() => {
1556
+ void tick();
1557
+ }, delay);
1558
+ timer.unref?.();
1559
+ };
1560
+ arm();
1561
+ const flush = async (timeoutMs) => {
1562
+ if (closed || halted) return;
1563
+ const abort = new AbortController();
1564
+ const budget = timeoutMs ?? FLUSH_MS;
1565
+ const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
1566
+ try {
1567
+ await runWork(abort.signal, async (signal) => {
1568
+ if (closed || halted) return;
1569
+ await drainAndEnqueue(true);
1570
+ await pump(signal);
1571
+ });
1572
+ } catch {
1573
+ } finally {
1574
+ clearTimeout(timeout);
1575
+ }
1576
+ };
1577
+ return {
1578
+ flush,
1579
+ close: async () => {
1580
+ if (closed) return;
1581
+ closed = true;
1582
+ if (timer) clearTimeout(timer);
1583
+ timer = void 0;
1584
+ const abort = new AbortController();
1585
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
1586
+ abortCurrent();
1587
+ try {
1588
+ await runWork(abort.signal, async (signal) => {
1589
+ input.collector.seal();
1590
+ await drainAndEnqueue(false);
1591
+ await pump(signal);
1592
+ });
1593
+ } catch {
1594
+ } finally {
1595
+ clearTimeout(timeout);
1596
+ stopped = true;
1597
+ input.collector.seal();
1598
+ queue.length = 0;
1599
+ queueBytes = 0;
1600
+ }
1601
+ },
1602
+ getStats: () => ({ sent, dropped, halted })
1603
+ };
1604
+ };
1605
+
1606
+ // src/execution-metrics/bind-execution-metrics.ts
1607
+ var SLOT = Symbol.for("rasputin.executionMetrics.runtime.v1");
1608
+ var releasedHandles = /* @__PURE__ */ new WeakSet();
1609
+ var isRuntime = (value) => {
1610
+ if (typeof value !== "object" || value === null) return false;
1611
+ return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
1612
+ };
1613
+ var bindingIdentity = (input) => `${input.ingestToken}
1614
+ ${input.url}
1615
+ ${input.environment}
1616
+ ${input.release}
1617
+ ${input.sampledMeasurementFormat ? "1" : "0"}`;
1618
+ var warnIncompatible = (runtime) => {
1619
+ if (runtime.warnedMismatch) return;
1620
+ runtime.warnedMismatch = true;
1621
+ console.warn(
1622
+ "[rasputin] execution metrics already running with a different configuration; this client will not collect execution metrics"
1623
+ );
1624
+ };
1625
+ var createBindings = (input) => {
1626
+ const collector = createExecutionMetricsCollector({
1627
+ environment: input.environment,
1628
+ producerId: randomUUID2(),
1629
+ release: input.release,
1630
+ sampledMeasurementFormat: input.sampledMeasurementFormat
1631
+ });
1632
+ return {
1633
+ collector,
1634
+ exporter: createExecutionMetricsExporter({
1635
+ collector,
1636
+ url: input.url,
1637
+ ingestToken: input.ingestToken,
1638
+ fetch: input.fetch ?? defaultIngestFetch()
1639
+ })
1640
+ };
1641
+ };
1642
+ var bindExecutionMetrics = (input) => {
1643
+ if (!input.clientEnabled) return void 0;
1644
+ if (input.options?.enabled === false) return void 0;
1645
+ const release = input.release.trim().toLowerCase();
1646
+ if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
1647
+ const url = resolveEndpointUrls2(input.apiUrl).executionMetricsUrl;
1648
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
1649
+ const key = bindingIdentity({
1650
+ ingestToken: input.ingestToken,
1651
+ url,
1652
+ environment: input.environment,
1653
+ release,
1654
+ sampledMeasurementFormat
1655
+ });
1656
+ const existing = Reflect.get(globalThis, SLOT);
1657
+ if (isRuntime(existing)) {
1658
+ if (existing.identity !== key) {
1659
+ warnIncompatible(existing);
1660
+ return void 0;
1661
+ }
1662
+ existing.refs += 1;
1663
+ return { collector: existing.collector, exporter: existing.exporter };
1664
+ }
1665
+ const bindings2 = createBindings({
1666
+ release,
1667
+ ingestToken: input.ingestToken,
1668
+ url,
1669
+ environment: input.environment,
1670
+ fetch: input.fetch,
1671
+ sampledMeasurementFormat
1672
+ });
1673
+ Reflect.set(globalThis, SLOT, {
1674
+ ...bindings2,
1675
+ refs: 1,
1676
+ identity: key,
1677
+ warnedMismatch: false
1678
+ });
1679
+ return bindings2;
1680
+ };
1681
+ var releaseExecutionMetricsBindings = async (bindings2) => {
1682
+ if (!bindings2 || releasedHandles.has(bindings2)) return;
1683
+ releasedHandles.add(bindings2);
1684
+ const existing = Reflect.get(globalThis, SLOT);
1685
+ if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
1686
+ existing.refs -= 1;
1687
+ if (existing.refs > 0) return;
1688
+ Reflect.deleteProperty(globalThis, SLOT);
1689
+ }
1690
+ await bindings2.exporter.close();
1691
+ };
1692
+
1693
+ // src/execution-recorder/execution-recorder.ts
1694
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
1695
+ import {
1696
+ functionMetricsTraceDeclaration as functionMetricsTraceDeclaration3,
1697
+ rasputinOmitted,
1698
+ rasputinTagKind,
1699
+ runtimeFunctionId as runtimeFunctionId3
1700
+ } from "@rasputin-ai/core";
1701
+
1702
+ // src/function-metrics/create-metrics-only-runtime.ts
1703
+ import { AsyncLocalStorage } from "node:async_hooks";
1704
+ import {
1705
+ functionMetricsTraceDeclaration as functionMetricsTraceDeclaration2,
1706
+ runtimeFunctionId as runtimeFunctionId2
1707
+ } from "@rasputin-ai/core";
1708
+
1709
+ // src/execution-recorder/error-observation.ts
1710
+ var bindings = /* @__PURE__ */ new WeakMap();
1711
+ var mintErrorObservation = (binding) => {
1712
+ const observation = Object.freeze(/* @__PURE__ */ Object.create(null));
1713
+ bindings.set(observation, binding);
1714
+ return observation;
1715
+ };
1716
+ var bindingForObservation = (value) => {
1717
+ if (typeof value !== "object" || value === null) return void 0;
1718
+ return bindings.get(value);
1719
+ };
1720
+ var inertErrorObservation = () => {
1721
+ return Object.freeze(/* @__PURE__ */ Object.create(null));
1722
+ };
1723
+
1724
+ // src/execution-recorder/execution-identity.ts
1725
+ var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
1726
+ var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
1727
+ var trimmed = (value) => typeof value === "string" ? value.trim() : "";
1728
+ var boundedKey = (key) => {
1729
+ return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
1730
+ };
1731
+ var executionTypeKey = (metadata) => {
1732
+ if (metadata.kind === "http") {
1733
+ const method = trimmed(metadata.request?.method).toUpperCase();
1734
+ const route = trimmed(metadata.request?.route);
1735
+ if (!method || !route) return void 0;
1736
+ if (route.includes("?") || route.includes("://")) return void 0;
1737
+ return boundedKey(`http:${method}:${route}`);
1738
+ }
1739
+ if (!NAMED_KINDS.has(metadata.kind)) return void 0;
1740
+ const name = trimmed(metadata.name);
1741
+ if (!name) return void 0;
1742
+ return boundedKey(`${metadata.kind}:${name}`);
1743
+ };
1744
+ var isHttpClientErrorStatus = (status) => {
1745
+ return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
1746
+ };
1747
+ var isHttpServerErrorStatus = (status) => {
1748
+ return typeof status === "number" && Number.isFinite(status) && status >= 500;
1749
+ };
1750
+ var executionOutcomeFailed = (input) => input.hasError || input.runFailed || isHttpServerErrorStatus(input.status);
1751
+
1752
+ // src/execution-recorder/function-plan.ts
1753
+ var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
1754
+ var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
1755
+
1756
+ // src/runtime-timing/call-duration.ts
1757
+ var planCallDuration = (sampler, input) => {
1758
+ if (!sampler) return { selected: true, measure: true };
1759
+ if (!input.executionType) return { selected: false, measure: input.forceMeasure };
1760
+ const selected = sampler.take(input.executionType, input.callerFunctionId, input.functionId);
1761
+ return { selected, measure: selected || input.forceMeasure };
1762
+ };
1763
+
1764
+ // src/runtime-timing/execution-duration.ts
1765
+ var planExecutionDuration = (sampler, executionType) => {
1766
+ if (!sampler) return { selected: true };
1767
+ if (!executionType) return { selected: false };
1768
+ return { selected: sampler.takeExecution(executionType) };
1769
+ };
1770
+
1771
+ // src/function-metrics/function-metric-declaration-registry.ts
1772
+ var REGISTRY_SYMBOL = Symbol.for("rasputin.functionMetrics.declarations.v1");
1773
+ var getRegistry2 = () => {
1774
+ const existing = Reflect.get(globalThis, REGISTRY_SYMBOL);
1775
+ if (typeof existing === "object" && existing !== null) {
1776
+ const byRuntimeId = Reflect.get(existing, "byRuntimeId");
1777
+ if (byRuntimeId instanceof Map) return { byRuntimeId };
1778
+ }
1779
+ const registry = {
1780
+ byRuntimeId: /* @__PURE__ */ new Map()
1781
+ };
1782
+ Reflect.set(globalThis, REGISTRY_SYMBOL, registry);
1783
+ return registry;
1784
+ };
1785
+ var registerFunctionMetricDeclarations = (declarations) => {
1786
+ const { byRuntimeId } = getRegistry2();
1787
+ for (const declaration of declarations) {
1788
+ if (byRuntimeId.has(declaration.runtime_id)) continue;
1789
+ byRuntimeId.set(declaration.runtime_id, declaration);
1790
+ }
1791
+ };
1792
+ var functionMetricDeclarationFor = (runtimeId) => getRegistry2().byRuntimeId.get(runtimeId);
1793
+
1794
+ // src/function-metrics/intern-prepared-metrics.ts
1795
+ import {
1796
+ functionMetricsTraceDeclaration
1797
+ } from "@rasputin-ai/core";
1798
+ var declarationForPreparedPlan = (plan) => {
1799
+ if (plan.excluded) return void 0;
1800
+ const declaration = plan.metricsDeclaration ?? functionMetricDeclarationFor(plan.functionId) ?? functionMetricsTraceDeclaration({
1801
+ runtimeId: plan.functionId
1802
+ });
1803
+ plan.metricsDeclaration = declaration;
1804
+ return declaration;
1805
+ };
1806
+ var internPreparedMetrics = (collector, plan) => {
1807
+ if (plan.excluded) return void 0;
1808
+ if (plan.metricsHandle !== void 0) return plan.metricsHandle;
1809
+ const declaration = declarationForPreparedPlan(plan);
1810
+ const handle = collector.internDeclaration(declaration);
1811
+ if (handle !== void 0) plan.metricsHandle = handle;
1812
+ return handle;
1813
+ };
1814
+
1815
+ // src/function-metrics/settle-function-metrics.ts
1816
+ var finishMetricsCall = (collector, functionHandle, executionHandle, failed, timing) => {
1817
+ try {
1818
+ collector.finishCall(functionHandle, executionHandle, failed, timing);
1819
+ } catch {
1820
+ }
1821
+ };
1822
+ var thenOf = (value) => {
1823
+ try {
1824
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
1825
+ return void 0;
1826
+ }
1827
+ if (!("then" in value)) return void 0;
1828
+ const then = value.then;
1829
+ if (typeof then !== "function") return void 0;
1830
+ return (onFulfilled, onRejected) => {
1831
+ Reflect.apply(then, value, [onFulfilled, onRejected]);
1832
+ };
1833
+ } catch {
1834
+ return void 0;
1835
+ }
1836
+ };
1837
+ var tryCallClock = () => {
1838
+ try {
1839
+ return process.hrtime.bigint();
1840
+ } catch {
1841
+ return void 0;
1842
+ }
1843
+ };
1844
+ var startMetricsCall = (collector, functionHandle, executionHandle, options) => {
1845
+ if (!collector || functionHandle === void 0) return void 0;
1846
+ try {
1847
+ return collector.startCall(functionHandle, executionHandle, options);
1848
+ } catch {
1849
+ return void 0;
1850
+ }
1851
+ };
1852
+ var completeMetricsResult = (collector, functionHandle, executionHandle, value, timing, onSettled) => {
1853
+ const then = thenOf(value);
1854
+ if (!then) {
1855
+ finishMetricsCall(collector, functionHandle, executionHandle, false, timing);
1856
+ return;
1857
+ }
1858
+ let completed = false;
1859
+ const complete = (failed) => {
1860
+ if (completed) return;
1861
+ completed = true;
1862
+ const endedNs = timing !== void 0 ? tryCallClock() : void 0;
1863
+ finishMetricsCall(
1864
+ collector,
1865
+ functionHandle,
1866
+ executionHandle,
1867
+ failed,
1868
+ timing === void 0 ? void 0 : { startedNs: timing.startedNs, endedNs }
1869
+ );
1870
+ try {
1871
+ onSettled?.(endedNs);
1872
+ } catch {
1873
+ }
1874
+ };
1875
+ try {
1876
+ then(
1877
+ () => complete(false),
1878
+ () => complete(true)
1879
+ );
1880
+ } catch {
1881
+ complete(true);
1882
+ }
1883
+ };
1884
+
1885
+ // src/function-metrics/create-metrics-only-runtime.ts
1886
+ var emptyStats = () => ({
1887
+ functionCallsObserved: 0,
1888
+ functionCallsCaptured: 0,
1889
+ functionCallsExcluded: 0,
1890
+ serializedValues: 0,
1891
+ serializedValueNodes: 0,
1892
+ serializedValueBytes: 0,
1893
+ errorSnapshots: 0,
1894
+ successfulExecutionsDiscarded: 0,
1895
+ truncatedEvents: 0,
1896
+ repeatedCallsSuppressed: 0,
1897
+ activeExecutions: 0,
1898
+ peakActiveExecutions: 0,
1899
+ activeEstimatedBytes: 0,
1900
+ peakActiveEstimatedBytes: 0,
1901
+ memoryPressureExecutions: 0,
1902
+ memoryPressureDegradations: 0,
1903
+ valuesDroppedByMemoryBudget: 0,
1904
+ eventsDroppedByMemoryBudget: 0,
1905
+ partialErrorSnapshots: 0,
1906
+ measuredExecutions: 0,
1907
+ totalInlineWallTimeMs: 0,
1908
+ maxInlineWallTimeMs: 0,
1909
+ journalPoolHits: 0,
1910
+ journalPoolMisses: 0,
1911
+ journalPoolSize: 0,
1912
+ journalAllocatedCapacity: 0,
1913
+ attributionDegradations: 0,
1914
+ adaptiveLightExecutions: 0,
1915
+ adaptiveFullExecutions: 0,
1916
+ adaptiveActivations: 0,
1917
+ adaptiveNotifyFailures: 0,
1918
+ adaptiveRefreshFailures: 0,
1919
+ lastAdaptiveFailureKind: null
1920
+ });
1921
+ var metricsStorage = new AsyncLocalStorage();
1922
+ var tryCallClock2 = () => {
1923
+ try {
1924
+ return process.hrtime.bigint();
1925
+ } catch {
1926
+ return void 0;
1927
+ }
1928
+ };
1929
+ var mergeMetadata = (store, metadata) => {
1930
+ if (metadata.kind) store.execution.kind = metadata.kind;
1931
+ if (metadata.name !== void 0) store.execution.name = metadata.name;
1932
+ if (metadata.request) {
1933
+ store.execution.request = { ...store.execution.request, ...metadata.request };
1934
+ }
1935
+ };
1936
+ var definitionOf = (input) => {
1937
+ if (typeof input === "string")
1938
+ return { name: input, functionId: runtimeFunctionId2({ name: input }) };
1939
+ return input;
1940
+ };
1941
+ var bindExecutionHandle = (collector, store) => {
1942
+ if (!collector) return;
1943
+ store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
1944
+ };
1945
+ var bindExecutionMetricsIdentity = (collector, store) => {
1946
+ if (!collector || !store.executionMetrics) return;
1947
+ collector.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
1948
+ };
1949
+ var settleStarted = (collector, functionHandle, executionHandle, started, value, failed, endedNs) => {
1950
+ if (!started || functionHandle === void 0 || executionHandle === void 0) return;
1951
+ const timing = started.measure ? { startedNs: started.startedNs, endedNs } : void 0;
1952
+ if (failed) {
1953
+ finishMetricsCall(collector, functionHandle, executionHandle, true, timing);
1954
+ return;
1955
+ }
1956
+ completeMetricsResult(collector, functionHandle, executionHandle, value, timing);
1957
+ };
1958
+ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1959
+ if (!collector) return callback();
1960
+ const duration = planCallDuration(durationSampler, {
1961
+ forceMeasure: false,
1962
+ executionType: store ? executionTypeKey(store.execution) : void 0,
1963
+ callerFunctionId: store?.currentFunctionId ?? "",
1964
+ functionId: plan.functionId
1965
+ });
1966
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
1967
+ const functionHandle = internPreparedMetrics(collector, plan);
1968
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
1969
+ measure: duration.selected,
1970
+ ...duration.selected ? { startedNs } : {}
1971
+ });
1972
+ const invoke = () => {
1973
+ try {
1974
+ const result = callback();
1975
+ settleStarted(
1976
+ collector,
1977
+ functionHandle,
1978
+ store?.executionHandle,
1979
+ started,
1980
+ result,
1981
+ false,
1982
+ started?.measure && !(result instanceof Promise) ? tryCallClock2() : void 0
1983
+ );
1984
+ return result;
1985
+ } catch (error) {
1986
+ settleStarted(
1987
+ collector,
1988
+ functionHandle,
1989
+ store?.executionHandle,
1990
+ started,
1991
+ error,
1992
+ true,
1993
+ started?.measure ? tryCallClock2() : void 0
1994
+ );
1995
+ throw error;
1996
+ }
1997
+ };
1998
+ if (!store || !durationSampler) return invoke();
1999
+ return metricsStorage.run({ ...store, currentFunctionId: plan.functionId }, invoke);
2000
+ };
2001
+ var metricsHandle = (collector, durationSampler, plan, store) => {
2002
+ if (!collector) return passthroughHandle();
2003
+ const duration = planCallDuration(durationSampler, {
2004
+ forceMeasure: false,
2005
+ executionType: store ? executionTypeKey(store.execution) : void 0,
2006
+ callerFunctionId: store?.currentFunctionId ?? "",
2007
+ functionId: plan.functionId
2008
+ });
2009
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
2010
+ const functionHandle = internPreparedMetrics(collector, plan);
2011
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
2012
+ measure: duration.selected,
2013
+ ...duration.selected ? { startedNs } : {}
2014
+ });
2015
+ if (!started || functionHandle === void 0 || store?.executionHandle === void 0) {
2016
+ return passthroughHandle();
2017
+ }
2018
+ const executionHandle = store.executionHandle;
2019
+ let failed = false;
2020
+ let settled = false;
2021
+ let previousFunctionId = store.currentFunctionId;
2022
+ let callerClaimed = false;
2023
+ const claimCaller = () => {
2024
+ if (callerClaimed || !durationSampler) return;
2025
+ previousFunctionId = store.currentFunctionId;
2026
+ store.currentFunctionId = plan.functionId;
2027
+ callerClaimed = true;
2028
+ };
2029
+ const releaseCaller = () => {
2030
+ if (!callerClaimed) return;
2031
+ callerClaimed = false;
2032
+ if (previousFunctionId === void 0) delete store.currentFunctionId;
2033
+ else store.currentFunctionId = previousFunctionId;
2034
+ };
2035
+ claimCaller();
2036
+ return {
2037
+ leave: (value) => value,
2038
+ fail: () => {
2039
+ failed = true;
2040
+ },
2041
+ end: () => {
2042
+ if (settled) return;
2043
+ settled = true;
2044
+ releaseCaller();
2045
+ const endedNs = started.measure ? tryCallClock2() : void 0;
2046
+ finishMetricsCall(
2047
+ collector,
2048
+ functionHandle,
2049
+ executionHandle,
2050
+ failed,
2051
+ started.measure ? { startedNs: started.startedNs, endedNs } : void 0
2052
+ );
2053
+ },
2054
+ run: function __rasputinHandleRun__4(callback) {
2055
+ return runExactlyOnce((invoke) => invoke(), callback);
2056
+ },
2057
+ suspend: (value) => {
2058
+ releaseCaller();
2059
+ return value;
2060
+ },
2061
+ resume: (value) => {
2062
+ claimCaller();
2063
+ return value;
2064
+ }
2065
+ };
2066
+ };
2067
+ var createMetricsOnlyRuntime = (input) => {
2068
+ const collector = input.functionMetrics;
2069
+ const executionMetrics = input.executionMetrics;
2070
+ const durationSampler = input.durationSampler;
2071
+ const preparedModules = /* @__PURE__ */ new WeakMap();
2072
+ let nextRuntimePlanId = 1;
2073
+ const currentStore = () => metricsStorage.getStore();
2074
+ const planFor = (definition) => ({
2075
+ runtimePlanId: nextRuntimePlanId++,
2076
+ definition,
2077
+ functionId: definition.functionId,
2078
+ excluded: false,
2079
+ estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
2080
+ omitCallValues: false,
2081
+ metricsDeclaration: functionMetricDeclarationFor(definition.functionId) ?? functionMetricsTraceDeclaration2({
2082
+ runtimeId: definition.functionId
2083
+ })
2084
+ });
2085
+ const prepareEncoded = (plans) => {
2086
+ const cached = preparedModules.get(plans);
2087
+ if (cached) return cached;
2088
+ const prepared = plans.map((encoded) => {
2089
+ const definition = definitionFromEncodedPlan(encoded);
2090
+ return {
2091
+ ...planFor(definition),
2092
+ omitCallValues: encodedPlanOmitsCallValues(encoded),
2093
+ metricsDeclaration: functionMetricDeclarationFor(definition.functionId)
2094
+ };
2095
+ });
2096
+ preparedModules.set(plans, prepared);
2097
+ return prepared;
2098
+ };
2099
+ const runPrepared = (plan, _args, callback) => runWithMetrics(collector, durationSampler, plan, currentStore(), callback);
2100
+ function trace(input2, fn) {
2101
+ const definition = typeof input2 === "string" ? definitionOf(input2) : { ...input2, functionId: runtimeFunctionId2(input2) };
2102
+ const plan = planFor(definition);
2103
+ return function __rasputinHandleRun__4(...args) {
2104
+ if (new.target) {
2105
+ throw new TypeError("execution.trace() wraps function calls, not constructors");
2106
+ }
2107
+ return runPrepared(plan, args, () => fn.apply(this, args));
2108
+ };
2109
+ }
2110
+ const finishScope = (store, next) => {
2111
+ if (next) {
2112
+ mergeMetadata(store, next);
2113
+ bindExecutionHandle(collector, store);
2114
+ bindExecutionMetricsIdentity(executionMetrics, store);
2115
+ }
2116
+ if (!executionMetrics || !store.executionMetrics) return;
2117
+ if (store.executionMetrics.finished) return;
2118
+ const endedNs = tryCallClock2();
2119
+ const executionKey = executionTypeKey(store.execution);
2120
+ bindExecutionMetricsIdentity(executionMetrics, store);
2121
+ executionMetrics.finishExecution(store.executionMetrics, {
2122
+ failed: executionOutcomeFailed({
2123
+ hasError: store.hasError,
2124
+ runFailed: store.runFailed,
2125
+ status: store.execution.request?.status
2126
+ }),
2127
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
2128
+ startedNs: store.startedAtNs,
2129
+ ...endedNs === void 0 ? {} : { endedNs }
2130
+ });
2131
+ };
2132
+ return {
2133
+ createScope: (metadata) => {
2134
+ const store = {
2135
+ execution: {
2136
+ ...metadata,
2137
+ ...metadata.request ? { request: { ...metadata.request } } : {}
2138
+ },
2139
+ executionHandle: void 0,
2140
+ startedAtNs: tryCallClock2() ?? 0n,
2141
+ hasError: false,
2142
+ runFailed: false
2143
+ };
2144
+ bindExecutionHandle(collector, store);
2145
+ if (executionMetrics) {
2146
+ store.executionMetrics = executionMetrics.createState();
2147
+ bindExecutionMetricsIdentity(executionMetrics, store);
2148
+ }
2149
+ return {
2150
+ run: (callback) => metricsStorage.run(store, () => {
2151
+ try {
2152
+ return callback();
2153
+ } catch (error) {
2154
+ store.runFailed = true;
2155
+ throw error;
2156
+ }
2157
+ }),
2158
+ getErrorState: () => void 0,
2159
+ observeError: () => {
2160
+ store.hasError = true;
2161
+ return inertErrorObservation();
2162
+ },
2163
+ finish: (next) => finishScope(store, next),
2164
+ mergeMetadata: (next) => {
2165
+ mergeMetadata(store, next);
2166
+ bindExecutionHandle(collector, store);
2167
+ bindExecutionMetricsIdentity(executionMetrics, store);
2168
+ }
2169
+ };
2170
+ },
2171
+ getErrorState: () => void 0,
2172
+ runFunction: (definition, args, callback) => runPrepared(planFor(definitionOf(definition)), args, callback),
2173
+ runFunctionPlans: (plans, planIndex, args, callback) => {
2174
+ const plan = prepareEncoded(plans)[planIndex];
2175
+ return plan ? runPrepared(plan, args, callback) : callback();
2176
+ },
2177
+ prepareFunctionPlans: (plans) => prepareEncoded(plans),
2178
+ runPreparedFunction: runPrepared,
2179
+ enterPreparedFunction: (plan) => metricsHandle(collector, durationSampler, plan, currentStore()),
2180
+ trace,
2181
+ getStats: () => emptyStats(),
2182
+ close: () => {
2183
+ durationSampler?.stop();
2184
+ }
2185
+ };
2186
+ };
2187
+
2188
+ // src/execution-recorder/adaptive-recording-options.ts
2189
+ var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
2190
+ var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
2191
+ var MAX_FULL_CAPTURE_DURATION_MS = 7 * 24 * 60 * 60 * 1e3;
2192
+ var sanitizeFullCaptureDurationMs = (value) => {
2193
+ if (typeof value !== "number" || !Number.isFinite(value)) {
2194
+ return DEFAULT_FULL_CAPTURE_DURATION_MS;
2195
+ }
2196
+ return Math.min(
2197
+ MAX_FULL_CAPTURE_DURATION_MS,
2198
+ Math.max(MIN_FULL_CAPTURE_DURATION_MS, Math.floor(value))
2199
+ );
2200
+ };
2201
+
2202
+ // src/execution-recorder/execution-journal.ts
2203
+ var KIND_ENTER = 1;
2204
+ var KIND_EXIT = 2;
2205
+ var KIND_THROW = 3;
2206
+ var KIND_SUPPRESSED = 4;
2207
+ var ARGS_OMITTED = Symbol("rasputin.argsOmitted");
2208
+ var NO_PARENT = 4294967295;
2209
+ var NO_SUPPRESSION = 4294967295;
2210
+ var TIMING_UNAVAILABLE = -1n;
2211
+ var MAX_POOLED_JOURNALS = 8;
2212
+ var MAX_POOLED_JOURNAL_CAPACITY = 4096;
2213
+ var INITIAL_JOURNAL_STORAGE = 32;
2214
+ var BYTES_PER_EVENT = Uint8Array.BYTES_PER_ELEMENT + Uint32Array.BYTES_PER_ELEMENT * 4 + BigInt64Array.BYTES_PER_ELEMENT * 2;
2215
+ var DEFAULT_MAX_EVENTS_PER_EXECUTION = 1500;
2216
+ var MAX_JOURNAL_EVENTS = 16384;
2217
+ var elapsedMs = (startedAtNs, endedAtNs) => Number(endedAtNs - startedAtNs) / 1e6;
2218
+ var roundedMilliseconds = (nanoseconds) => Math.round(Number(nanoseconds) / 1e6 * 1e4) / 1e4;
2219
+ var relativeMs = (relativeNs) => Number(relativeNs) / 1e6;
2220
+ var measuredRelativeMs = (relativeNs) => relativeNs === TIMING_UNAVAILABLE ? void 0 : relativeMs(relativeNs);
2221
+ var sanitizeJournalCapacity = (value) => {
2222
+ const requested = value ?? DEFAULT_MAX_EVENTS_PER_EXECUTION;
2223
+ if (!Number.isFinite(requested)) return DEFAULT_MAX_EVENTS_PER_EXECUTION;
2224
+ return Math.min(MAX_JOURNAL_EVENTS, Math.max(2, Math.floor(requested)));
2225
+ };
2226
+ var ExecutionJournal = class {
2227
+ dropped = 0;
2228
+ allocatedBytes = 0;
2229
+ onGrow;
2230
+ length = 0;
2231
+ kind = new Uint8Array(0);
2232
+ planId = new Uint32Array(0);
2233
+ callId = new Uint32Array(0);
2234
+ parentCallId = new Uint32Array(0);
2235
+ timestampNs = new BigInt64Array(0);
2236
+ durationNs = new BigInt64Array(0);
2237
+ suppressionIndex = new Uint32Array(0);
2238
+ payloads = [];
2239
+ suppressions = [];
2240
+ openCallIds = /* @__PURE__ */ new Set();
2241
+ notedPlanIds = [];
2242
+ notedPlanSet = /* @__PURE__ */ new Set();
2243
+ maxCapacity;
2244
+ constructor(capacity) {
2245
+ this.maxCapacity = sanitizeJournalCapacity(capacity);
2246
+ this.reallocate(Math.min(this.maxCapacity, INITIAL_JOURNAL_STORAGE));
2247
+ }
2248
+ get capacity() {
839
2249
  return this.maxCapacity;
840
2250
  }
841
2251
  get hasOpenCalls() {
@@ -886,6 +2296,15 @@ var ExecutionJournal = class {
886
2296
  }
887
2297
  this.openCallIds.delete(callId);
888
2298
  }
2299
+ setCallTiming(callId, timestampNs, durationNs) {
2300
+ for (let index = this.length - 1; index >= 0; index--) {
2301
+ if (this.callId[index] !== callId) continue;
2302
+ if (this.kind[index] !== KIND_EXIT && this.kind[index] !== KIND_THROW) continue;
2303
+ this.timestampNs[index] = timestampNs;
2304
+ this.durationNs[index] = durationNs;
2305
+ return;
2306
+ }
2307
+ }
889
2308
  dropCall() {
890
2309
  this.dropped += 2;
891
2310
  }
@@ -1188,10 +2607,6 @@ var ExecutionJournalPool = class {
1188
2607
  }
1189
2608
  };
1190
2609
 
1191
- // src/execution-recorder/function-plan.ts
1192
- var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
1193
- var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
1194
-
1195
2610
  // src/execution-recorder/publish-runtime-state.ts
1196
2611
  var measured = (value) => typeof value === "number";
1197
2612
  var eventsAreFullyTimed = (events) => {
@@ -2690,7 +4105,7 @@ var manualFunctionDefinition = (value) => {
2690
4105
  ...located?.[4] ? { column: Number(located[4]) } : {}
2691
4106
  } : void 0;
2692
4107
  const definition = { name, ...source ? { source } : {} };
2693
- return { ...definition, functionId: runtimeFunctionId2(definition) };
4108
+ return { ...definition, functionId: runtimeFunctionId3(definition) };
2694
4109
  };
2695
4110
  var normalizeFunctionDefinition = (value) => typeof value === "string" ? manualFunctionDefinition(value) : value;
2696
4111
  var elapsedMs2 = (startedAtNs, endedAtNs = process.hrtime.bigint()) => Number(endedAtNs - startedAtNs) / 1e6;
@@ -2731,7 +4146,7 @@ var observeRecordedCallback = function __rasputinHandleRun__3(recording, recorde
2731
4146
  recordExitWork(phaseTimingEnabled ? process.hrtime.bigint() : recorderStartedAtNs);
2732
4147
  return result;
2733
4148
  };
2734
- var emptyStats = {
4149
+ var emptyStats2 = {
2735
4150
  functionCallsObserved: 0,
2736
4151
  functionCallsCaptured: 0,
2737
4152
  functionCallsExcluded: 0,
@@ -2792,7 +4207,7 @@ var noOpExecution = {
2792
4207
  resume: (value) => value
2793
4208
  }),
2794
4209
  trace: (_functionId, fn) => fn,
2795
- getStats: () => ({ ...emptyStats }),
4210
+ getStats: () => ({ ...emptyStats2 }),
2796
4211
  close: () => {
2797
4212
  }
2798
4213
  };
@@ -2826,16 +4241,50 @@ var newSuppression = (group, parentCallId, startedAtNs, endedAtNs, timed) => {
2826
4241
  var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
2827
4242
  var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
2828
4243
  var createExecutionRecorder = (options, hooks = {}) => {
2829
- if (!options?.enabled) return noOpExecution;
4244
+ if (!options?.enabled) {
4245
+ return hooks.functionMetrics || hooks.executionMetrics ? createMetricsOnlyRuntime({
4246
+ functionMetrics: hooks.functionMetrics,
4247
+ executionMetrics: hooks.executionMetrics,
4248
+ durationSampler: hooks.durationSampler
4249
+ }) : noOpExecution;
4250
+ }
4251
+ const functionMetrics = hooks.functionMetrics;
4252
+ const executionMetrics = hooks.executionMetrics;
4253
+ const durationSampler = hooks.durationSampler;
4254
+ const bindMetricsExecution = (recording) => {
4255
+ if (!functionMetrics) return;
4256
+ recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
4257
+ executionTypeKey(recording.execution)
4258
+ );
4259
+ };
4260
+ const bindExecutionMetricsIdentity2 = (recording) => {
4261
+ if (!executionMetrics || !recording.executionMetrics) return;
4262
+ executionMetrics.bindIdentity(
4263
+ recording.executionMetrics,
4264
+ executionTypeKey(recording.execution)
4265
+ );
4266
+ };
2830
4267
  warnIfMissingAsyncContextFrame();
2831
4268
  const adaptiveEnabled = options.adaptive?.enabled === true;
2832
4269
  const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
2833
4270
  options.adaptive?.fullCaptureDurationMs
2834
4271
  );
2835
- const durationSamplingEnabled = adaptiveEnabled && sanitizeDynamicDurationSampling(options.adaptive?.dynamicDurationSampling);
4272
+ const trackCallers = durationSampler !== void 0;
2836
4273
  const readCallClock = () => process.hrtime.bigint();
4274
+ const tryCallClock3 = () => {
4275
+ try {
4276
+ return readCallClock();
4277
+ } catch {
4278
+ return void 0;
4279
+ }
4280
+ };
4281
+ const invocationStart = (measure) => {
4282
+ if (!measure) return { timed: false, startedAtNs: 0n };
4283
+ const startedAtNs = tryCallClock3();
4284
+ if (startedAtNs === void 0) return { timed: false, startedAtNs: 0n };
4285
+ return { timed: true, startedAtNs };
4286
+ };
2837
4287
  const nowMs = () => hooks.nowMs?.() ?? Date.now();
2838
- const durationSamples = durationSamplingEnabled ? createDynamicDurationSampleBuckets({ nowMs }) : void 0;
2839
4288
  const localActivations = /* @__PURE__ */ new Map();
2840
4289
  const policySnapshotFor = () => hooks.policySnapshot?.() ?? localActivations;
2841
4290
  const keyIsActive = (snapshot, key, atMs) => {
@@ -2848,7 +4297,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
2848
4297
  if (!key) return false;
2849
4298
  return keyIsActive(snapshot, key, atMs);
2850
4299
  };
2851
- const storage = new AsyncLocalStorage();
4300
+ const storage = new AsyncLocalStorage2();
2852
4301
  const currentStore = () => {
2853
4302
  try {
2854
4303
  return storage.getStore();
@@ -3020,21 +4469,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
3020
4469
  }
3021
4470
  };
3022
4471
  const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
3023
- const durationSamplingApplies = (recording) => durationSamplingEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess;
3024
4472
  const callStoreFor = (store, functionId, callId) => {
3025
4473
  const next = { ...store, currentCallId: callId };
3026
- if (durationSamplingEnabled) next.currentFunctionId = functionId;
4474
+ if (trackCallers) next.currentFunctionId = functionId;
3027
4475
  return next;
3028
4476
  };
3029
4477
  const samplingStore = (store, functionId) => {
3030
- return durationSamplingEnabled ? { ...store, currentFunctionId: functionId } : store;
3031
- };
3032
- const decideCallTiming = (recording, plan, callerFunctionId) => {
3033
- if (!durationSamplingApplies(recording) || !durationSamples) return true;
3034
- const typeKey = executionTypeKey(recording.execution);
3035
- if (!typeKey) return true;
3036
- return durationSamples.take(typeKey, callerFunctionId ?? "", plan.functionId);
3037
- };
4478
+ return trackCallers ? { ...store, currentFunctionId: functionId } : store;
4479
+ };
4480
+ const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess);
4481
+ const planInvocationDuration = (recording, plan, callerFunctionId) => planCallDuration(durationSampler, {
4482
+ forceMeasure: recorderForceMeasure(recording),
4483
+ executionType: executionTypeKey(recording.execution),
4484
+ callerFunctionId: callerFunctionId ?? "",
4485
+ functionId: plan.functionId
4486
+ });
3038
4487
  const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
3039
4488
  const tryAdmitLiveSession = (recording) => {
3040
4489
  if (recording.retainSuccess || recording.finished) return;
@@ -3099,7 +4548,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
3099
4548
  functionId: definition.functionId,
3100
4549
  excluded: excludesSource(definition),
3101
4550
  estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
3102
- omitCallValues: false
4551
+ omitCallValues: false,
4552
+ metricsDeclaration: functionMetricDeclarationFor(definition.functionId)
3103
4553
  });
3104
4554
  internedPlans.set(definition.functionId, plan);
3105
4555
  return plan;
@@ -3117,7 +4567,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
3117
4567
  functionId: withParams.functionId,
3118
4568
  excluded: excludesSource(withParams),
3119
4569
  estimatedCallBytes: estimatedCallBytesFor(withParams.functionId),
3120
- omitCallValues: encodedPlanOmitsCallValues(encoded)
4570
+ omitCallValues: encodedPlanOmitsCallValues(encoded),
4571
+ metricsDeclaration: functionMetricDeclarationFor(withParams.functionId)
3121
4572
  });
3122
4573
  });
3123
4574
  preparedModules.set(plans, prepared);
@@ -3245,7 +4696,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3245
4696
  },
3246
4697
  functions: functions.slice(),
3247
4698
  events: fullyTimed ? asFullyTimedEvents(events) : events.slice(),
3248
- ...fullyTimed || !durationSamplingEnabled ? {} : { durationSampling: { policy: "progressive" } },
4699
+ ...fullyTimed || !durationSampler ? {} : { durationSampling: { policy: "progressive" } },
3249
4700
  ...truncated ? { truncated: { ...truncated } } : {},
3250
4701
  ...capture ? { capture: { ...capture } } : {}
3251
4702
  };
@@ -3515,7 +4966,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3515
4966
  }
3516
4967
  };
3517
4968
  };
3518
- const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs) => {
4969
+ const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
3519
4970
  if (!recording.journal) {
3520
4971
  return;
3521
4972
  }
@@ -3525,17 +4976,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
3525
4976
  const callId = ++recording.nextCallId;
3526
4977
  const capturedError = serializedError(recording, error, callId);
3527
4978
  const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3528
- const endedAtNs = readCallClock();
4979
+ const endedAtNs = timed ? completedAtNs : void 0;
3529
4980
  const droppedBefore = recording.journal.dropped;
3530
4981
  const retained = recording.journal.forceCompletedCall(
3531
4982
  plan.runtimePlanId,
3532
4983
  callId,
3533
4984
  parentCallId,
3534
- timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4985
+ timed && endedAtNs !== void 0 ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
3535
4986
  recordedArgs,
3536
4987
  KIND_THROW,
3537
- endedAtNs - recording.startedAtNs,
3538
- timed ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
4988
+ timed && endedAtNs !== void 0 ? endedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4989
+ timed && endedAtNs !== void 0 ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
3539
4990
  capturedError.value
3540
4991
  );
3541
4992
  if (retained) {
@@ -3567,6 +5018,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
3567
5018
  appendSuppressedPlaceholder(recording, suppressed);
3568
5019
  }
3569
5020
  };
5021
+ const addSuppressedDuration = (suppressed, startedAtNs, endedAtNs) => {
5022
+ if (!suppressed.firstTimed) {
5023
+ suppressed.firstTimestampNs = startedAtNs;
5024
+ suppressed.firstTimed = true;
5025
+ }
5026
+ suppressed.lastTimestampNs = endedAtNs;
5027
+ suppressed.lastTimed = true;
5028
+ suppressed.sampledDurationCount++;
5029
+ suppressed.sampledDurationNs += endedAtNs - startedAtNs;
5030
+ };
3570
5031
  const releaseJournalIfIdle = (recording) => {
3571
5032
  if (!recording.finished || recording.hasError || recording.inFlightCalls > 0) return;
3572
5033
  if (!recording.journal) return;
@@ -3636,7 +5097,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
3636
5097
  }
3637
5098
  const recorderStartedAtNs = process.hrtime.bigint();
3638
5099
  recording.finished = true;
3639
- if (metadata) mergeExecutionMetadata(recording.execution, metadata);
5100
+ if (metadata) {
5101
+ mergeExecutionMetadata(recording.execution, metadata);
5102
+ bindMetricsExecution(recording);
5103
+ bindExecutionMetricsIdentity2(recording);
5104
+ }
5105
+ if (executionMetrics && recording.executionMetrics) {
5106
+ const executionKey = executionTypeKey(recording.execution);
5107
+ bindExecutionMetricsIdentity2(recording);
5108
+ executionMetrics.finishExecution(recording.executionMetrics, {
5109
+ failed: executionOutcomeFailed({
5110
+ hasError: recording.hasError,
5111
+ runFailed: recording.runFailed === true,
5112
+ status: recording.execution.request?.status
5113
+ }),
5114
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
5115
+ startedNs: recording.startedAtNs,
5116
+ endedNs: recorderStartedAtNs
5117
+ });
5118
+ }
3640
5119
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3641
5120
  if (recording.runFailed && !recording.hasError) {
3642
5121
  retainFailure(recording);
@@ -3705,6 +5184,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
3705
5184
  sessionCaptureSnapshot
3706
5185
  };
3707
5186
  if (identityComplete) tryAdmitLiveSession(recording);
5187
+ bindMetricsExecution(recording);
5188
+ if (executionMetrics) {
5189
+ recording.executionMetrics = executionMetrics.createState();
5190
+ bindExecutionMetricsIdentity2(recording);
5191
+ }
3708
5192
  stats.activeExecutions++;
3709
5193
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3710
5194
  liveRecordings.push(recording);
@@ -3756,6 +5240,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
3756
5240
  try {
3757
5241
  mergeExecutionMetadata(recording.execution, nextMetadata);
3758
5242
  completeIdentityFromSnapshot(recording);
5243
+ bindMetricsExecution(recording);
5244
+ bindExecutionMetricsIdentity2(recording);
3759
5245
  } catch {
3760
5246
  }
3761
5247
  }
@@ -3772,9 +5258,57 @@ var createExecutionRecorder = (options, hooks = {}) => {
3772
5258
  }
3773
5259
  };
3774
5260
  const runPreparedFunctionFromStore = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5261
+ const duration = plan.excluded ? { selected: false, measure: false } : store ? planInvocationDuration(store.recording, plan, store.currentFunctionId) : { selected: false, measure: false };
5262
+ const startedNs = duration.measure ? tryCallClock3() : void 0;
5263
+ const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
5264
+ const executionHandle = store?.recording.metricsExecutionHandle;
5265
+ const metricsStart = startMetricsCall(functionMetrics, functionHandle, executionHandle, {
5266
+ measure: duration.selected,
5267
+ ...duration.selected ? { startedNs } : {}
5268
+ });
5269
+ const sharedClock = {
5270
+ start: startedNs,
5271
+ timed: startedNs !== void 0,
5272
+ selected: duration.selected
5273
+ };
5274
+ const applyRecorderEnd = (endedNs) => {
5275
+ if (endedNs === void 0) return;
5276
+ sharedClock.end = endedNs;
5277
+ sharedClock.applyEnd?.(endedNs);
5278
+ };
5279
+ const settle = (value, failed) => {
5280
+ const pending = !failed && value instanceof Promise;
5281
+ if (!pending && sharedClock.timed && sharedClock.end === void 0) {
5282
+ sharedClock.end = tryCallClock3();
5283
+ }
5284
+ if (!functionMetrics || !metricsStart || functionHandle === void 0 || executionHandle === void 0) {
5285
+ return;
5286
+ }
5287
+ const timing = sharedClock.selected ? { startedNs: sharedClock.start, endedNs: sharedClock.end } : void 0;
5288
+ if (failed) {
5289
+ finishMetricsCall(functionMetrics, functionHandle, executionHandle, true, timing);
5290
+ return;
5291
+ }
5292
+ completeMetricsResult(
5293
+ functionMetrics,
5294
+ functionHandle,
5295
+ executionHandle,
5296
+ value,
5297
+ timing,
5298
+ (endedNs) => {
5299
+ if (endedNs !== void 0) {
5300
+ applyRecorderEnd(endedNs);
5301
+ return;
5302
+ }
5303
+ if (!sharedClock.selected && sharedClock.timed) {
5304
+ applyRecorderEnd(tryCallClock3());
5305
+ }
5306
+ }
5307
+ );
5308
+ };
3775
5309
  let startedCallback = false;
3776
5310
  try {
3777
- return runPreparedFunctionFromStoreInner(
5311
+ const result = runPreparedFunctionFromStoreInner(
3778
5312
  store,
3779
5313
  plan,
3780
5314
  args,
@@ -3782,14 +5316,22 @@ var createExecutionRecorder = (options, hooks = {}) => {
3782
5316
  startedCallback = true;
3783
5317
  return callback();
3784
5318
  },
3785
- omitValues
5319
+ omitValues,
5320
+ sharedClock
3786
5321
  );
5322
+ settle(result, false);
5323
+ return result;
3787
5324
  } catch (error) {
3788
- if (startedCallback) throw error;
3789
- return callback();
5325
+ if (startedCallback) {
5326
+ settle(error, true);
5327
+ throw error;
5328
+ }
5329
+ const result = callback();
5330
+ settle(result, false);
5331
+ return result;
3790
5332
  }
3791
5333
  };
3792
- const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5334
+ const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues, sharedClock) {
3793
5335
  const omitCallValues = omitValues === true || plan.omitCallValues;
3794
5336
  if (!store) return callback();
3795
5337
  if (plan.disabled) {
@@ -3825,9 +5367,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
3825
5367
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
3826
5368
  } catch {
3827
5369
  }
3828
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
5370
+ const timed = sharedClock.timed;
5371
+ const startedAtNs = sharedClock.start ?? 0n;
3829
5372
  if (group.observedCalls > capturedCallLimitFor(recording)) {
3830
- const startedAtNs2 = timed ? readCallClock() : 0n;
3831
5373
  try {
3832
5374
  const result = runStore(
3833
5375
  samplingStore(store, plan.functionId),
@@ -3835,23 +5377,48 @@ var createExecutionRecorder = (options, hooks = {}) => {
3835
5377
  return callback();
3836
5378
  }
3837
5379
  );
3838
- recordSuppressedCall(
3839
- recording,
3840
- group,
3841
- parentCallId,
3842
- startedAtNs2,
3843
- timed ? readCallClock() : 0n,
3844
- timed
3845
- );
5380
+ if (result instanceof Promise) {
5381
+ recordSuppressedCall(recording, group, parentCallId, startedAtNs, 0n, false);
5382
+ if (timed) {
5383
+ const suppressed = group.suppressed;
5384
+ sharedClock.applyEnd = (endedNs) => {
5385
+ if (endedNs === void 0 || recording.finished || !suppressed || group.suppressed !== suppressed) {
5386
+ return;
5387
+ }
5388
+ addSuppressedDuration(suppressed, startedAtNs, endedNs);
5389
+ };
5390
+ }
5391
+ } else {
5392
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5393
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5394
+ recordSuppressedCall(
5395
+ recording,
5396
+ group,
5397
+ parentCallId,
5398
+ startedAtNs,
5399
+ endedAtNs ?? 0n,
5400
+ endedAtNs !== void 0
5401
+ );
5402
+ }
3846
5403
  settleInFlight(recording);
3847
5404
  return result;
3848
5405
  } catch (error) {
3849
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs2, error, timed);
5406
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5407
+ captureCompletedThrow(
5408
+ recording,
5409
+ plan,
5410
+ args,
5411
+ parentCallId,
5412
+ startedAtNs,
5413
+ error,
5414
+ timed,
5415
+ void 0,
5416
+ sharedClock.end
5417
+ );
3850
5418
  settleInFlight(recording);
3851
5419
  throw error;
3852
5420
  }
3853
5421
  }
3854
- const startedAtNs = timed ? readCallClock() : 0n;
3855
5422
  if (!journal) {
3856
5423
  memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes);
3857
5424
  return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
@@ -3880,7 +5447,18 @@ var createExecutionRecorder = (options, hooks = {}) => {
3880
5447
  callback,
3881
5448
  captureSuccess,
3882
5449
  (error) => {
3883
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs, error, timed);
5450
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5451
+ captureCompletedThrow(
5452
+ recording,
5453
+ plan,
5454
+ args,
5455
+ parentCallId,
5456
+ startedAtNs,
5457
+ error,
5458
+ timed,
5459
+ void 0,
5460
+ sharedClock.end
5461
+ );
3884
5462
  settleInFlight(recording);
3885
5463
  }
3886
5464
  );
@@ -3900,7 +5478,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3900
5478
  });
3901
5479
  }
3902
5480
  const callId = ++recording.nextCallId;
3903
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
5481
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
3904
5482
  const capturedArgs = enterPayload(recording, omitCallValues, args);
3905
5483
  try {
3906
5484
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -3926,7 +5504,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
3926
5504
  callback,
3927
5505
  (value) => {
3928
5506
  if (recording.journal) {
3929
- const endedAtNs = timed ? readCallClock() : void 0;
5507
+ const pending = value instanceof Promise;
5508
+ const endedAtNs = timed && !pending ? tryCallClock3() : void 0;
5509
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
3930
5510
  const returnValue = exitPayload(recording, omitCallValues, value);
3931
5511
  if (endedAtNs !== void 0) {
3932
5512
  recording.journal.finishCall(
@@ -3945,6 +5525,19 @@ var createExecutionRecorder = (options, hooks = {}) => {
3945
5525
  returnValue
3946
5526
  );
3947
5527
  }
5528
+ if (pending && timed) {
5529
+ const journal2 = recording.journal;
5530
+ sharedClock.applyEnd = (endedNs) => {
5531
+ if (endedNs === void 0 || recording.finished || recording.journal !== journal2) {
5532
+ return;
5533
+ }
5534
+ journal2.setCallTiming(
5535
+ callId,
5536
+ endedNs - recording.startedAtNs,
5537
+ endedNs - startedAtNs
5538
+ );
5539
+ };
5540
+ }
3948
5541
  stats.functionCallsCaptured++;
3949
5542
  }
3950
5543
  settleInFlight(recording);
@@ -3955,14 +5548,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
3955
5548
  return;
3956
5549
  }
3957
5550
  const capturedError = serializedError(recording, error, callId);
3958
- const endedAtNs = readCallClock();
3959
- recording.journal.finishCall(
3960
- KIND_THROW,
3961
- callId,
3962
- endedAtNs - recording.startedAtNs,
3963
- timed ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
3964
- capturedError.value
3965
- );
5551
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5552
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5553
+ if (endedAtNs !== void 0) {
5554
+ recording.journal.finishCall(
5555
+ KIND_THROW,
5556
+ callId,
5557
+ endedAtNs - recording.startedAtNs,
5558
+ endedAtNs - startedAtNs,
5559
+ capturedError.value
5560
+ );
5561
+ } else {
5562
+ recording.journal.finishCall(
5563
+ KIND_THROW,
5564
+ callId,
5565
+ TIMING_UNAVAILABLE,
5566
+ TIMING_UNAVAILABLE,
5567
+ capturedError.value
5568
+ );
5569
+ }
3966
5570
  stats.functionCallsCaptured++;
3967
5571
  capturedError.commit();
3968
5572
  settleInFlight(recording);
@@ -3991,16 +5595,24 @@ var createExecutionRecorder = (options, hooks = {}) => {
3991
5595
  this.group = group;
3992
5596
  this.captureDroppedThrow = captureDroppedThrow;
3993
5597
  this.callerClaimed = false;
5598
+ this.completedAtNs = void 0;
5599
+ this.metricsSelected = false;
5600
+ this.metricsOpen = false;
5601
+ this.metricsMeasure = false;
5602
+ this.metricsFailed = false;
5603
+ this.metricsFunctionHandle = 0;
5604
+ this.metricsExecutionHandle = 0;
5605
+ this.metricsStartedNs = void 0;
3994
5606
  }
3995
5607
  claimCaller() {
3996
- if (this.callerClaimed || !durationSamplingEnabled || !this.plan) return;
5608
+ if (this.callerClaimed || !trackCallers || !this.plan) return;
3997
5609
  if (this.activeStore !== this.parentStore) return;
3998
5610
  this.previousFunctionId = this.parentStore.currentFunctionId;
3999
5611
  this.parentStore.currentFunctionId = this.plan.functionId;
4000
5612
  this.callerClaimed = true;
4001
5613
  }
4002
5614
  reclaimCaller() {
4003
- if (!durationSamplingEnabled || !this.plan || this.activeStore !== this.parentStore) return;
5615
+ if (!trackCallers || !this.plan || this.activeStore !== this.parentStore) return;
4004
5616
  this.parentStore.currentFunctionId = this.plan.functionId;
4005
5617
  this.callerClaimed = true;
4006
5618
  }
@@ -4025,6 +5637,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
4025
5637
  try {
4026
5638
  if (this.status === "failed") return;
4027
5639
  this.status = "failed";
5640
+ this.metricsFailed = true;
5641
+ if (this.timed && this.completedAtNs === void 0) {
5642
+ this.completedAtNs = tryCallClock3();
5643
+ }
4028
5644
  if (this.mode === "captured") writeCapturedThrow(this, error);
4029
5645
  else if (this.mode === "suppressed" && this.plan) {
4030
5646
  captureCompletedThrow(
@@ -4035,7 +5651,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4035
5651
  this.startedAtNs,
4036
5652
  error,
4037
5653
  this.timed,
4038
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5654
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5655
+ this.completedAtNs
4039
5656
  );
4040
5657
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
4041
5658
  captureCompletedThrow(
@@ -4046,26 +5663,49 @@ var createExecutionRecorder = (options, hooks = {}) => {
4046
5663
  this.startedAtNs,
4047
5664
  error,
4048
5665
  this.timed,
4049
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5666
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5667
+ this.completedAtNs
4050
5668
  );
4051
5669
  }
4052
5670
  } catch {
4053
5671
  }
4054
5672
  }
4055
5673
  end() {
5674
+ let endedAtNs = this.completedAtNs;
5675
+ if (endedAtNs === void 0 && this.timed) {
5676
+ endedAtNs = tryCallClock3();
5677
+ this.completedAtNs = endedAtNs;
5678
+ }
5679
+ if (this.metricsOpen && functionMetrics) {
5680
+ this.metricsOpen = false;
5681
+ try {
5682
+ finishMetricsCall(
5683
+ functionMetrics,
5684
+ this.metricsFunctionHandle,
5685
+ this.metricsExecutionHandle,
5686
+ this.metricsFailed,
5687
+ this.metricsMeasure ? { startedNs: this.metricsStartedNs, endedNs: endedAtNs } : void 0
5688
+ );
5689
+ } catch {
5690
+ }
5691
+ }
4056
5692
  if (this.mode === "expired") return;
4057
5693
  try {
4058
5694
  if (this.status !== "failed") {
4059
5695
  if (this.mode === "captured") {
4060
- writeCapturedExit(this, this.status === "left" ? this.pendingReturn : void 0);
5696
+ writeCapturedExit(
5697
+ this,
5698
+ this.status === "left" ? this.pendingReturn : void 0,
5699
+ endedAtNs
5700
+ );
4061
5701
  } else if (this.mode === "suppressed" && this.group) {
4062
5702
  recordSuppressedCall(
4063
5703
  this.recording,
4064
5704
  this.group,
4065
5705
  this.parentCallId,
4066
5706
  this.startedAtNs,
4067
- this.timed ? readCallClock() : 0n,
4068
- this.timed
5707
+ endedAtNs ?? 0n,
5708
+ this.timed && endedAtNs !== void 0
4069
5709
  );
4070
5710
  } else if (this.mode === "dropped") {
4071
5711
  const droppedBefore = this.recording.journal?.dropped ?? 0;
@@ -4137,9 +5777,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4137
5777
  const expectStore = (frame, expected) => {
4138
5778
  if (currentStore() !== expected && frame.plan) degradeAttribution(frame.recording, frame.plan);
4139
5779
  };
4140
- const writeCapturedExit = (frame, value) => {
5780
+ const writeCapturedExit = (frame, value, completedAtNs) => {
4141
5781
  if (!frame.recording.journal) return;
4142
- const endedAtNs = frame.timed ? readCallClock() : void 0;
5782
+ const endedAtNs = frame.timed ? completedAtNs : void 0;
4143
5783
  const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
4144
5784
  if (endedAtNs !== void 0) {
4145
5785
  frame.recording.journal.finishCall(
@@ -4162,19 +5802,47 @@ var createExecutionRecorder = (options, hooks = {}) => {
4162
5802
  };
4163
5803
  const writeCapturedThrow = (frame, error) => {
4164
5804
  if (!frame.recording.journal) return;
4165
- const endedAtNs = readCallClock();
5805
+ const endedAtNs = frame.timed ? frame.completedAtNs : void 0;
4166
5806
  const capturedError = serializedError(frame.recording, error, frame.callId);
4167
- frame.recording.journal.finishCall(
4168
- KIND_THROW,
4169
- frame.callId,
4170
- endedAtNs - frame.recording.startedAtNs,
4171
- frame.timed ? endedAtNs - frame.startedAtNs : TIMING_UNAVAILABLE,
4172
- capturedError.value
4173
- );
5807
+ if (endedAtNs !== void 0) {
5808
+ frame.recording.journal.finishCall(
5809
+ KIND_THROW,
5810
+ frame.callId,
5811
+ endedAtNs - frame.recording.startedAtNs,
5812
+ endedAtNs - frame.startedAtNs,
5813
+ capturedError.value
5814
+ );
5815
+ } else {
5816
+ frame.recording.journal.finishCall(
5817
+ KIND_THROW,
5818
+ frame.callId,
5819
+ TIMING_UNAVAILABLE,
5820
+ TIMING_UNAVAILABLE,
5821
+ capturedError.value
5822
+ );
5823
+ }
4174
5824
  stats.functionCallsCaptured++;
4175
5825
  capturedError.commit();
4176
5826
  };
4177
- const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow) => {
5827
+ const armCallFrameMetrics = (frame, plan) => {
5828
+ if (!functionMetrics || plan.excluded) return;
5829
+ const functionHandle = internPreparedMetrics(functionMetrics, plan);
5830
+ const started = startMetricsCall(
5831
+ functionMetrics,
5832
+ functionHandle,
5833
+ frame.recording.metricsExecutionHandle,
5834
+ frame.metricsSelected ? { measure: true, startedNs: frame.timed ? frame.startedAtNs : void 0 } : { measure: false }
5835
+ );
5836
+ if (!started || functionHandle === void 0) return;
5837
+ const executionHandle = frame.recording.metricsExecutionHandle;
5838
+ if (executionHandle === void 0) return;
5839
+ frame.metricsOpen = true;
5840
+ frame.metricsMeasure = started.measure;
5841
+ frame.metricsFunctionHandle = functionHandle;
5842
+ frame.metricsExecutionHandle = executionHandle;
5843
+ frame.metricsStartedNs = started.startedNs;
5844
+ };
5845
+ const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected) => {
4178
5846
  const frame = new CallFrame(
4179
5847
  mode,
4180
5848
  recording,
@@ -4190,8 +5858,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
4190
5858
  group,
4191
5859
  captureDroppedThrow
4192
5860
  );
5861
+ frame.metricsSelected = selected;
4193
5862
  frame.claimCaller();
4194
5863
  enterStore(frame, parentStore);
5864
+ armCallFrameMetrics(frame, plan);
4195
5865
  return frame;
4196
5866
  };
4197
5867
  const enterPreparedFunctionFromStore = (store, plan, args, omitValues) => {
@@ -4202,8 +5872,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
4202
5872
  }
4203
5873
  if (store.recording.finished) {
4204
5874
  if (!store.recording.budgetExpired && !store.recording.evicted) return noopHandle2;
5875
+ const duration2 = planInvocationDuration(store.recording, plan, store.currentFunctionId);
5876
+ const start2 = invocationStart(duration2.measure);
4205
5877
  const expiredStore = { recording: store.recording };
4206
- return new CallFrame(
5878
+ const expired = new CallFrame(
4207
5879
  "expired",
4208
5880
  store.recording,
4209
5881
  expiredStore,
@@ -4212,12 +5884,15 @@ var createExecutionRecorder = (options, hooks = {}) => {
4212
5884
  EMPTY_ARGS,
4213
5885
  false,
4214
5886
  void 0,
4215
- 0n,
4216
- true,
5887
+ start2.startedAtNs,
5888
+ start2.timed,
4217
5889
  0,
4218
5890
  void 0,
4219
5891
  false
4220
5892
  );
5893
+ expired.metricsSelected = duration2.selected;
5894
+ armCallFrameMetrics(expired, plan);
5895
+ return expired;
4221
5896
  }
4222
5897
  stats.functionCallsObserved++;
4223
5898
  const recording = store.recording;
@@ -4225,6 +5900,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4225
5900
  const parentCallId = store.currentCallId;
4226
5901
  if (skipCapture(store, plan)) {
4227
5902
  stats.functionCallsExcluded++;
5903
+ const excludedDuration = plan.excluded ? { selected: false, measure: false } : planInvocationDuration(recording, plan, store.currentFunctionId);
5904
+ const start2 = invocationStart(excludedDuration.measure);
4228
5905
  const excludedStore = { ...store, suppressCapture: true };
4229
5906
  const frame = new CallFrame(
4230
5907
  "excluded",
@@ -4235,13 +5912,15 @@ var createExecutionRecorder = (options, hooks = {}) => {
4235
5912
  EMPTY_ARGS,
4236
5913
  false,
4237
5914
  void 0,
4238
- 0n,
4239
- true,
5915
+ start2.startedAtNs,
5916
+ start2.timed,
4240
5917
  0,
4241
5918
  void 0,
4242
5919
  false
4243
5920
  );
5921
+ frame.metricsSelected = excludedDuration.selected;
4244
5922
  enterStore(frame, excludedStore);
5923
+ armCallFrameMetrics(frame, plan);
4245
5924
  return frame;
4246
5925
  }
4247
5926
  recording.inFlightCalls++;
@@ -4252,8 +5931,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
4252
5931
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
4253
5932
  } catch {
4254
5933
  }
4255
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
4256
- const startedAtNs = timed ? readCallClock() : 0n;
5934
+ const duration = planInvocationDuration(recording, plan, store.currentFunctionId);
5935
+ const start = invocationStart(duration.measure);
5936
+ const timed = start.timed;
5937
+ const startedAtNs = start.startedAtNs;
4257
5938
  const parentStore = store;
4258
5939
  const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
4259
5940
  if (group.observedCalls > capturedCallLimitFor(recording)) {
@@ -4268,7 +5949,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4268
5949
  startedAtNs,
4269
5950
  timed,
4270
5951
  group,
4271
- false
5952
+ false,
5953
+ duration.selected
4272
5954
  );
4273
5955
  }
4274
5956
  if (!journal) {
@@ -4284,7 +5966,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4284
5966
  startedAtNs,
4285
5967
  timed,
4286
5968
  group,
4287
- false
5969
+ false,
5970
+ duration.selected
4288
5971
  );
4289
5972
  }
4290
5973
  if (!journal.canStartCall()) {
@@ -4299,7 +5982,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4299
5982
  startedAtNs,
4300
5983
  timed,
4301
5984
  group,
4302
- true
5985
+ true,
5986
+ duration.selected
4303
5987
  );
4304
5988
  }
4305
5989
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
@@ -4314,11 +5998,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
4314
5998
  startedAtNs,
4315
5999
  timed,
4316
6000
  group,
4317
- false
6001
+ false,
6002
+ duration.selected
4318
6003
  );
4319
6004
  }
4320
6005
  const callId = ++recording.nextCallId;
4321
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
6006
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
4322
6007
  const capturedArgs = enterPayload(recording, omitCallValues, args);
4323
6008
  try {
4324
6009
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -4335,7 +6020,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4335
6020
  startedAtNs,
4336
6021
  timed,
4337
6022
  group,
4338
- false
6023
+ false,
6024
+ duration.selected
4339
6025
  );
4340
6026
  }
4341
6027
  const callStore = callStoreFor(store, plan.functionId, callId);
@@ -4354,7 +6040,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4354
6040
  group,
4355
6041
  false
4356
6042
  );
6043
+ captured.metricsSelected = duration.selected;
4357
6044
  enterStore(captured, callStore);
6045
+ armCallFrameMetrics(captured, plan);
4358
6046
  return captured;
4359
6047
  };
4360
6048
  const runPreparedFunction = (plan, args, callback, omitValues) => {
@@ -4395,8 +6083,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
4395
6083
  };
4396
6084
  const prepareFunctionPlans = (plans) => preparedPlansFor(plans);
4397
6085
  function trace(input, fn) {
4398
- const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId: runtimeFunctionId2(input) };
6086
+ const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId: runtimeFunctionId3(input) };
4399
6087
  const plan = preparePlan(definition);
6088
+ plan.metricsDeclaration ??= functionMetricsTraceDeclaration3({
6089
+ runtimeId: definition.functionId
6090
+ });
4400
6091
  return function __rasputinHandleRun__4(...args) {
4401
6092
  if (new.target) {
4402
6093
  throw new TypeError("execution.trace() wraps function calls, not constructors");
@@ -4419,7 +6110,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4419
6110
  enterPreparedFunction,
4420
6111
  trace,
4421
6112
  close: () => {
4422
- durationSamples?.stop();
6113
+ durationSampler?.stop();
4423
6114
  },
4424
6115
  getStats: () => ({
4425
6116
  ...stats,
@@ -4476,14 +6167,14 @@ var installAutomaticExecutionRuntime = (execution) => {
4476
6167
  // src/execution-recorder/bind-adaptive-recorder.ts
4477
6168
  import {
4478
6169
  resolveClientActivation,
4479
- resolveEndpointUrls as resolveEndpointUrls2
6170
+ resolveEndpointUrls as resolveEndpointUrls3
4480
6171
  } from "@rasputin-ai/core";
4481
6172
 
4482
6173
  // src/execution-recorder/execution-recording-sync.ts
4483
6174
  import {
4484
6175
  copyRedactKeys,
4485
- defaultIngestFetch,
4486
- encodeJsonRequestBodyAsync,
6176
+ defaultIngestFetch as defaultIngestFetch2,
6177
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
4487
6178
  MAX_REDACT_KEYS
4488
6179
  } from "@rasputin-ai/core";
4489
6180
 
@@ -4666,7 +6357,7 @@ var MAX_CACHE_ENTRIES = 1024;
4666
6357
  var MAX_PENDING_NOTIFIES = 32;
4667
6358
  var MAX_PENDING_TYPES = 64;
4668
6359
  var DEFAULT_POLL_INTERVAL_MS = 1e4;
4669
- var REQUEST_TIMEOUT_MS = 5e3;
6360
+ var REQUEST_TIMEOUT_MS2 = 5e3;
4670
6361
  var MAX_RETRIES = 5;
4671
6362
  var MAX_POLL_JITTER_MS = 2e3;
4672
6363
  var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
@@ -4681,7 +6372,7 @@ var classifyHttpFailure = (status) => {
4681
6372
  if (status >= 500) return "server_error";
4682
6373
  return "non_retryable_http";
4683
6374
  };
4684
- var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
6375
+ var backoffMs2 = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
4685
6376
  var abortFrom = (parent, child) => {
4686
6377
  const onAbort = () => child.abort();
4687
6378
  parent.addEventListener("abort", onAbort, { once: true });
@@ -4689,10 +6380,9 @@ var abortFrom = (parent, child) => {
4689
6380
  return () => parent.removeEventListener("abort", onAbort);
4690
6381
  };
4691
6382
  var createExecutionRecordingCoordinator = (options) => {
4692
- const environment = trimmed2(options.environment);
6383
+ const environment = options.environment;
4693
6384
  const nowMs = () => options.nowMs?.() ?? Date.now();
4694
- const fetchFn = options.fetch ?? defaultIngestFetch();
4695
- const networkEnabled = environment.length > 0;
6385
+ const fetchFn = options.fetch ?? defaultIngestFetch2();
4696
6386
  const instanceId = crypto.randomUUID();
4697
6387
  const startedAt = /* @__PURE__ */ new Date();
4698
6388
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
@@ -4829,7 +6519,7 @@ var createExecutionRecordingCoordinator = (options) => {
4829
6519
  };
4830
6520
  const withRequestTimeout = async (signal, run) => {
4831
6521
  const request = new AbortController();
4832
- const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS);
6522
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
4833
6523
  timer.unref?.();
4834
6524
  const stopParent = abortFrom(signal, request);
4835
6525
  const stopCancel = abortFrom(cancelWork.signal, request);
@@ -4889,7 +6579,7 @@ var createExecutionRecordingCoordinator = (options) => {
4889
6579
  notifyFailures++;
4890
6580
  return false;
4891
6581
  }
4892
- await wait(backoffMs(attempt), signal);
6582
+ await wait(backoffMs2(attempt), signal);
4893
6583
  } catch (error) {
4894
6584
  if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4895
6585
  rememberFailure("aborted");
@@ -4900,463 +6590,1528 @@ var createExecutionRecordingCoordinator = (options) => {
4900
6590
  notifyFailures++;
4901
6591
  return false;
4902
6592
  }
4903
- await wait(backoffMs(attempt), signal);
6593
+ await wait(backoffMs2(attempt), signal);
6594
+ }
6595
+ }
6596
+ return false;
6597
+ };
6598
+ const runPump = async (signal) => {
6599
+ do {
6600
+ pumpAgain = false;
6601
+ const queued = new Set(pending.keys());
6602
+ for (const key of queued) {
6603
+ if (signal.aborted) return;
6604
+ const current = pending.get(key);
6605
+ if (!current) continue;
6606
+ sendingKey = key;
6607
+ const done = await sendNotify(current, signal);
6608
+ sendingKey = void 0;
6609
+ if (pending.get(key) !== current) pumpAgain = true;
6610
+ else if (done || !signal.aborted) pending.delete(key);
6611
+ }
6612
+ for (const key of pending.keys()) {
6613
+ if (!queued.has(key)) {
6614
+ pumpAgain = true;
6615
+ break;
6616
+ }
6617
+ }
6618
+ } while (pumpAgain && pending.size > 0 && !signal.aborted);
6619
+ };
6620
+ const drainNotifies = async (signal) => {
6621
+ while (pending.size > 0 && !signal.aborted) {
6622
+ if (pump) {
6623
+ pumpAgain = true;
6624
+ await joinUntil(pump, signal);
6625
+ continue;
6626
+ }
6627
+ const running = runPump(signal);
6628
+ pump = running;
6629
+ try {
6630
+ await running;
6631
+ } finally {
6632
+ if (pump === running) pump = void 0;
6633
+ }
6634
+ break;
6635
+ }
6636
+ };
6637
+ const kickNotify = () => {
6638
+ if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
6639
+ void drainNotifies(notifySignal());
6640
+ };
6641
+ const rememberCatalog = (key, atMs) => {
6642
+ if (key.length === 0 || key.length > MAX_EXECUTION_TYPE_KEY_LENGTH) return;
6643
+ if (catalog.size >= MAX_CACHE_ENTRIES && !catalog.has(key)) {
6644
+ const oldest = catalog.keys().next().value;
6645
+ if (oldest !== void 0) catalog.delete(oldest);
6646
+ }
6647
+ catalog.set(key, atMs);
6648
+ };
6649
+ const applyCompletedSessionIds = (value) => {
6650
+ if (!Array.isArray(value)) return;
6651
+ for (const entry of value) {
6652
+ const sessionId = trimmed2(entry);
6653
+ if (!sessionId) continue;
6654
+ completedSessionIds.add(sessionId);
6655
+ sessionsById.delete(sessionId);
6656
+ }
6657
+ markSessionsDirty();
6658
+ };
6659
+ const applySessions = (entries) => {
6660
+ if (!Array.isArray(entries)) return;
6661
+ const atMs = nowMs();
6662
+ const next = /* @__PURE__ */ new Map();
6663
+ for (const entry of entries) {
6664
+ if (!isRecord2(entry)) continue;
6665
+ const sessionId = trimmed2(entry.id);
6666
+ const executionKeyValue = trimmed2(entry.execution_key);
6667
+ const status = trimmed2(entry.status);
6668
+ const expiresAtMs = Date.parse(String(entry.expires_at ?? ""));
6669
+ const requestedCount = typeof entry.requested_count === "number" && Number.isFinite(entry.requested_count) ? Math.round(entry.requested_count) : 0;
6670
+ if (!sessionId || !executionKeyValue || status !== "active") continue;
6671
+ if (completedSessionIds.has(sessionId)) continue;
6672
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
6673
+ const existing = sessionsById.get(sessionId);
6674
+ const overrides = parseSessionSettings(entry.overrides);
6675
+ next.set(sessionId, {
6676
+ sessionId,
6677
+ executionKey: executionKeyValue,
6678
+ expiresAtMs,
6679
+ requestedCount,
6680
+ admitted: existing?.admitted ?? 0,
6681
+ serializer: serializers.serializerFor(overrides),
6682
+ redactKeys: overrides?.redactKeys,
6683
+ excludeSources: overrides?.excludeSources,
6684
+ maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
6685
+ maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
6686
+ scrubPII: overrides?.scrubPII
6687
+ });
6688
+ }
6689
+ sessionsById.clear();
6690
+ for (const [id, session] of next) sessionsById.set(id, session);
6691
+ markSessionsDirty();
6692
+ };
6693
+ const applyActivations = (activations) => {
6694
+ if (!Array.isArray(activations)) return;
6695
+ const atMs = nowMs();
6696
+ const seen = /* @__PURE__ */ new Set();
6697
+ for (const entry of activations) {
6698
+ if (!isRecord2(entry)) continue;
6699
+ const key = trimmed2(entry.execution_key);
6700
+ const expiresAt = Date.parse(String(entry.expires_at ?? ""));
6701
+ if (!key || !Number.isFinite(expiresAt) || expiresAt <= atMs) continue;
6702
+ cache.set(key, expiresAt);
6703
+ seen.add(key);
6704
+ }
6705
+ trimCache();
6706
+ for (const key of seen) pending.delete(key);
6707
+ };
6708
+ const catalogTypes = () => {
6709
+ const entries = [];
6710
+ for (const [executionKey, lastSeenAtMs] of catalog) {
6711
+ entries.push({ executionKey, lastSeenAtMs });
6712
+ if (entries.length >= MAX_PENDING_TYPES) break;
6713
+ }
6714
+ return entries;
6715
+ };
6716
+ const syncOnce = async (signal) => {
6717
+ if (closed) return;
6718
+ const types2 = catalogTypes();
6719
+ try {
6720
+ const { response, body: payload } = await postJson(
6721
+ options.syncUrl,
6722
+ {
6723
+ environment,
6724
+ instance: {
6725
+ id: instanceId,
6726
+ sdk_name: options.sdkName,
6727
+ sdk_version: options.sdkVersion,
6728
+ release: options.release,
6729
+ pid: process.pid,
6730
+ started_at: startedAt.toISOString(),
6731
+ reported_mode: options.mode,
6732
+ reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
6733
+ capabilities
6734
+ },
6735
+ types: types2.map((entry) => ({
6736
+ execution_key: entry.executionKey,
6737
+ last_seen_at: new Date(entry.lastSeenAtMs).toISOString()
6738
+ }))
6739
+ },
6740
+ signal,
6741
+ async (syncResponse) => {
6742
+ if (!syncResponse.ok) return void 0;
6743
+ return unwrapPayload(await syncResponse.json());
6744
+ }
6745
+ );
6746
+ if (!response.ok) {
6747
+ rememberFailure(classifyHttpFailure(response.status));
6748
+ refreshFailures++;
6749
+ return;
6750
+ }
6751
+ applyActivations(payload?.activations);
6752
+ applySessions(payload?.sessions);
6753
+ for (const entry of types2) {
6754
+ const current = catalog.get(entry.executionKey);
6755
+ if (current === void 0) continue;
6756
+ catalog.delete(entry.executionKey);
6757
+ if (current !== entry.lastSeenAtMs) {
6758
+ catalog.set(entry.executionKey, current);
6759
+ }
6760
+ }
6761
+ } catch (error) {
6762
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
6763
+ rememberFailure("aborted");
6764
+ } else {
6765
+ rememberFailure("network_error");
6766
+ }
6767
+ refreshFailures++;
6768
+ }
6769
+ };
6770
+ const runSyncOnce = async (signal) => {
6771
+ if (syncFlight) {
6772
+ await joinUntil(syncFlight, signal);
6773
+ return;
6774
+ }
6775
+ const running = syncOnce(signal);
6776
+ const flight = running.finally(() => {
6777
+ if (syncFlight === flight) syncFlight = void 0;
6778
+ });
6779
+ syncFlight = flight;
6780
+ await joinUntil(flight, signal);
6781
+ };
6782
+ const sendRecordings = async (batch, signal) => {
6783
+ const followed = new AbortController();
6784
+ const stopParent = abortFrom(signal, followed);
6785
+ const stopCancel = abortFrom(cancelWork.signal, followed);
6786
+ const combined = followed.signal;
6787
+ try {
6788
+ if (combined.aborted) return false;
6789
+ let encoded;
6790
+ try {
6791
+ encoded = await encodeJsonRequestBodyAsync2(
6792
+ {
6793
+ instance_id: instanceId,
6794
+ recordings: batch.map((item) => ({
6795
+ session_id: item.sessionId,
6796
+ execution_id: item.executionId,
6797
+ outcome: item.outcome,
6798
+ runtime_state: item.runtimeState,
6799
+ release: options.release,
6800
+ redact_keys: copyRedactKeys([
6801
+ ...redactKeys ?? [],
6802
+ ...item.redactKeys ?? []
6803
+ ])?.slice(0, MAX_REDACT_KEYS),
6804
+ scrub_pii: item.scrubPii ?? scrubPii
6805
+ }))
6806
+ },
6807
+ void 0,
6808
+ combined
6809
+ );
6810
+ } catch (error) {
6811
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
6812
+ rememberFailure("aborted");
6813
+ return false;
6814
+ }
6815
+ rememberFailure("network_error");
6816
+ return false;
6817
+ }
6818
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
6819
+ if (combined.aborted) return false;
6820
+ try {
6821
+ const { response, body } = await postEncoded(
6822
+ options.recordingsUrl,
6823
+ encoded,
6824
+ combined,
6825
+ async (uploadResponse) => {
6826
+ if (!uploadResponse.ok) return void 0;
6827
+ try {
6828
+ return unwrapPayload(await uploadResponse.json());
6829
+ } catch {
6830
+ return void 0;
6831
+ }
6832
+ }
6833
+ );
6834
+ if (response.ok) {
6835
+ applyCompletedSessionIds(body?.completed_session_ids);
6836
+ return true;
6837
+ }
6838
+ const kind = classifyHttpFailure(response.status);
6839
+ rememberFailure(kind);
6840
+ if (kind === "non_retryable_http") return true;
6841
+ if (attempt === MAX_RETRIES) return false;
6842
+ await wait(backoffMs2(attempt), combined);
6843
+ } catch (error) {
6844
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
6845
+ rememberFailure("aborted");
6846
+ return false;
6847
+ }
6848
+ rememberFailure("network_error");
6849
+ if (attempt === MAX_RETRIES) return false;
6850
+ await wait(backoffMs2(attempt), combined);
6851
+ }
4904
6852
  }
6853
+ return false;
6854
+ } finally {
6855
+ stopParent();
6856
+ stopCancel();
4905
6857
  }
4906
- return false;
4907
6858
  };
4908
- const runPump = async (signal) => {
4909
- do {
4910
- pumpAgain = false;
4911
- const queued = new Set(pending.keys());
4912
- for (const key of queued) {
4913
- if (signal.aborted) return;
4914
- const current = pending.get(key);
4915
- if (!current) continue;
4916
- sendingKey = key;
4917
- const done = await sendNotify(current, signal);
4918
- sendingKey = void 0;
4919
- if (pending.get(key) !== current) pumpAgain = true;
4920
- else if (done || !signal.aborted) pending.delete(key);
6859
+ const drainRecordings = async (signal) => {
6860
+ while (recordings.length > 0 && !signal.aborted) {
6861
+ const batch = recordings.splice(0, 8);
6862
+ const ok = await sendRecordings(batch, signal);
6863
+ if (!ok) {
6864
+ recordings.unshift(...batch);
6865
+ break;
4921
6866
  }
4922
- for (const key of pending.keys()) {
4923
- if (!queued.has(key)) {
4924
- pumpAgain = true;
6867
+ }
6868
+ };
6869
+ const kickRecordings = () => {
6870
+ if (closed || closing || recordings.length === 0) return;
6871
+ if (recordingPump) return;
6872
+ const running = drainRecordings(recordingSignal());
6873
+ recordingPump = running;
6874
+ void running.finally(() => {
6875
+ if (recordingPump === running) recordingPump = void 0;
6876
+ if (recordings.length > 0) kickRecordings();
6877
+ });
6878
+ };
6879
+ const activate = (metadata, window) => {
6880
+ if (closed || options.mode !== "adaptive") return;
6881
+ const key = executionTypeKey(metadata);
6882
+ if (!key) return;
6883
+ const atMs = nowMs();
6884
+ const existing = cache.get(key);
6885
+ if (existing !== void 0 && existing > atMs) return;
6886
+ cache.set(key, window.expiresAtMs);
6887
+ trimCache();
6888
+ if (window.expiresAtMs <= atMs) return;
6889
+ if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
6890
+ for (const oldest of pending.keys()) {
6891
+ if (oldest !== sendingKey) {
6892
+ pending.delete(oldest);
4925
6893
  break;
4926
6894
  }
4927
6895
  }
4928
- } while (pumpAgain && pending.size > 0 && !signal.aborted);
6896
+ }
6897
+ pending.set(key, { executionKey: key, ...window });
6898
+ kickNotify();
4929
6899
  };
4930
- const drainNotifies = async (signal) => {
4931
- while (pending.size > 0 && !signal.aborted) {
4932
- if (pump) {
4933
- pumpAgain = true;
4934
- await joinUntil(pump, signal);
4935
- continue;
6900
+ const peekSessions = () => {
6901
+ if (sessionsDirty) rebuildSessionSnapshot();
6902
+ else {
6903
+ const atMs = nowMs();
6904
+ for (const session of sessionSnapshot.values()) {
6905
+ if (session.expiresAtMs <= atMs) {
6906
+ rebuildSessionSnapshot();
6907
+ break;
6908
+ }
4936
6909
  }
4937
- const running = runPump(signal);
4938
- pump = running;
6910
+ }
6911
+ return sessionSnapshot;
6912
+ };
6913
+ const consumeSession = (executionKeyValue, sessionId) => {
6914
+ const atMs = nowMs();
6915
+ for (const session of sessionsById.values()) {
6916
+ if (session.executionKey !== executionKeyValue) continue;
6917
+ if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
6918
+ if (!sessionHasRoom(session, atMs)) continue;
6919
+ session.admitted += 1;
6920
+ markSessionsDirty();
6921
+ return sessionView(session);
6922
+ }
6923
+ return void 0;
6924
+ };
6925
+ const observeType = (executionKeyValue) => {
6926
+ rememberCatalog(executionKeyValue, nowMs());
6927
+ };
6928
+ const enqueueRecording = (payload) => {
6929
+ if (closed || closing) return;
6930
+ recordings.push(payload);
6931
+ kickRecordings();
6932
+ };
6933
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
6934
+ const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
6935
+ const delay = interval + Math.floor(Math.random() * jitterMax);
6936
+ pollStartTimer = setTimeout(() => {
6937
+ pollStartTimer = void 0;
6938
+ if (closed || closing) return;
6939
+ void runSyncOnce(pollSignal());
6940
+ pollTimer = setInterval(() => {
6941
+ if (closed || closing) return;
6942
+ void runSyncOnce(pollSignal());
6943
+ }, interval);
6944
+ pollTimer.unref?.();
6945
+ }, delay);
6946
+ pollStartTimer.unref?.();
6947
+ const stopTimers = () => {
6948
+ if (pollStartTimer) {
6949
+ clearTimeout(pollStartTimer);
6950
+ pollStartTimer = void 0;
6951
+ }
6952
+ if (pollTimer) {
6953
+ clearInterval(pollTimer);
6954
+ pollTimer = void 0;
6955
+ }
6956
+ };
6957
+ return {
6958
+ peek,
6959
+ activate,
6960
+ peekSessions,
6961
+ consumeSession,
6962
+ observeType,
6963
+ enqueueRecording,
6964
+ getStats: () => ({
6965
+ adaptiveNotifyFailures: notifyFailures,
6966
+ adaptiveRefreshFailures: refreshFailures,
6967
+ lastAdaptiveFailureKind: lastFailureKind
6968
+ }),
6969
+ flush: async (timeoutMs = 2e3) => {
6970
+ if (closed || closing) return;
6971
+ const flushAbort = new AbortController();
6972
+ const onAbort = () => interruptWork();
6973
+ flushAbort.signal.addEventListener("abort", onAbort, { once: true });
6974
+ const timer = setTimeout(() => flushAbort.abort(), Math.max(0, timeoutMs));
4939
6975
  try {
4940
- await running;
6976
+ await runSyncOnce(flushAbort.signal);
6977
+ if (!flushAbort.signal.aborted) await drainNotifies(flushAbort.signal);
6978
+ await joinUntil(recordingPump, flushAbort.signal);
6979
+ if (!flushAbort.signal.aborted) await drainRecordings(flushAbort.signal);
4941
6980
  } finally {
4942
- if (pump === running) pump = void 0;
6981
+ clearTimeout(timer);
6982
+ flushAbort.signal.removeEventListener("abort", onAbort);
4943
6983
  }
4944
- break;
6984
+ },
6985
+ close: async () => {
6986
+ if (closed || closing) return;
6987
+ closing = true;
6988
+ stopTimers();
6989
+ const deadline = new AbortController();
6990
+ const timer = setTimeout(() => {
6991
+ deadline.abort();
6992
+ interruptWork();
6993
+ }, 2e3);
6994
+ try {
6995
+ await runSyncOnce(deadline.signal);
6996
+ if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
6997
+ await joinUntil(recordingPump, deadline.signal);
6998
+ if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
6999
+ } finally {
7000
+ clearTimeout(timer);
7001
+ closed = true;
7002
+ interruptWork();
7003
+ pending.clear();
7004
+ }
7005
+ }
7006
+ };
7007
+ };
7008
+
7009
+ // src/execution-recorder/bind-adaptive-recorder.ts
7010
+ var bindAdaptiveRecorder = (input) => {
7011
+ const options = input.executionRecorder;
7012
+ const adaptiveEnabled = options?.adaptive?.enabled === true;
7013
+ const activation = resolveClientActivation({
7014
+ enabled: input.enabled,
7015
+ dsn: input.dsn,
7016
+ projectApiKey: input.projectApiKey,
7017
+ apiUrl: input.apiUrl,
7018
+ release: input.release,
7019
+ environment: input.environment
7020
+ });
7021
+ const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
7022
+ environment: activation.environment,
7023
+ ingestToken: activation.ingestToken,
7024
+ activateUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingActivateUrl,
7025
+ syncUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingSyncUrl,
7026
+ recordingsUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingRecordingsUrl,
7027
+ sdkName: input.sdkName,
7028
+ sdkVersion: input.sdkVersion,
7029
+ release: activation.release,
7030
+ recorderOptions: options,
7031
+ scrubPII: input.scrubPII,
7032
+ mode: adaptiveEnabled ? "adaptive" : "full",
7033
+ fetch: input.fetch
7034
+ }) : void 0;
7035
+ const recorderHooks = {};
7036
+ if (coordinator) {
7037
+ recorderHooks.policySnapshot = coordinator.peek;
7038
+ recorderHooks.onQualifyingFailure = adaptiveEnabled ? coordinator.activate : void 0;
7039
+ recorderHooks.getStats = coordinator.getStats;
7040
+ recorderHooks.sessionCaptureSnapshot = coordinator.peekSessions;
7041
+ recorderHooks.consumeSession = coordinator.consumeSession;
7042
+ recorderHooks.observeExecutionType = coordinator.observeType;
7043
+ recorderHooks.onSessionRecording = coordinator.enqueueRecording;
7044
+ }
7045
+ if (input.functionMetrics) recorderHooks.functionMetrics = input.functionMetrics;
7046
+ if (input.executionMetrics) recorderHooks.executionMetrics = input.executionMetrics;
7047
+ if (input.durationSampler) recorderHooks.durationSampler = input.durationSampler;
7048
+ const runtime = createExecutionRecorder(
7049
+ { ...options, enabled: input.recorderEnabled },
7050
+ recorderHooks
7051
+ );
7052
+ return { runtime, policy: coordinator };
7053
+ };
7054
+
7055
+ // src/function-metrics/bind-function-metrics.ts
7056
+ import { randomUUID as randomUUID4 } from "node:crypto";
7057
+ import {
7058
+ defaultIngestFetch as defaultIngestFetch3,
7059
+ resolveEndpointUrls as resolveEndpointUrls4
7060
+ } from "@rasputin-ai/core";
7061
+
7062
+ // src/function-metrics/function-metrics-collector.ts
7063
+ import {
7064
+ durationHistogramBucket as durationHistogramBucket2,
7065
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT as FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2,
7066
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES as FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7067
+ FUNCTION_METRICS_MAX_BUFFERED_MS as FUNCTION_METRICS_MAX_BUFFERED_MS2,
7068
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES as FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
7069
+ FUNCTION_METRICS_MAX_FUNCTIONS,
7070
+ FUNCTION_METRICS_MAX_MINUTE_ROWS as FUNCTION_METRICS_MAX_MINUTE_ROWS2,
7071
+ FUNCTION_METRICS_MAX_STATE_BYTES as FUNCTION_METRICS_MAX_STATE_BYTES2,
7072
+ FUNCTION_METRICS_MEASUREMENT_FORMAT as FUNCTION_METRICS_MEASUREMENT_FORMAT2,
7073
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS3,
7074
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT as FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2,
7075
+ functionIdentityKey,
7076
+ isCanonicalFunctionMetricsExecutionKey as isCanonicalFunctionMetricsExecutionKey2
7077
+ } from "@rasputin-ai/core";
7078
+
7079
+ // src/function-metrics/function-metrics-batches.ts
7080
+ import { randomUUID as randomUUID3 } from "node:crypto";
7081
+ import {
7082
+ FUNCTION_METRICS_SCHEMA_VERSION
7083
+ } from "@rasputin-ai/core";
7084
+ var emptyCoverage3 = (buckets) => ({
7085
+ covered_bucket_starts: buckets,
7086
+ skipped_unresolved_execution_type: 0,
7087
+ dropped_active_series: 0,
7088
+ dropped_byte_budget: 0,
7089
+ dropped_queue_budget: 0,
7090
+ dropped_late_completion: 0,
7091
+ dropped_unexportable: 0
7092
+ });
7093
+ var bucketStart2 = (minute) => new Date(minute * 6e4).toISOString();
7094
+ var sparseHistogram2 = (histogram) => {
7095
+ const cells = [];
7096
+ for (let index = 0; index < histogram.length; index += 1) {
7097
+ const count = histogram[index] ?? 0;
7098
+ if (count > 0) cells.push([index, count]);
7099
+ }
7100
+ return cells;
7101
+ };
7102
+ var toMinute2 = (row, functionIndex, executionTypeIndex) => ({
7103
+ function_index: functionIndex,
7104
+ execution_type_index: executionTypeIndex,
7105
+ bucket_start: bucketStart2(row.minute),
7106
+ started_calls: row.series.started,
7107
+ completed_calls: row.series.completed,
7108
+ failed_calls: row.series.failed,
7109
+ duration_sample_count: row.series.sampleCount,
7110
+ duration_sample_sum_us: row.series.sampleSumUs,
7111
+ duration_sample_min_us: row.series.sampleMinUs,
7112
+ duration_sample_max_us: row.series.sampleMaxUs,
7113
+ duration_histogram: sparseHistogram2(row.series.histogram),
7114
+ invalid_timing_count: row.series.invalidTiming
7115
+ });
7116
+ var rowsFromQueue = (queued) => {
7117
+ const rows = [];
7118
+ for (const queuedMinute of queued) {
7119
+ for (const [functionHandle, byExecution] of queuedMinute.series) {
7120
+ for (const [executionHandle, series] of byExecution) {
7121
+ rows.push({
7122
+ minute: queuedMinute.minute,
7123
+ functionHandle,
7124
+ executionHandle,
7125
+ series
7126
+ });
7127
+ }
7128
+ }
7129
+ }
7130
+ rows.sort((left, right) => {
7131
+ if (left.minute !== right.minute) return left.minute - right.minute;
7132
+ if (left.functionHandle !== right.functionHandle) {
7133
+ return left.functionHandle - right.functionHandle;
7134
+ }
7135
+ return left.executionHandle - right.executionHandle;
7136
+ });
7137
+ return rows;
7138
+ };
7139
+ var chunkRows = (rows, maxFunctions, maxExecutionTypes, maxMinuteRows) => {
7140
+ const chunks = [];
7141
+ let current = [];
7142
+ let functions = /* @__PURE__ */ new Set();
7143
+ let executionTypes = /* @__PURE__ */ new Set();
7144
+ const flush = () => {
7145
+ if (current.length === 0) return;
7146
+ chunks.push(current);
7147
+ current = [];
7148
+ functions = /* @__PURE__ */ new Set();
7149
+ executionTypes = /* @__PURE__ */ new Set();
7150
+ };
7151
+ for (const row of rows) {
7152
+ const nextFunctions = functions.has(row.functionHandle) ? functions.size : functions.size + 1;
7153
+ const nextTypes = executionTypes.has(row.executionHandle) ? executionTypes.size : executionTypes.size + 1;
7154
+ const rowWouldOverflow = current.length >= maxMinuteRows || nextFunctions > maxFunctions || nextTypes > maxExecutionTypes;
7155
+ if (rowWouldOverflow) flush();
7156
+ current.push(row);
7157
+ functions.add(row.functionHandle);
7158
+ executionTypes.add(row.executionHandle);
7159
+ }
7160
+ flush();
7161
+ return chunks;
7162
+ };
7163
+ var batchForChunk2 = (draft, rows, coverage) => {
7164
+ const functionIndexes = /* @__PURE__ */ new Map();
7165
+ const executionIndexes = /* @__PURE__ */ new Map();
7166
+ const functions = [];
7167
+ const executionTypes = [];
7168
+ const minutes = [];
7169
+ for (const row of rows) {
7170
+ let functionIndex = functionIndexes.get(row.functionHandle);
7171
+ if (functionIndex === void 0) {
7172
+ const declaration = draft.functions[row.functionHandle];
7173
+ if (!declaration) continue;
7174
+ functionIndex = functions.length;
7175
+ functionIndexes.set(row.functionHandle, functionIndex);
7176
+ functions.push(declaration);
7177
+ }
7178
+ let executionTypeIndex = executionIndexes.get(row.executionHandle);
7179
+ if (executionTypeIndex === void 0) {
7180
+ const executionKey = draft.executionKeys[row.executionHandle];
7181
+ if (!executionKey) continue;
7182
+ executionTypeIndex = executionTypes.length;
7183
+ executionIndexes.set(row.executionHandle, executionTypeIndex);
7184
+ executionTypes.push({ execution_key: executionKey });
7185
+ }
7186
+ minutes.push(toMinute2(row, functionIndex, executionTypeIndex));
7187
+ }
7188
+ const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
7189
+ return {
7190
+ schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
7191
+ measurement_format: draft.measurementFormat,
7192
+ producer_id: draft.producerId,
7193
+ batch_id: draft.batchId(),
7194
+ environment: draft.environment,
7195
+ release: draft.release,
7196
+ functions,
7197
+ execution_types: executionTypes,
7198
+ minutes,
7199
+ coverage: { ...coverage, covered_bucket_starts: covered }
7200
+ };
7201
+ };
7202
+ var functionMetricsBatchesFromQueue = (draft) => {
7203
+ const rows = rowsFromQueue(draft.queued);
7204
+ if (rows.length === 0) {
7205
+ const hasLoss = Object.entries(draft.coverage).some(([key, value]) => {
7206
+ return key !== "covered_bucket_starts" && typeof value === "number" && value > 0;
7207
+ });
7208
+ if (!hasLoss) return [];
7209
+ return [
7210
+ {
7211
+ schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
7212
+ measurement_format: draft.measurementFormat,
7213
+ producer_id: draft.producerId,
7214
+ batch_id: draft.batchId(),
7215
+ environment: draft.environment,
7216
+ release: draft.release,
7217
+ functions: [],
7218
+ execution_types: [],
7219
+ minutes: [],
7220
+ coverage: draft.coverage
7221
+ }
7222
+ ];
7223
+ }
7224
+ const chunks = chunkRows(rows, draft.maxFunctions, draft.maxExecutionTypes, draft.maxMinuteRows);
7225
+ return chunks.map(
7226
+ (chunk, index) => batchForChunk2(draft, chunk, index === 0 ? draft.coverage : emptyCoverage3([]))
7227
+ );
7228
+ };
7229
+ var newFunctionMetricsBatchId = () => randomUUID3();
7230
+
7231
+ // src/function-metrics/function-metrics-collector.ts
7232
+ var SERIES_BYTES2 = 256;
7233
+ var HISTOGRAM_BYTES2 = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2 * 4;
7234
+ var DECLARATION_BYTES = 1024;
7235
+ var MAX_ELAPSED_NS2 = BigInt(Number.MAX_SAFE_INTEGER);
7236
+ var defaultLimits2 = () => ({
7237
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7238
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES2,
7239
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS2 / FUNCTION_METRICS_MINUTE_MS3,
7240
+ maxFunctions: FUNCTION_METRICS_MAX_FUNCTIONS,
7241
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
7242
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS2
7243
+ });
7244
+ var defaultClock2 = () => ({
7245
+ monotonicNs: () => process.hrtime.bigint(),
7246
+ wallTimeMs: () => Date.now()
7247
+ });
7248
+ var emptyCoverage4 = () => ({
7249
+ covered_bucket_starts: [],
7250
+ skipped_unresolved_execution_type: 0,
7251
+ dropped_active_series: 0,
7252
+ dropped_byte_budget: 0,
7253
+ dropped_queue_budget: 0,
7254
+ dropped_late_completion: 0,
7255
+ dropped_unexportable: 0
7256
+ });
7257
+ var note2 = (coverage, counter, amount = 1) => {
7258
+ const next = coverage[counter] + amount;
7259
+ coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
7260
+ };
7261
+ var countSeries2 = (table) => {
7262
+ let count = 0;
7263
+ for (const byExecution of table.values()) count += byExecution.size;
7264
+ return count;
7265
+ };
7266
+ var tableBytes2 = (table) => {
7267
+ let bytes = 0;
7268
+ for (const byExecution of table.values()) {
7269
+ for (const series of byExecution.values()) bytes += series.bytes;
7270
+ }
7271
+ return bytes;
7272
+ };
7273
+ var discardedMarks2 = (table) => {
7274
+ let marks = 0;
7275
+ for (const byExecution of table.values()) {
7276
+ for (const series of byExecution.values()) {
7277
+ const next = marks + series.started + series.completed;
7278
+ marks = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
7279
+ }
7280
+ }
7281
+ return marks;
7282
+ };
7283
+ var seriesHasMarks2 = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
7284
+ var copySeries2 = (series) => ({
7285
+ ...series,
7286
+ histogram: series.histogram.slice()
7287
+ });
7288
+ var resetSeries2 = (series) => {
7289
+ series.started = 0;
7290
+ series.completed = 0;
7291
+ series.failed = 0;
7292
+ series.sampleCount = 0;
7293
+ series.sampleSumUs = 0;
7294
+ series.sampleMinUs = null;
7295
+ series.sampleMaxUs = null;
7296
+ series.invalidTiming = 0;
7297
+ series.histogram.fill(0);
7298
+ };
7299
+ var snapshotAndReset2 = (table) => {
7300
+ const snapshot = /* @__PURE__ */ new Map();
7301
+ for (const [functionHandle, byExecution] of table) {
7302
+ const copied = /* @__PURE__ */ new Map();
7303
+ for (const [executionHandle, series] of byExecution) {
7304
+ if (seriesHasMarks2(series)) copied.set(executionHandle, copySeries2(series));
7305
+ resetSeries2(series);
7306
+ }
7307
+ if (copied.size > 0) snapshot.set(functionHandle, copied);
7308
+ }
7309
+ return snapshot;
7310
+ };
7311
+ var declarationAccepted = (declaration) => {
7312
+ if (declaration.identity_kind !== declaration.descriptor.identity_kind) return false;
7313
+ if (declaration.logical_key !== functionIdentityKey(declaration.descriptor)) return false;
7314
+ if (declaration.descriptor.identity_kind === "release_scoped") {
7315
+ return declaration.descriptor.declaration_id === declaration.runtime_id;
7316
+ }
7317
+ return true;
7318
+ };
7319
+ var createFunctionMetricsCollector = (options) => {
7320
+ const limits = { ...defaultLimits2(), ...options.limits };
7321
+ const clock = options.clock ?? defaultClock2();
7322
+ const batchId = options.batchId ?? newFunctionMetricsBatchId;
7323
+ const measurementFormat = options.sampledMeasurementFormat ? FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2 : FUNCTION_METRICS_MEASUREMENT_FORMAT2;
7324
+ const coverage = emptyCoverage4();
7325
+ const functions = [];
7326
+ const functionHandleByRuntimeId = /* @__PURE__ */ new Map();
7327
+ const executionKeys = [];
7328
+ const executionHandleByKey = /* @__PURE__ */ new Map();
7329
+ const active = /* @__PURE__ */ new Map();
7330
+ const queue = [];
7331
+ let lastClosedMinute = Number.NEGATIVE_INFINITY;
7332
+ let lastSeenMinute = Number.NEGATIVE_INFINITY;
7333
+ let stateBytes = 0;
7334
+ let activeSeries = 0;
7335
+ let sealed = false;
7336
+ const reserve = (bytes) => {
7337
+ if (stateBytes > limits.maxStateBytes - bytes) {
7338
+ note2(coverage, "dropped_byte_budget");
7339
+ return false;
7340
+ }
7341
+ stateBytes += bytes;
7342
+ return true;
7343
+ };
7344
+ const internDeclaration = (declaration) => {
7345
+ if (!declaration) {
7346
+ note2(coverage, "dropped_unexportable");
7347
+ return void 0;
7348
+ }
7349
+ const existing = functionHandleByRuntimeId.get(declaration.runtime_id);
7350
+ if (existing !== void 0) return existing;
7351
+ if (!declarationAccepted(declaration)) {
7352
+ note2(coverage, "dropped_unexportable");
7353
+ return void 0;
7354
+ }
7355
+ if (functions.length >= limits.maxFunctions) {
7356
+ note2(coverage, "dropped_unexportable");
7357
+ return void 0;
4945
7358
  }
7359
+ if (!reserve(DECLARATION_BYTES + declaration.runtime_id.length)) return void 0;
7360
+ const handle = functions.length;
7361
+ functions.push(declaration);
7362
+ functionHandleByRuntimeId.set(declaration.runtime_id, handle);
7363
+ return handle;
7364
+ };
7365
+ const internExecutionKey = (key) => {
7366
+ if (!key || !isCanonicalFunctionMetricsExecutionKey2(key)) return void 0;
7367
+ const existing = executionHandleByKey.get(key);
7368
+ if (existing !== void 0) return existing;
7369
+ if (executionKeys.length >= limits.maxExecutionTypes) {
7370
+ note2(coverage, "dropped_unexportable");
7371
+ return void 0;
7372
+ }
7373
+ if (!reserve(key.length)) return void 0;
7374
+ const handle = executionKeys.length;
7375
+ executionKeys.push(key);
7376
+ executionHandleByKey.set(key, handle);
7377
+ return handle;
4946
7378
  };
4947
- const kickNotify = () => {
4948
- if (!networkEnabled || closed || closing || pending.size === 0 || options.mode !== "adaptive")
7379
+ const ensureSeries = (minute, functionHandle, executionHandle) => {
7380
+ let byFunction = active.get(minute);
7381
+ if (!byFunction) {
7382
+ byFunction = /* @__PURE__ */ new Map();
7383
+ active.set(minute, byFunction);
7384
+ }
7385
+ let byExecution = byFunction.get(functionHandle);
7386
+ if (!byExecution) {
7387
+ byExecution = /* @__PURE__ */ new Map();
7388
+ byFunction.set(functionHandle, byExecution);
7389
+ }
7390
+ const existing = byExecution.get(executionHandle);
7391
+ if (existing) return existing;
7392
+ if (activeSeries >= limits.maxActiveSeries) {
7393
+ note2(coverage, "dropped_active_series");
7394
+ return void 0;
7395
+ }
7396
+ if (!reserve(SERIES_BYTES2 + HISTOGRAM_BYTES2)) return void 0;
7397
+ const series = {
7398
+ started: 0,
7399
+ completed: 0,
7400
+ failed: 0,
7401
+ sampleCount: 0,
7402
+ sampleSumUs: 0,
7403
+ sampleMinUs: null,
7404
+ sampleMaxUs: null,
7405
+ invalidTiming: 0,
7406
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2),
7407
+ bytes: SERIES_BYTES2 + HISTOGRAM_BYTES2
7408
+ };
7409
+ byExecution.set(executionHandle, series);
7410
+ activeSeries += 1;
7411
+ return series;
7412
+ };
7413
+ const appendQueue = (entry) => {
7414
+ if (discardedMarks2(entry.series) === 0) {
7415
+ stateBytes -= entry.bytes;
7416
+ if (stateBytes < 0) stateBytes = 0;
4949
7417
  return;
4950
- void drainNotifies(notifySignal());
4951
- };
4952
- const rememberCatalog = (key, atMs) => {
4953
- if (key.length === 0 || key.length > MAX_EXECUTION_TYPE_KEY_LENGTH) return;
4954
- if (catalog.size >= MAX_CACHE_ENTRIES && !catalog.has(key)) {
4955
- const oldest = catalog.keys().next().value;
4956
- if (oldest !== void 0) catalog.delete(oldest);
4957
7418
  }
4958
- catalog.set(key, atMs);
7419
+ queue.push(entry);
7420
+ queue.sort((left, right) => left.minute - right.minute);
7421
+ while (queue.length > limits.maxQueuedMinutes) {
7422
+ const dropped = queue.shift();
7423
+ if (!dropped) break;
7424
+ stateBytes -= dropped.bytes;
7425
+ if (stateBytes < 0) stateBytes = 0;
7426
+ note2(coverage, "dropped_queue_budget", discardedMarks2(dropped.series));
7427
+ }
7428
+ };
7429
+ const closeMinute = (minute, table) => {
7430
+ active.delete(minute);
7431
+ activeSeries -= countSeries2(table);
7432
+ if (minute > lastClosedMinute) lastClosedMinute = minute;
7433
+ appendQueue({ minute, series: table, bytes: tableBytes2(table) });
7434
+ };
7435
+ const rotate = (currentMinute) => {
7436
+ for (const minute of [...active.keys()]) {
7437
+ if (minute >= currentMinute) continue;
7438
+ const table = active.get(minute);
7439
+ if (table) closeMinute(minute, table);
7440
+ }
7441
+ const closedThrough = currentMinute - 1;
7442
+ if (closedThrough > lastClosedMinute) lastClosedMinute = closedThrough;
7443
+ };
7444
+ const rotateIfNeeded = (minute) => {
7445
+ if (minute === lastSeenMinute) return;
7446
+ lastSeenMinute = minute;
7447
+ rotate(minute);
7448
+ };
7449
+ const snapshotActive = () => {
7450
+ for (const [minute, table] of active) {
7451
+ appendQueue({ minute, series: snapshotAndReset2(table), bytes: 0 });
7452
+ }
7453
+ };
7454
+ const moveAllActive = () => {
7455
+ for (const minute of [...active.keys()]) {
7456
+ const table = active.get(minute);
7457
+ if (table) closeMinute(minute, table);
7458
+ }
7459
+ };
7460
+ const rememberSample = (series, durationUs, bucket) => {
7461
+ const sampleCount = series.sampleCount + 1;
7462
+ const sampleSumUs = series.sampleSumUs + durationUs;
7463
+ const previous = series.histogram[bucket];
7464
+ if (previous === void 0) return false;
7465
+ const cell = previous + 1;
7466
+ const sumFits = Number.isFinite(sampleSumUs) && sampleSumUs >= 0 && sampleSumUs <= Number.MAX_SAFE_INTEGER;
7467
+ if (!Number.isSafeInteger(sampleCount) || !Number.isSafeInteger(cell) || !sumFits) return false;
7468
+ series.histogram[bucket] = cell;
7469
+ series.sampleCount = sampleCount;
7470
+ series.sampleSumUs = sampleSumUs;
7471
+ series.sampleMinUs = series.sampleMinUs === null ? durationUs : Math.min(series.sampleMinUs, durationUs);
7472
+ series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
7473
+ return true;
4959
7474
  };
4960
- const applyCompletedSessionIds = (value) => {
4961
- if (!Array.isArray(value)) return;
4962
- for (const entry of value) {
4963
- const sessionId = trimmed2(entry);
4964
- if (!sessionId) continue;
4965
- completedSessionIds.add(sessionId);
4966
- sessionsById.delete(sessionId);
7475
+ const rememberOutcome = (series, failed) => {
7476
+ const completed = series.completed + 1;
7477
+ const failures = series.failed + (failed ? 1 : 0);
7478
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
7479
+ series.completed = completed;
7480
+ series.failed = failures;
7481
+ return true;
7482
+ };
7483
+ const rememberInvalidTiming = (series, failed) => {
7484
+ const completed = series.completed + 1;
7485
+ const failures = series.failed + (failed ? 1 : 0);
7486
+ const invalidTiming = series.invalidTiming + 1;
7487
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures) || !Number.isSafeInteger(invalidTiming)) {
7488
+ return false;
4967
7489
  }
4968
- markSessionsDirty();
7490
+ series.completed = completed;
7491
+ series.failed = failures;
7492
+ series.invalidTiming = invalidTiming;
7493
+ return true;
4969
7494
  };
4970
- const applySessions = (entries) => {
4971
- if (!Array.isArray(entries)) return;
4972
- const atMs = nowMs();
4973
- const next = /* @__PURE__ */ new Map();
4974
- for (const entry of entries) {
4975
- if (!isRecord2(entry)) continue;
4976
- const sessionId = trimmed2(entry.id);
4977
- const executionKeyValue = trimmed2(entry.execution_key);
4978
- const status = trimmed2(entry.status);
4979
- const expiresAtMs = Date.parse(String(entry.expires_at ?? ""));
4980
- const requestedCount = typeof entry.requested_count === "number" && Number.isFinite(entry.requested_count) ? Math.round(entry.requested_count) : 0;
4981
- if (!sessionId || !executionKeyValue || status !== "active") continue;
4982
- if (completedSessionIds.has(sessionId)) continue;
4983
- if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
4984
- const existing = sessionsById.get(sessionId);
4985
- const overrides = parseSessionSettings(entry.overrides);
4986
- next.set(sessionId, {
4987
- sessionId,
4988
- executionKey: executionKeyValue,
4989
- expiresAtMs,
4990
- requestedCount,
4991
- admitted: existing?.admitted ?? 0,
4992
- serializer: serializers.serializerFor(overrides),
4993
- redactKeys: overrides?.redactKeys,
4994
- excludeSources: overrides?.excludeSources,
4995
- maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
4996
- maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
4997
- scrubPII: overrides?.scrubPII
4998
- });
7495
+ const rememberCompletion = (series, startedNs, failed, endedNs) => {
7496
+ const completed = series.completed + 1;
7497
+ const failures = series.failed + (failed ? 1 : 0);
7498
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
7499
+ const elapsed = endedNs - startedNs;
7500
+ const durationUs = Number(elapsed) / 1e3;
7501
+ const placed = durationHistogramBucket2(durationUs);
7502
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS2;
7503
+ const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
7504
+ if (!sampled) {
7505
+ const invalidTiming = series.invalidTiming + 1;
7506
+ if (!Number.isSafeInteger(invalidTiming)) return false;
7507
+ series.invalidTiming = invalidTiming;
7508
+ }
7509
+ series.completed = completed;
7510
+ series.failed = failures;
7511
+ return true;
7512
+ };
7513
+ const startCall = (functionHandle, executionHandle, callOptions) => {
7514
+ if (sealed) {
7515
+ note2(coverage, "dropped_unexportable");
7516
+ return void 0;
7517
+ }
7518
+ if (executionHandle === void 0) {
7519
+ note2(coverage, "skipped_unresolved_execution_type");
7520
+ return void 0;
7521
+ }
7522
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
7523
+ rotateIfNeeded(minute);
7524
+ if (minute <= lastClosedMinute) {
7525
+ note2(coverage, "dropped_late_completion");
7526
+ return void 0;
7527
+ }
7528
+ const series = ensureSeries(minute, functionHandle, executionHandle);
7529
+ if (!series) return void 0;
7530
+ const started = series.started + 1;
7531
+ if (!Number.isSafeInteger(started)) {
7532
+ note2(coverage, "dropped_unexportable");
7533
+ return void 0;
7534
+ }
7535
+ series.started = started;
7536
+ const measure = callOptions?.measure !== false;
7537
+ if (!measure) return { measure: false };
7538
+ if (callOptions && "startedNs" in callOptions) {
7539
+ return { measure: true, startedNs: callOptions.startedNs };
7540
+ }
7541
+ try {
7542
+ return { measure: true, startedNs: clock.monotonicNs() };
7543
+ } catch {
7544
+ return { measure: true };
4999
7545
  }
5000
- sessionsById.clear();
5001
- for (const [id, session] of next) sessionsById.set(id, session);
5002
- markSessionsDirty();
5003
7546
  };
5004
- const applyActivations = (activations) => {
5005
- if (!Array.isArray(activations)) return;
5006
- const atMs = nowMs();
5007
- const seen = /* @__PURE__ */ new Set();
5008
- for (const entry of activations) {
5009
- if (!isRecord2(entry)) continue;
5010
- const key = trimmed2(entry.execution_key);
5011
- const expiresAt = Date.parse(String(entry.expires_at ?? ""));
5012
- if (!key || !Number.isFinite(expiresAt) || expiresAt <= atMs) continue;
5013
- cache.set(key, expiresAt);
5014
- seen.add(key);
7547
+ const finishCall = (functionHandle, executionHandle, failed, timing) => {
7548
+ if (sealed) {
7549
+ note2(coverage, "dropped_late_completion");
7550
+ return;
5015
7551
  }
5016
- trimCache();
5017
- for (const key of seen) pending.delete(key);
7552
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
7553
+ rotateIfNeeded(minute);
7554
+ if (minute <= lastClosedMinute && !active.has(minute)) {
7555
+ note2(coverage, "dropped_late_completion");
7556
+ return;
7557
+ }
7558
+ const series = ensureSeries(minute, functionHandle, executionHandle);
7559
+ if (!series) return;
7560
+ const remembered = timing === void 0 ? rememberOutcome(series, failed) : timing.startedNs !== void 0 && timing.endedNs !== void 0 ? rememberCompletion(series, timing.startedNs, failed, timing.endedNs) : rememberInvalidTiming(series, failed);
7561
+ if (!remembered) note2(coverage, "dropped_unexportable");
5018
7562
  };
5019
- const catalogTypes = () => {
5020
- const entries = [];
5021
- for (const [executionKey, lastSeenAtMs] of catalog) {
5022
- entries.push({ executionKey, lastSeenAtMs });
5023
- if (entries.length >= MAX_PENDING_TYPES) break;
7563
+ const beginCall = (input) => {
7564
+ const functionHandle = internDeclaration(input.declaration);
7565
+ if (functionHandle === void 0) return void 0;
7566
+ if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey2(input.executionKey)) {
7567
+ startCall(functionHandle, void 0);
7568
+ return void 0;
5024
7569
  }
5025
- return entries;
7570
+ const executionHandle = internExecutionKey(input.executionKey);
7571
+ if (executionHandle === void 0) return void 0;
7572
+ const started = startCall(functionHandle, executionHandle, {
7573
+ measure: input.measure,
7574
+ ..."startedNs" in input ? { startedNs: input.startedNs } : {}
7575
+ });
7576
+ if (!started) return void 0;
7577
+ return {
7578
+ settled: false,
7579
+ functionHandle,
7580
+ executionHandle,
7581
+ startedNs: started.startedNs,
7582
+ measure: started.measure
7583
+ };
5026
7584
  };
5027
- const syncOnce = async (signal) => {
5028
- if (!networkEnabled || closed) return;
5029
- const types2 = catalogTypes();
7585
+ const completeCall = (call, failed) => {
7586
+ if (!call || call.settled) return;
7587
+ call.settled = true;
7588
+ if (!call.measure) {
7589
+ finishCall(call.functionHandle, call.executionHandle, failed);
7590
+ return;
7591
+ }
7592
+ let endedNs;
5030
7593
  try {
5031
- const { response, body: payload } = await postJson(
5032
- options.syncUrl,
5033
- {
5034
- environment,
5035
- instance: {
5036
- id: instanceId,
5037
- sdk_name: options.sdkName,
5038
- sdk_version: options.sdkVersion,
5039
- release: options.release,
5040
- pid: process.pid,
5041
- started_at: startedAt.toISOString(),
5042
- reported_mode: options.mode,
5043
- reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
5044
- capabilities
5045
- },
5046
- types: types2.map((entry) => ({
5047
- execution_key: entry.executionKey,
5048
- last_seen_at: new Date(entry.lastSeenAtMs).toISOString()
5049
- }))
5050
- },
5051
- signal,
5052
- async (syncResponse) => {
5053
- if (!syncResponse.ok) return void 0;
5054
- return unwrapPayload(await syncResponse.json());
5055
- }
5056
- );
5057
- if (!response.ok) {
5058
- rememberFailure(classifyHttpFailure(response.status));
5059
- refreshFailures++;
5060
- return;
5061
- }
5062
- applyActivations(payload?.activations);
5063
- applySessions(payload?.sessions);
5064
- for (const entry of types2) {
5065
- const current = catalog.get(entry.executionKey);
5066
- if (current === void 0) continue;
5067
- catalog.delete(entry.executionKey);
5068
- if (current !== entry.lastSeenAtMs) {
5069
- catalog.set(entry.executionKey, current);
5070
- }
5071
- }
5072
- } catch (error) {
5073
- if (signal.aborted || error instanceof Error && error.name === "AbortError") {
5074
- rememberFailure("aborted");
5075
- } else {
5076
- rememberFailure("network_error");
5077
- }
5078
- refreshFailures++;
7594
+ endedNs = clock.monotonicNs();
7595
+ } catch {
7596
+ endedNs = void 0;
5079
7597
  }
7598
+ finishCall(call.functionHandle, call.executionHandle, failed, {
7599
+ startedNs: call.startedNs,
7600
+ endedNs
7601
+ });
5080
7602
  };
5081
- const runSyncOnce = async (signal) => {
5082
- if (syncFlight) {
5083
- await joinUntil(syncFlight, signal);
5084
- return;
7603
+ const drain = (drainOptions) => {
7604
+ if (!sealed) {
7605
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3));
7606
+ if (drainOptions?.flushAll) snapshotActive();
5085
7607
  }
5086
- const running = syncOnce(signal);
5087
- const flight = running.finally(() => {
5088
- if (syncFlight === flight) syncFlight = void 0;
7608
+ const batches = functionMetricsBatchesFromQueue({
7609
+ environment: options.environment,
7610
+ release: options.release,
7611
+ producerId: options.producerId,
7612
+ batchId,
7613
+ maxFunctions: limits.maxFunctions,
7614
+ maxExecutionTypes: limits.maxExecutionTypes,
7615
+ maxMinuteRows: limits.maxMinuteRows,
7616
+ functions,
7617
+ executionKeys,
7618
+ queued: queue,
7619
+ coverage: { ...coverage, covered_bucket_starts: [] },
7620
+ measurementFormat
5089
7621
  });
5090
- syncFlight = flight;
5091
- await joinUntil(flight, signal);
7622
+ if (batches.length === 0) return [];
7623
+ for (const queued of queue) stateBytes -= queued.bytes;
7624
+ if (stateBytes < 0) stateBytes = 0;
7625
+ queue.length = 0;
7626
+ coverage.skipped_unresolved_execution_type = 0;
7627
+ coverage.dropped_active_series = 0;
7628
+ coverage.dropped_byte_budget = 0;
7629
+ coverage.dropped_queue_budget = 0;
7630
+ coverage.dropped_late_completion = 0;
7631
+ coverage.dropped_unexportable = 0;
7632
+ return batches;
5092
7633
  };
5093
- const sendRecordings = async (batch, signal) => {
5094
- const followed = new AbortController();
5095
- const stopParent = abortFrom(signal, followed);
5096
- const stopCancel = abortFrom(cancelWork.signal, followed);
5097
- const combined = followed.signal;
5098
- try {
5099
- if (combined.aborted) return false;
5100
- let encoded;
5101
- try {
5102
- encoded = await encodeJsonRequestBodyAsync(
5103
- {
5104
- instance_id: instanceId,
5105
- recordings: batch.map((item) => ({
5106
- session_id: item.sessionId,
5107
- execution_id: item.executionId,
5108
- outcome: item.outcome,
5109
- runtime_state: item.runtimeState,
5110
- release: options.release,
5111
- redact_keys: copyRedactKeys([
5112
- ...redactKeys ?? [],
5113
- ...item.redactKeys ?? []
5114
- ])?.slice(0, MAX_REDACT_KEYS),
5115
- scrub_pii: item.scrubPii ?? scrubPii
5116
- }))
5117
- },
5118
- void 0,
5119
- combined
5120
- );
5121
- } catch (error) {
5122
- if (combined.aborted || error instanceof Error && error.name === "AbortError") {
5123
- rememberFailure("aborted");
5124
- return false;
5125
- }
5126
- rememberFailure("network_error");
5127
- return false;
5128
- }
5129
- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
5130
- if (combined.aborted) return false;
5131
- try {
5132
- const { response, body } = await postEncoded(
5133
- options.recordingsUrl,
5134
- encoded,
5135
- combined,
5136
- async (uploadResponse) => {
5137
- if (!uploadResponse.ok) return void 0;
5138
- try {
5139
- return unwrapPayload(await uploadResponse.json());
5140
- } catch {
5141
- return void 0;
5142
- }
5143
- }
5144
- );
5145
- if (response.ok) {
5146
- applyCompletedSessionIds(body?.completed_session_ids);
5147
- return true;
5148
- }
5149
- const kind = classifyHttpFailure(response.status);
5150
- rememberFailure(kind);
5151
- if (kind === "non_retryable_http") return true;
5152
- if (attempt === MAX_RETRIES) return false;
5153
- await wait(backoffMs(attempt), combined);
5154
- } catch (error) {
5155
- if (combined.aborted || error instanceof Error && error.name === "AbortError") {
5156
- rememberFailure("aborted");
5157
- return false;
5158
- }
5159
- rememberFailure("network_error");
5160
- if (attempt === MAX_RETRIES) return false;
5161
- await wait(backoffMs(attempt), combined);
5162
- }
5163
- }
5164
- return false;
5165
- } finally {
5166
- stopParent();
5167
- stopCancel();
7634
+ return {
7635
+ internDeclaration,
7636
+ internExecutionKey,
7637
+ startCall,
7638
+ finishCall,
7639
+ beginCall,
7640
+ completeCall,
7641
+ drain,
7642
+ seal: () => {
7643
+ if (sealed) return;
7644
+ sealed = true;
7645
+ moveAllActive();
5168
7646
  }
5169
7647
  };
5170
- const drainRecordings = async (signal) => {
5171
- while (recordings.length > 0 && !signal.aborted) {
5172
- const batch = recordings.splice(0, 8);
5173
- const ok = await sendRecordings(batch, signal);
5174
- if (!ok) {
5175
- recordings.unshift(...batch);
5176
- break;
5177
- }
5178
- }
7648
+ };
7649
+
7650
+ // src/function-metrics/encode-function-metrics-upload.ts
7651
+ import {
7652
+ encodeFunctionMetricsBatch,
7653
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync3,
7654
+ FUNCTION_METRICS_BUCKET_LATENESS_MS as FUNCTION_METRICS_BUCKET_LATENESS_MS2,
7655
+ FUNCTION_METRICS_MAX_DECODED_BYTES as FUNCTION_METRICS_MAX_DECODED_BYTES2,
7656
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS4,
7657
+ parseFunctionMetricsBucketStart as parseFunctionMetricsBucketStart2
7658
+ } from "@rasputin-ai/core";
7659
+ var minuteMarks2 = (minute) => {
7660
+ const next = minute.started_calls + minute.completed_calls;
7661
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
7662
+ };
7663
+ var expiresAtMsFor2 = (batch, nowMs) => {
7664
+ let oldest;
7665
+ for (const start of batch.coverage.covered_bucket_starts) {
7666
+ const bucket = parseFunctionMetricsBucketStart2(start);
7667
+ if (bucket === void 0) continue;
7668
+ if (oldest === void 0 || bucket < oldest) oldest = bucket;
7669
+ }
7670
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
7671
+ return oldest + FUNCTION_METRICS_MINUTE_MS4 + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
7672
+ };
7673
+ var zeroLossCoverage2 = (coverage) => ({
7674
+ ...coverage,
7675
+ skipped_unresolved_execution_type: 0,
7676
+ dropped_active_series: 0,
7677
+ dropped_byte_budget: 0,
7678
+ dropped_queue_budget: 0,
7679
+ dropped_late_completion: 0,
7680
+ dropped_unexportable: 0
7681
+ });
7682
+ var projectMinutes2 = (source, minutes, coverage, batchId) => {
7683
+ const functionIndexes = /* @__PURE__ */ new Map();
7684
+ const typeIndexes = /* @__PURE__ */ new Map();
7685
+ const functions = [];
7686
+ const executionTypes = [];
7687
+ const remapped = [];
7688
+ for (const minute of minutes) {
7689
+ let functionIndex = functionIndexes.get(minute.function_index);
7690
+ if (functionIndex === void 0) {
7691
+ const declaration = source.functions[minute.function_index];
7692
+ if (!declaration) continue;
7693
+ functionIndex = functions.length;
7694
+ functionIndexes.set(minute.function_index, functionIndex);
7695
+ functions.push(declaration);
7696
+ }
7697
+ let executionTypeIndex = typeIndexes.get(minute.execution_type_index);
7698
+ if (executionTypeIndex === void 0) {
7699
+ const entry = source.execution_types[minute.execution_type_index];
7700
+ if (!entry) continue;
7701
+ executionTypeIndex = executionTypes.length;
7702
+ typeIndexes.set(minute.execution_type_index, executionTypeIndex);
7703
+ executionTypes.push(entry);
7704
+ }
7705
+ remapped.push({
7706
+ ...minute,
7707
+ function_index: functionIndex,
7708
+ execution_type_index: executionTypeIndex
7709
+ });
7710
+ }
7711
+ const covered = [...new Set(remapped.map((minute) => minute.bucket_start))].sort();
7712
+ return {
7713
+ ...source,
7714
+ batch_id: batchId,
7715
+ functions,
7716
+ execution_types: executionTypes,
7717
+ minutes: remapped,
7718
+ coverage: { ...coverage, covered_bucket_starts: covered }
7719
+ };
7720
+ };
7721
+ var withLoss2 = (batch, loss) => ({
7722
+ ...batch,
7723
+ coverage: {
7724
+ ...batch.coverage,
7725
+ dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
7726
+ dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
7727
+ }
7728
+ });
7729
+ var encodeOne2 = async (batch, nowMs, signal) => {
7730
+ const decodedBytes = encodeFunctionMetricsBatch(batch);
7731
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES2) return void 0;
7732
+ const encoded = await encodeJsonRequestBodyAsync3(decodedBytes, void 0, signal);
7733
+ return {
7734
+ decodedBytes,
7735
+ body: encoded.body,
7736
+ gzip: encoded.gzip,
7737
+ batchId: batch.batch_id,
7738
+ expiresAtMs: expiresAtMsFor2(batch, nowMs)
7739
+ };
7740
+ };
7741
+ var encodeFitting2 = async (batch, nowMs, signal) => {
7742
+ const encoded = await encodeOne2(batch, nowMs, signal);
7743
+ if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
7744
+ if (batch.minutes.length <= 1) {
7745
+ return {
7746
+ uploads: [],
7747
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks2(minute), 0)
7748
+ };
7749
+ }
7750
+ const mid = Math.ceil(batch.minutes.length / 2);
7751
+ const first = projectMinutes2(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
7752
+ const rest = projectMinutes2(
7753
+ batch,
7754
+ batch.minutes.slice(mid),
7755
+ zeroLossCoverage2(batch.coverage),
7756
+ newFunctionMetricsBatchId()
7757
+ );
7758
+ const left = await encodeFitting2(first, nowMs, signal);
7759
+ const right = await encodeFitting2(rest, nowMs, signal);
7760
+ return {
7761
+ uploads: [...left.uploads, ...right.uploads],
7762
+ droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
5179
7763
  };
5180
- const kickRecordings = () => {
5181
- if (!networkEnabled || closed || closing || recordings.length === 0) return;
5182
- if (recordingPump) return;
5183
- const running = drainRecordings(recordingSignal());
5184
- recordingPump = running;
5185
- void running.finally(() => {
5186
- if (recordingPump === running) recordingPump = void 0;
5187
- if (recordings.length > 0) kickRecordings();
7764
+ };
7765
+ var encodeFunctionMetricsUploads = async (batches, input) => {
7766
+ const uploads = [];
7767
+ let extra = {
7768
+ dropped_unexportable: 0,
7769
+ dropped_queue_budget: input.queueDrops ?? 0
7770
+ };
7771
+ for (const batch of batches) {
7772
+ const fitted = await encodeFitting2(withLoss2(batch, extra), input.nowMs, input.signal);
7773
+ extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
7774
+ uploads.push(...fitted.uploads);
7775
+ }
7776
+ return uploads;
7777
+ };
7778
+
7779
+ // src/function-metrics/function-metrics-exporter.ts
7780
+ var MAX_QUEUE_ITEMS2 = 32;
7781
+ var MAX_QUEUE_BYTES2 = 4 * 1024 * 1024;
7782
+ var DEFAULT_SCHEDULE_MS2 = 6e4;
7783
+ var FLUSH_MS2 = 1e4;
7784
+ var SHUTDOWN_FLUSH_MS2 = 2e3;
7785
+ var MAX_ATTEMPTS2 = 8;
7786
+ var sleep2 = (ms, signal) => new Promise((resolve) => {
7787
+ if (ms <= 0 || signal.aborted) {
7788
+ resolve();
7789
+ return;
7790
+ }
7791
+ const timer = setTimeout(finish, ms);
7792
+ timer.unref?.();
7793
+ const onAbort = () => {
7794
+ clearTimeout(timer);
7795
+ finish();
7796
+ };
7797
+ function finish() {
7798
+ signal.removeEventListener("abort", onAbort);
7799
+ resolve();
7800
+ }
7801
+ signal.addEventListener("abort", onAbort);
7802
+ if (signal.aborted) onAbort();
7803
+ });
7804
+ var createFunctionMetricsExporter = (input) => {
7805
+ const nowMs = input.nowMs ?? Date.now;
7806
+ const random = input.random ?? Math.random;
7807
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS2;
7808
+ const queue = [];
7809
+ let queueBytes = 0;
7810
+ let queueDrops = 0;
7811
+ let timer;
7812
+ let closed = false;
7813
+ let halted = false;
7814
+ let stopped = false;
7815
+ let workAbort;
7816
+ let work;
7817
+ let sent = 0;
7818
+ let dropped = 0;
7819
+ let warnedHalt = null;
7820
+ const dropOldest = () => {
7821
+ const oldest = queue.shift();
7822
+ if (!oldest) return;
7823
+ queueBytes -= oldest.upload.decodedBytes.byteLength;
7824
+ if (queueBytes < 0) queueBytes = 0;
7825
+ queueDrops += 1;
7826
+ dropped += 1;
7827
+ };
7828
+ const enqueue = (upload) => {
7829
+ queue.push({ upload, attempt: 0 });
7830
+ queueBytes += upload.decodedBytes.byteLength;
7831
+ while (queue.length > MAX_QUEUE_ITEMS2 || queueBytes > MAX_QUEUE_BYTES2) dropOldest();
7832
+ };
7833
+ const drainAndEnqueue = async (flushAll2) => {
7834
+ if (halted || stopped) return;
7835
+ const batches = input.collector.drain({ flushAll: flushAll2 });
7836
+ if (batches.length === 0) return;
7837
+ const encoded = await encodeFunctionMetricsUploads(batches, {
7838
+ nowMs: nowMs(),
7839
+ queueDrops
5188
7840
  });
7841
+ if (encoded.length === 0 || halted || stopped) return;
7842
+ queueDrops = 0;
7843
+ for (const upload of encoded) enqueue(upload);
7844
+ };
7845
+ const warnHalt = (status) => {
7846
+ if (warnedHalt === status) return;
7847
+ warnedHalt = status;
7848
+ if (status === 401 || status === 403) {
7849
+ console.warn("[rasputin] function metrics export stopped: authentication failed");
7850
+ return;
7851
+ }
7852
+ if (status === 404) {
7853
+ console.warn("[rasputin] function metrics export stopped: ingest route is unavailable");
7854
+ }
5189
7855
  };
5190
- const activate = (metadata, window) => {
5191
- if (closed || options.mode !== "adaptive") return;
5192
- const key = executionTypeKey(metadata);
5193
- if (!key) return;
5194
- const atMs = nowMs();
5195
- const existing = cache.get(key);
5196
- if (existing !== void 0 && existing > atMs) return;
5197
- cache.set(key, window.expiresAtMs);
5198
- trimCache();
5199
- if (!networkEnabled || window.expiresAtMs <= atMs) return;
5200
- if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
5201
- for (const oldest of pending.keys()) {
5202
- if (oldest !== sendingKey) {
5203
- pending.delete(oldest);
5204
- break;
7856
+ const pump = async (signal) => {
7857
+ while (queue.length > 0 && !halted && !stopped && !signal.aborted) {
7858
+ const item = queue[0];
7859
+ if (!item) return;
7860
+ if (item.upload.expiresAtMs <= nowMs()) {
7861
+ queue.shift();
7862
+ queueBytes -= item.upload.decodedBytes.byteLength;
7863
+ dropped += 1;
7864
+ continue;
7865
+ }
7866
+ if (item.attempt >= MAX_ATTEMPTS2) {
7867
+ queue.shift();
7868
+ queueBytes -= item.upload.decodedBytes.byteLength;
7869
+ dropped += 1;
7870
+ continue;
7871
+ }
7872
+ const result = await sendFunctionMetricsBatch({
7873
+ url: input.url,
7874
+ ingestToken: input.ingestToken,
7875
+ upload: item.upload,
7876
+ fetch: input.fetch,
7877
+ signal,
7878
+ attempt: item.attempt,
7879
+ random,
7880
+ nowMs
7881
+ });
7882
+ if (result.outcome === "aborted") return;
7883
+ if (result.outcome === "ok") {
7884
+ queue.shift();
7885
+ queueBytes -= item.upload.decodedBytes.byteLength;
7886
+ sent += 1;
7887
+ continue;
7888
+ }
7889
+ if (result.outcome === "terminal") {
7890
+ queue.shift();
7891
+ queueBytes -= item.upload.decodedBytes.byteLength;
7892
+ dropped += 1;
7893
+ if (result.halt) {
7894
+ halted = true;
7895
+ warnHalt(result.status);
5205
7896
  }
7897
+ continue;
5206
7898
  }
5207
- }
5208
- pending.set(key, { executionKey: key, ...window });
5209
- kickNotify();
7899
+ item.attempt += 1;
7900
+ await sleep2(result.waitMs, signal);
7901
+ }
7902
+ };
7903
+ const abortCurrent = () => {
7904
+ workAbort?.abort();
7905
+ };
7906
+ const raceUntilAborted = async (running, signal) => {
7907
+ if (signal.aborted) return;
7908
+ await new Promise((resolve) => {
7909
+ let settled = false;
7910
+ const finish = () => {
7911
+ if (settled) return;
7912
+ settled = true;
7913
+ signal.removeEventListener("abort", finish);
7914
+ resolve();
7915
+ };
7916
+ signal.addEventListener("abort", finish);
7917
+ if (signal.aborted) {
7918
+ finish();
7919
+ return;
7920
+ }
7921
+ void running.then(finish, finish);
7922
+ });
5210
7923
  };
5211
- const peekSessions = () => {
5212
- if (sessionsDirty) rebuildSessionSnapshot();
5213
- else {
5214
- const atMs = nowMs();
5215
- for (const session of sessionSnapshot.values()) {
5216
- if (session.expiresAtMs <= atMs) {
5217
- rebuildSessionSnapshot();
5218
- break;
5219
- }
7924
+ const runWork = async (signal, task) => {
7925
+ const onAbort = () => abortCurrent();
7926
+ signal.addEventListener("abort", onAbort);
7927
+ if (signal.aborted) abortCurrent();
7928
+ try {
7929
+ while (work) {
7930
+ const previous = work;
7931
+ await raceUntilAborted(previous, signal);
7932
+ if (signal.aborted || halted) return;
7933
+ if (work === previous) return;
7934
+ }
7935
+ if (halted) return;
7936
+ const inner = new AbortController();
7937
+ workAbort = inner;
7938
+ if (signal.aborted) {
7939
+ workAbort = void 0;
7940
+ return;
5220
7941
  }
7942
+ const running = task(inner.signal).finally(() => {
7943
+ if (workAbort === inner) workAbort = void 0;
7944
+ if (work === running) work = void 0;
7945
+ });
7946
+ work = running;
7947
+ await raceUntilAborted(running, signal);
7948
+ } finally {
7949
+ signal.removeEventListener("abort", onAbort);
5221
7950
  }
5222
- return sessionSnapshot;
5223
7951
  };
5224
- const consumeSession = (executionKeyValue, sessionId) => {
5225
- const atMs = nowMs();
5226
- for (const session of sessionsById.values()) {
5227
- if (session.executionKey !== executionKeyValue) continue;
5228
- if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
5229
- if (!sessionHasRoom(session, atMs)) continue;
5230
- session.admitted += 1;
5231
- markSessionsDirty();
5232
- return sessionView(session);
7952
+ const tick = async () => {
7953
+ if (closed || halted) return;
7954
+ try {
7955
+ await runWork(new AbortController().signal, async (signal) => {
7956
+ if (closed || halted) return;
7957
+ await drainAndEnqueue(false);
7958
+ await pump(signal);
7959
+ });
7960
+ } catch {
5233
7961
  }
5234
- return void 0;
5235
- };
5236
- const observeType = (executionKeyValue) => {
5237
- rememberCatalog(executionKeyValue, nowMs());
5238
- };
5239
- const enqueueRecording = (payload) => {
5240
- if (closed || closing) return;
5241
- recordings.push(payload);
5242
- kickRecordings();
7962
+ if (!closed && !halted) arm();
5243
7963
  };
5244
- if (networkEnabled) {
5245
- const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
5246
- const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
5247
- const delay = interval + Math.floor(Math.random() * jitterMax);
5248
- pollStartTimer = setTimeout(() => {
5249
- pollStartTimer = void 0;
5250
- if (closed || closing) return;
5251
- void runSyncOnce(pollSignal());
5252
- pollTimer = setInterval(() => {
5253
- if (closed || closing) return;
5254
- void runSyncOnce(pollSignal());
5255
- }, interval);
5256
- pollTimer.unref?.();
7964
+ const arm = () => {
7965
+ if (closed || halted) return;
7966
+ const delay = Math.max(1e3, Math.floor(scheduleMs * (0.85 + random() * 0.3)));
7967
+ timer = setTimeout(() => {
7968
+ void tick();
5257
7969
  }, delay);
5258
- pollStartTimer.unref?.();
5259
- }
5260
- const stopTimers = () => {
5261
- if (pollStartTimer) {
5262
- clearTimeout(pollStartTimer);
5263
- pollStartTimer = void 0;
5264
- }
5265
- if (pollTimer) {
5266
- clearInterval(pollTimer);
5267
- pollTimer = void 0;
7970
+ timer.unref?.();
7971
+ };
7972
+ arm();
7973
+ const flush = async (timeoutMs) => {
7974
+ if (closed || halted) return;
7975
+ const abort = new AbortController();
7976
+ const budget = timeoutMs ?? FLUSH_MS2;
7977
+ const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
7978
+ try {
7979
+ await runWork(abort.signal, async (signal) => {
7980
+ if (closed || halted) return;
7981
+ await drainAndEnqueue(true);
7982
+ await pump(signal);
7983
+ });
7984
+ } catch {
7985
+ } finally {
7986
+ clearTimeout(timeout);
5268
7987
  }
5269
7988
  };
5270
7989
  return {
5271
- peek,
5272
- activate,
5273
- peekSessions,
5274
- consumeSession,
5275
- observeType,
5276
- enqueueRecording,
5277
- getStats: () => ({
5278
- adaptiveNotifyFailures: notifyFailures,
5279
- adaptiveRefreshFailures: refreshFailures,
5280
- lastAdaptiveFailureKind: lastFailureKind
5281
- }),
5282
- flush: async (timeoutMs = 2e3) => {
5283
- if (!networkEnabled || closed || closing) return;
5284
- const flushAbort = new AbortController();
5285
- const onAbort = () => interruptWork();
5286
- flushAbort.signal.addEventListener("abort", onAbort, { once: true });
5287
- const timer = setTimeout(() => flushAbort.abort(), Math.max(0, timeoutMs));
5288
- try {
5289
- await runSyncOnce(flushAbort.signal);
5290
- if (!flushAbort.signal.aborted) await drainNotifies(flushAbort.signal);
5291
- await joinUntil(recordingPump, flushAbort.signal);
5292
- if (!flushAbort.signal.aborted) await drainRecordings(flushAbort.signal);
5293
- } finally {
5294
- clearTimeout(timer);
5295
- flushAbort.signal.removeEventListener("abort", onAbort);
5296
- }
5297
- },
7990
+ flush,
5298
7991
  close: async () => {
5299
- if (closed || closing) return;
5300
- closing = true;
5301
- stopTimers();
5302
- const deadline = new AbortController();
5303
- const timer = setTimeout(() => {
5304
- deadline.abort();
5305
- interruptWork();
5306
- }, 2e3);
7992
+ if (closed) return;
7993
+ closed = true;
7994
+ if (timer) clearTimeout(timer);
7995
+ timer = void 0;
7996
+ const abort = new AbortController();
7997
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS2);
7998
+ abortCurrent();
5307
7999
  try {
5308
- if (networkEnabled) await runSyncOnce(deadline.signal);
5309
- if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
5310
- await joinUntil(recordingPump, deadline.signal);
5311
- if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
8000
+ await runWork(abort.signal, async (signal) => {
8001
+ input.collector.seal();
8002
+ await drainAndEnqueue(false);
8003
+ await pump(signal);
8004
+ });
8005
+ } catch {
5312
8006
  } finally {
5313
- clearTimeout(timer);
5314
- closed = true;
5315
- interruptWork();
5316
- pending.clear();
8007
+ clearTimeout(timeout);
8008
+ stopped = true;
8009
+ input.collector.seal();
8010
+ queue.length = 0;
8011
+ queueBytes = 0;
5317
8012
  }
5318
- }
8013
+ },
8014
+ getStats: () => ({ sent, dropped, halted })
5319
8015
  };
5320
8016
  };
5321
8017
 
5322
- // src/execution-recorder/bind-adaptive-recorder.ts
5323
- var bindAdaptiveRecorder = (input) => {
5324
- const options = input.executionRecorder;
5325
- const adaptiveEnabled = options?.adaptive?.enabled === true;
5326
- const activation = resolveClientActivation({
5327
- enabled: input.enabled,
5328
- dsn: input.dsn,
5329
- projectApiKey: input.projectApiKey,
5330
- apiUrl: input.apiUrl,
5331
- release: input.release
5332
- });
5333
- const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
5334
- environment: input.environment ?? "",
5335
- ingestToken: activation.ingestToken,
5336
- activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5337
- syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5338
- recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
5339
- sdkName: input.sdkName,
5340
- sdkVersion: input.sdkVersion,
5341
- release: activation.release,
5342
- recorderOptions: options,
5343
- scrubPII: input.scrubPII,
5344
- mode: adaptiveEnabled ? "adaptive" : "full",
5345
- fetch: input.fetch
5346
- }) : void 0;
5347
- const runtime = createExecutionRecorder(
5348
- { ...options, enabled: input.recorderEnabled },
5349
- coordinator ? {
5350
- policySnapshot: coordinator.peek,
5351
- onQualifyingFailure: adaptiveEnabled ? coordinator.activate : void 0,
5352
- getStats: coordinator.getStats,
5353
- sessionCaptureSnapshot: coordinator.peekSessions,
5354
- consumeSession: coordinator.consumeSession,
5355
- observeExecutionType: coordinator.observeType,
5356
- onSessionRecording: coordinator.enqueueRecording
5357
- } : void 0
8018
+ // src/function-metrics/install-function-metric-declaration-sink.ts
8019
+ var REGISTER = "__rasputinRegisterFunctionMetricDeclarations";
8020
+ var PENDING = "__rasputinPendingFunctionMetricDeclarations";
8021
+ var installFunctionMetricDeclarationSink = () => {
8022
+ Reflect.set(globalThis, REGISTER, registerFunctionMetricDeclarations);
8023
+ const pending = Reflect.get(globalThis, PENDING);
8024
+ if (!Array.isArray(pending) || pending.length === 0) return;
8025
+ registerFunctionMetricDeclarations(pending);
8026
+ pending.length = 0;
8027
+ };
8028
+
8029
+ // src/function-metrics/bind-function-metrics.ts
8030
+ var SLOT2 = Symbol.for("rasputin.functionMetrics.runtime.v1");
8031
+ var releasedHandles2 = /* @__PURE__ */ new WeakSet();
8032
+ var isRuntime2 = (value) => {
8033
+ if (typeof value !== "object" || value === null) return false;
8034
+ return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
8035
+ };
8036
+ var bindingIdentity2 = (input) => `${input.ingestToken}
8037
+ ${input.url}
8038
+ ${input.environment}
8039
+ ${input.release}
8040
+ ${input.sampledMeasurementFormat ? "1" : "0"}`;
8041
+ var warnIncompatible2 = (runtime) => {
8042
+ if (runtime.warnedMismatch) return;
8043
+ runtime.warnedMismatch = true;
8044
+ console.warn(
8045
+ "[rasputin] function metrics already running with a different configuration; this client will not collect function metrics"
5358
8046
  );
5359
- return { runtime, policy: coordinator };
8047
+ };
8048
+ var createBindings2 = (input) => {
8049
+ installFunctionMetricDeclarationSink();
8050
+ const collector = createFunctionMetricsCollector({
8051
+ environment: input.environment,
8052
+ producerId: randomUUID4(),
8053
+ release: input.release,
8054
+ sampledMeasurementFormat: input.sampledMeasurementFormat
8055
+ });
8056
+ return {
8057
+ collector,
8058
+ exporter: createFunctionMetricsExporter({
8059
+ collector,
8060
+ url: input.url,
8061
+ ingestToken: input.ingestToken,
8062
+ fetch: input.fetch ?? defaultIngestFetch3()
8063
+ })
8064
+ };
8065
+ };
8066
+ var bindFunctionMetrics = (input) => {
8067
+ if (!input.clientEnabled) return void 0;
8068
+ if (input.options?.enabled === false) return void 0;
8069
+ const release = input.release.trim().toLowerCase();
8070
+ if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
8071
+ const url = resolveEndpointUrls4(input.apiUrl).functionMetricsUrl;
8072
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
8073
+ const key = bindingIdentity2({
8074
+ ingestToken: input.ingestToken,
8075
+ url,
8076
+ environment: input.environment,
8077
+ release,
8078
+ sampledMeasurementFormat
8079
+ });
8080
+ const existing = Reflect.get(globalThis, SLOT2);
8081
+ if (isRuntime2(existing)) {
8082
+ if (existing.identity !== key) {
8083
+ warnIncompatible2(existing);
8084
+ return void 0;
8085
+ }
8086
+ existing.refs += 1;
8087
+ return { collector: existing.collector, exporter: existing.exporter };
8088
+ }
8089
+ const bindings2 = createBindings2({
8090
+ release,
8091
+ ingestToken: input.ingestToken,
8092
+ url,
8093
+ environment: input.environment,
8094
+ fetch: input.fetch,
8095
+ sampledMeasurementFormat
8096
+ });
8097
+ Reflect.set(globalThis, SLOT2, {
8098
+ ...bindings2,
8099
+ refs: 1,
8100
+ identity: key,
8101
+ warnedMismatch: false
8102
+ });
8103
+ return bindings2;
8104
+ };
8105
+ var releaseFunctionMetricsBindings = async (bindings2) => {
8106
+ if (!bindings2 || releasedHandles2.has(bindings2)) return;
8107
+ releasedHandles2.add(bindings2);
8108
+ const existing = Reflect.get(globalThis, SLOT2);
8109
+ if (isRuntime2(existing) && existing.exporter === bindings2.exporter) {
8110
+ existing.refs -= 1;
8111
+ if (existing.refs > 0) return;
8112
+ Reflect.deleteProperty(globalThis, SLOT2);
8113
+ }
8114
+ await bindings2.exporter.close();
5360
8115
  };
5361
8116
 
5362
8117
  // src/install-global-handlers.ts
@@ -5495,9 +8250,77 @@ var installGlobalHandlers = (client, options = {}) => {
5495
8250
  };
5496
8251
  };
5497
8252
 
8253
+ // src/runtime-timing/dynamic-duration-sampling.ts
8254
+ var DYNAMIC_DURATION_SAMPLE_STAGES = [
8255
+ { below: 10, divisor: 1 },
8256
+ { below: 30, divisor: 2 },
8257
+ { below: 100, divisor: 3 },
8258
+ { below: 500, divisor: 11 },
8259
+ { below: 1e3, divisor: 23 },
8260
+ { below: 5e3, divisor: 53 }
8261
+ ];
8262
+ var MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS = 4096;
8263
+ var DYNAMIC_DURATION_SAMPLE_TAIL_AFTER = 5e3;
8264
+ var DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR = 100;
8265
+ var DYNAMIC_DURATION_SAMPLE_RESET_MS = 60 * 60 * 1e3;
8266
+ var EXECUTION_DURATION_SAMPLE_PREFIX = "\0execution-metrics\0";
8267
+ var dynamicDurationSampleDivisor = (index) => {
8268
+ for (const stage of DYNAMIC_DURATION_SAMPLE_STAGES) {
8269
+ if (index < stage.below) return stage.divisor;
8270
+ }
8271
+ return DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8272
+ };
8273
+ var shouldSampleDynamicDuration = (index) => {
8274
+ return index % dynamicDurationSampleDivisor(index) === 0;
8275
+ };
8276
+ var nextDurationSampleIndex = (index) => {
8277
+ if (index < Number.MAX_SAFE_INTEGER) return index + 1;
8278
+ return DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + (index - DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + 1) % DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8279
+ };
8280
+ var createDynamicDurationSampleBuckets = (options) => {
8281
+ const functionBuckets = /* @__PURE__ */ new Map();
8282
+ const executionBuckets = /* @__PURE__ */ new Map();
8283
+ const maxBuckets = options.maxBuckets ?? MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS;
8284
+ const resetMs = options.resetMs ?? DYNAMIC_DURATION_SAMPLE_RESET_MS;
8285
+ let lastResetAtMs = options.nowMs();
8286
+ let stopped = false;
8287
+ const reset = () => {
8288
+ functionBuckets.clear();
8289
+ executionBuckets.clear();
8290
+ lastResetAtMs = options.nowMs();
8291
+ };
8292
+ const resetTimer = setInterval(reset, resetMs);
8293
+ resetTimer.unref?.();
8294
+ const takeKey = (buckets, key) => {
8295
+ if (options.nowMs() - lastResetAtMs >= resetMs) reset();
8296
+ const existing = buckets.get(key);
8297
+ if (existing !== void 0) {
8298
+ buckets.delete(key);
8299
+ buckets.set(key, nextDurationSampleIndex(existing));
8300
+ return shouldSampleDynamicDuration(existing);
8301
+ }
8302
+ while (buckets.size >= maxBuckets) {
8303
+ const oldest = buckets.keys().next().value;
8304
+ if (oldest === void 0) break;
8305
+ buckets.delete(oldest);
8306
+ }
8307
+ buckets.set(key, nextDurationSampleIndex(0));
8308
+ return shouldSampleDynamicDuration(0);
8309
+ };
8310
+ return {
8311
+ take: (executionType, callerFunctionId, functionId) => takeKey(functionBuckets, `${executionType}\0${callerFunctionId}\0${functionId}`),
8312
+ takeExecution: (executionType) => takeKey(executionBuckets, `${EXECUTION_DURATION_SAMPLE_PREFIX}${executionType}`),
8313
+ stop: () => {
8314
+ if (stopped) return;
8315
+ stopped = true;
8316
+ clearInterval(resetTimer);
8317
+ }
8318
+ };
8319
+ };
8320
+
5498
8321
  // src/sdk-meta.ts
5499
8322
  var SDK_NAME = "@rasputin-ai/node";
5500
- var SDK_VERSION = "0.13.0";
8323
+ var SDK_VERSION = "0.14.0";
5501
8324
 
5502
8325
  // src/rasputin-init.ts
5503
8326
  var publicExecution = (runtime) => ({
@@ -5513,7 +8336,7 @@ var publicExecution = (runtime) => ({
5513
8336
  getStats: runtime.getStats
5514
8337
  });
5515
8338
  var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
5516
- }, policy) => {
8339
+ }, policy, metrics, executionMetrics) => {
5517
8340
  const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
5518
8341
  };
5519
8342
  const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
@@ -5533,10 +8356,14 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
5533
8356
  await client.flush(timeoutMs);
5534
8357
  if (timeoutMs === void 0) {
5535
8358
  await policy?.flush();
8359
+ await metrics?.exporter.flush();
8360
+ await executionMetrics?.exporter.flush();
5536
8361
  await manifestUpload.wait();
5537
8362
  return;
5538
8363
  }
5539
8364
  await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8365
+ await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8366
+ await executionMetrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
5540
8367
  await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
5541
8368
  },
5542
8369
  close: async () => {
@@ -5546,15 +8373,40 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
5546
8373
  manifestUpload.disconnect();
5547
8374
  const startedAt = Date.now();
5548
8375
  await policy?.close();
8376
+ await releaseFunctionMetricsBindings(metrics);
8377
+ await releaseExecutionMetricsBindings(executionMetrics);
5549
8378
  await client.close();
5550
8379
  await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
5551
8380
  }
5552
8381
  };
5553
8382
  };
5554
- var RasputinInit = (options) => {
8383
+ function RasputinInit(options, hooks = {}) {
5555
8384
  try {
5556
8385
  const enabled = isClientEnabled(options);
8386
+ const activation = resolveClientActivation2(options);
5557
8387
  const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
8388
+ const durationSampling = options.dynamicDurationSampling === true;
8389
+ const metrics = activation.enabled ? bindFunctionMetrics({
8390
+ options: options.functionMetrics,
8391
+ clientEnabled: true,
8392
+ environment: activation.environment,
8393
+ release: activation.release,
8394
+ ingestToken: activation.ingestToken,
8395
+ apiUrl: activation.apiUrl,
8396
+ fetch: hooks.fetch,
8397
+ sampledMeasurementFormat: durationSampling
8398
+ }) : void 0;
8399
+ const executionMetrics = activation.enabled ? bindExecutionMetrics({
8400
+ options: options.executionMetrics,
8401
+ clientEnabled: true,
8402
+ environment: activation.environment,
8403
+ release: activation.release,
8404
+ ingestToken: activation.ingestToken,
8405
+ apiUrl: activation.apiUrl,
8406
+ fetch: hooks.fetch,
8407
+ sampledMeasurementFormat: durationSampling
8408
+ }) : void 0;
8409
+ const durationSampler = durationSampling && (recorderEnabled || Boolean(metrics) || Boolean(executionMetrics)) ? createDynamicDurationSampleBuckets({ nowMs: () => Date.now() }) : void 0;
5558
8410
  const { runtime, policy } = bindAdaptiveRecorder({
5559
8411
  executionRecorder: options.executionRecorder,
5560
8412
  recorderEnabled,
@@ -5566,11 +8418,16 @@ var RasputinInit = (options) => {
5566
8418
  enabled: options.enabled,
5567
8419
  sdkName: SDK_NAME,
5568
8420
  sdkVersion: SDK_VERSION,
5569
- scrubPII: options.scrubPII
8421
+ scrubPII: options.scrubPII,
8422
+ fetch: hooks.fetch,
8423
+ functionMetrics: metrics?.collector,
8424
+ executionMetrics: executionMetrics?.collector,
8425
+ durationSampler
5570
8426
  });
5571
8427
  const client = createClient(options, {
5572
8428
  sdkVersion: SDK_VERSION,
5573
8429
  sdkName: SDK_NAME,
8430
+ fetch: hooks.fetch,
5574
8431
  installTransportSignalHandlers: options.installTransportSignalHandlers,
5575
8432
  redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
5576
8433
  resolveObservation: (observation) => runtime.getErrorState(observation)
@@ -5585,7 +8442,7 @@ var RasputinInit = (options) => {
5585
8442
  const wrappedClient = withExecution(
5586
8443
  client,
5587
8444
  runtime,
5588
- recorderEnabled,
8445
+ recorderEnabled || Boolean(metrics),
5589
8446
  {
5590
8447
  projectApiKey: options.projectApiKey,
5591
8448
  release: options.release,
@@ -5596,7 +8453,9 @@ var RasputinInit = (options) => {
5596
8453
  logSuccess: options.logSuccess
5597
8454
  },
5598
8455
  () => uninstallHandlers(),
5599
- policy
8456
+ policy,
8457
+ metrics,
8458
+ executionMetrics
5600
8459
  );
5601
8460
  if (enabled && options.installGlobalHandlers !== false) {
5602
8461
  uninstallHandlers = installGlobalHandlers(wrappedClient);
@@ -5618,7 +8477,7 @@ var RasputinInit = (options) => {
5618
8477
  }
5619
8478
  );
5620
8479
  }
5621
- };
8480
+ }
5622
8481
  export {
5623
8482
  RasputinInit
5624
8483
  };