@rasputin-ai/node 0.13.1 → 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 (52) hide show
  1. package/dist/execution-metrics/bind-execution-metrics.d.ts +20 -0
  2. package/dist/execution-metrics/bind-execution-metrics.d.ts.map +1 -0
  3. package/dist/execution-metrics/encode-execution-metrics-upload.d.ts +14 -0
  4. package/dist/execution-metrics/encode-execution-metrics-upload.d.ts.map +1 -0
  5. package/dist/execution-metrics/execution-metrics-batches.d.ts +34 -0
  6. package/dist/execution-metrics/execution-metrics-batches.d.ts.map +1 -0
  7. package/dist/execution-metrics/execution-metrics-collector.d.ts +44 -0
  8. package/dist/execution-metrics/execution-metrics-collector.d.ts.map +1 -0
  9. package/dist/execution-metrics/execution-metrics-exporter.d.ts +23 -0
  10. package/dist/execution-metrics/execution-metrics-exporter.d.ts.map +1 -0
  11. package/dist/execution-recorder/adaptive-recording-options.d.ts +0 -2
  12. package/dist/execution-recorder/adaptive-recording-options.d.ts.map +1 -1
  13. package/dist/execution-recorder/bind-adaptive-recorder.d.ts +4 -0
  14. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -1
  15. package/dist/execution-recorder/execution-identity.d.ts +6 -0
  16. package/dist/execution-recorder/execution-identity.d.ts.map +1 -1
  17. package/dist/execution-recorder/execution-journal.d.ts +1 -0
  18. package/dist/execution-recorder/execution-journal.d.ts.map +1 -1
  19. package/dist/execution-recorder/execution-recorder-hooks.d.ts +6 -0
  20. package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -1
  21. package/dist/execution-recorder/execution-recorder-types.d.ts +0 -10
  22. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  23. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  24. package/dist/function-metrics/bind-function-metrics.d.ts +1 -0
  25. package/dist/function-metrics/bind-function-metrics.d.ts.map +1 -1
  26. package/dist/function-metrics/create-metrics-only-runtime.d.ts +7 -1
  27. package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -1
  28. package/dist/function-metrics/function-metrics-batches.d.ts +2 -1
  29. package/dist/function-metrics/function-metrics-batches.d.ts.map +1 -1
  30. package/dist/function-metrics/function-metrics-collector.d.ts +18 -3
  31. package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -1
  32. package/dist/function-metrics/intern-prepared-metrics.d.ts +2 -0
  33. package/dist/function-metrics/intern-prepared-metrics.d.ts.map +1 -1
  34. package/dist/function-metrics/settle-function-metrics.d.ts +7 -4
  35. package/dist/function-metrics/settle-function-metrics.d.ts.map +1 -1
  36. package/dist/index.js +1849 -461
  37. package/dist/instrument/bun.js +1 -1
  38. package/dist/instrument/node.js +1 -1
  39. package/dist/internal.d.ts +3 -0
  40. package/dist/internal.d.ts.map +1 -1
  41. package/dist/internal.js +1828 -456
  42. package/dist/rasputin-init.d.ts +23 -3
  43. package/dist/rasputin-init.d.ts.map +1 -1
  44. package/dist/runtime-timing/call-duration.d.ts +13 -0
  45. package/dist/runtime-timing/call-duration.d.ts.map +1 -0
  46. package/dist/{execution-recorder → runtime-timing}/dynamic-duration-sampling.d.ts +6 -4
  47. package/dist/runtime-timing/dynamic-duration-sampling.d.ts.map +1 -0
  48. package/dist/runtime-timing/execution-duration.d.ts +5 -0
  49. package/dist/runtime-timing/execution-duration.d.ts.map +1 -0
  50. package/dist/sdk-meta.d.ts +1 -1
  51. package/package.json +2 -2
  52. package/dist/execution-recorder/dynamic-duration-sampling.d.ts.map +0 -1
package/dist/internal.js CHANGED
@@ -647,6 +647,1018 @@ var scheduleInstrumentationManifestUpload = (options) => {
647
647
  };
648
648
  };
649
649
 
650
+ // src/execution-metrics/bind-execution-metrics.ts
651
+ import { randomUUID as randomUUID2 } from "node:crypto";
652
+ import {
653
+ defaultIngestFetch,
654
+ resolveEndpointUrls as resolveEndpointUrls2
655
+ } from "@rasputin-ai/core";
656
+
657
+ // src/execution-metrics/execution-metrics-collector.ts
658
+ import {
659
+ durationHistogramBucket,
660
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
661
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES,
662
+ FUNCTION_METRICS_MAX_BUFFERED_MS,
663
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES,
664
+ FUNCTION_METRICS_MAX_MINUTE_ROWS,
665
+ FUNCTION_METRICS_MAX_STATE_BYTES,
666
+ FUNCTION_METRICS_MEASUREMENT_FORMAT,
667
+ FUNCTION_METRICS_MINUTE_MS,
668
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT,
669
+ isCanonicalFunctionMetricsExecutionKey
670
+ } from "@rasputin-ai/core";
671
+
672
+ // src/execution-metrics/execution-metrics-batches.ts
673
+ import { randomUUID } from "node:crypto";
674
+ import {
675
+ EXECUTION_METRICS_SCHEMA_VERSION
676
+ } from "@rasputin-ai/core";
677
+ var emptyCoverage = (buckets) => ({
678
+ covered_bucket_starts: buckets,
679
+ skipped_unresolved_execution_type: 0,
680
+ dropped_active_series: 0,
681
+ dropped_byte_budget: 0,
682
+ dropped_queue_budget: 0,
683
+ dropped_late_completion: 0,
684
+ dropped_unexportable: 0
685
+ });
686
+ var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
687
+ var sparseHistogram = (histogram) => {
688
+ const cells = [];
689
+ for (let index = 0; index < histogram.length; index += 1) {
690
+ const count = histogram[index] ?? 0;
691
+ if (count > 0) cells.push([index, count]);
692
+ }
693
+ return cells;
694
+ };
695
+ var toMinute = (unit, executionTypeIndex) => ({
696
+ execution_type_index: executionTypeIndex,
697
+ bucket_start: bucketStart(unit.minute),
698
+ started_executions: unit.series.started,
699
+ completed_executions: unit.series.completed,
700
+ failed_executions: unit.series.failed,
701
+ duration_sample_count: unit.series.sampleCount,
702
+ duration_sample_sum_us: unit.series.sampleSumUs,
703
+ duration_sample_min_us: unit.series.sampleMinUs,
704
+ duration_sample_max_us: unit.series.sampleMaxUs,
705
+ duration_histogram: sparseHistogram(unit.series.histogram),
706
+ invalid_timing_count: unit.series.invalidTiming
707
+ });
708
+ var unitsFromQueue = (queued) => {
709
+ const units = [];
710
+ for (const queuedMinute of queued) {
711
+ for (const [executionHandle, series] of queuedMinute.series) {
712
+ units.push({ minute: queuedMinute.minute, executionHandle, series });
713
+ }
714
+ }
715
+ units.sort((left, right) => {
716
+ if (left.minute !== right.minute) return left.minute - right.minute;
717
+ return left.executionHandle - right.executionHandle;
718
+ });
719
+ return units;
720
+ };
721
+ var unitMarks = (series) => {
722
+ const next = series.started + series.completed;
723
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
724
+ };
725
+ var chunkUnits = (units, maxExecutionTypes, maxMinuteRows) => {
726
+ const chunks = [];
727
+ let current = [];
728
+ let executionTypes = /* @__PURE__ */ new Set();
729
+ let droppedUnexportable = 0;
730
+ const flush = () => {
731
+ if (current.length === 0) return;
732
+ chunks.push(current);
733
+ current = [];
734
+ executionTypes = /* @__PURE__ */ new Set();
735
+ };
736
+ for (const unit of units) {
737
+ if (maxMinuteRows < 1) {
738
+ droppedUnexportable += unitMarks(unit.series);
739
+ continue;
740
+ }
741
+ const nextTypes = executionTypes.has(unit.executionHandle) ? executionTypes.size : executionTypes.size + 1;
742
+ if (current.length >= maxMinuteRows || nextTypes > maxExecutionTypes) flush();
743
+ current.push(unit);
744
+ executionTypes.add(unit.executionHandle);
745
+ }
746
+ flush();
747
+ return { chunks, droppedUnexportable };
748
+ };
749
+ var batchForChunk = (draft, units, coverage) => {
750
+ const executionIndexes = /* @__PURE__ */ new Map();
751
+ const executionTypes = [];
752
+ const minutes = [];
753
+ for (const unit of units) {
754
+ let executionTypeIndex = executionIndexes.get(unit.executionHandle);
755
+ if (executionTypeIndex === void 0) {
756
+ const executionKey = draft.executionKeys[unit.executionHandle];
757
+ if (!executionKey) continue;
758
+ executionTypeIndex = executionTypes.length;
759
+ executionIndexes.set(unit.executionHandle, executionTypeIndex);
760
+ executionTypes.push({ execution_key: executionKey });
761
+ }
762
+ minutes.push(toMinute(unit, executionTypeIndex));
763
+ }
764
+ const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
765
+ return {
766
+ schema_version: EXECUTION_METRICS_SCHEMA_VERSION,
767
+ measurement_format: draft.measurementFormat,
768
+ producer_id: draft.producerId,
769
+ batch_id: draft.batchId(),
770
+ environment: draft.environment,
771
+ release: draft.release,
772
+ execution_types: executionTypes,
773
+ minutes,
774
+ coverage: { ...coverage, covered_bucket_starts: covered }
775
+ };
776
+ };
777
+ var lossOnlyBatch = (draft, coverage) => ({
778
+ schema_version: EXECUTION_METRICS_SCHEMA_VERSION,
779
+ measurement_format: draft.measurementFormat,
780
+ producer_id: draft.producerId,
781
+ batch_id: draft.batchId(),
782
+ environment: draft.environment,
783
+ release: draft.release,
784
+ execution_types: [],
785
+ minutes: [],
786
+ coverage
787
+ });
788
+ var executionMetricsBatchesFromQueue = (draft) => {
789
+ const units = unitsFromQueue(draft.queued);
790
+ const { chunks, droppedUnexportable } = chunkUnits(
791
+ units,
792
+ draft.maxExecutionTypes,
793
+ draft.maxMinuteRows
794
+ );
795
+ const coverage = {
796
+ ...draft.coverage,
797
+ dropped_unexportable: draft.coverage.dropped_unexportable + droppedUnexportable
798
+ };
799
+ if (chunks.length === 0) {
800
+ const hasLoss = Object.entries(coverage).some(([key, value]) => {
801
+ return key !== "covered_bucket_starts" && typeof value === "number" && value > 0;
802
+ });
803
+ return hasLoss ? [lossOnlyBatch(draft, coverage)] : [];
804
+ }
805
+ return chunks.map(
806
+ (chunk, index) => batchForChunk(draft, chunk, index === 0 ? coverage : emptyCoverage([]))
807
+ );
808
+ };
809
+ var newExecutionMetricsBatchId = () => randomUUID();
810
+
811
+ // src/execution-metrics/execution-metrics-collector.ts
812
+ var SERIES_BYTES = 256;
813
+ var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
814
+ var MAX_ELAPSED_NS = BigInt(Number.MAX_SAFE_INTEGER);
815
+ var defaultLimits = () => ({
816
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES,
817
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES,
818
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS / FUNCTION_METRICS_MINUTE_MS,
819
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
820
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
821
+ });
822
+ var defaultClock = () => ({
823
+ monotonicNs: () => process.hrtime.bigint(),
824
+ wallTimeMs: () => Date.now()
825
+ });
826
+ var emptyCoverage2 = () => ({
827
+ covered_bucket_starts: [],
828
+ skipped_unresolved_execution_type: 0,
829
+ dropped_active_series: 0,
830
+ dropped_byte_budget: 0,
831
+ dropped_queue_budget: 0,
832
+ dropped_late_completion: 0,
833
+ dropped_unexportable: 0
834
+ });
835
+ var note = (coverage, counter, amount = 1) => {
836
+ const next = coverage[counter] + amount;
837
+ coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
838
+ };
839
+ var countSeries = (table) => table.size;
840
+ var tableBytes = (table) => {
841
+ let bytes = 0;
842
+ for (const series of table.values()) bytes += series.bytes;
843
+ return bytes;
844
+ };
845
+ var discardedMarks = (table) => {
846
+ let marks = 0;
847
+ for (const series of table.values()) {
848
+ const next = marks + series.started + series.completed;
849
+ marks = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
850
+ }
851
+ return marks;
852
+ };
853
+ var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
854
+ var copySeries = (series) => ({
855
+ ...series,
856
+ histogram: series.histogram.slice()
857
+ });
858
+ var resetSeries = (series) => {
859
+ series.started = 0;
860
+ series.completed = 0;
861
+ series.failed = 0;
862
+ series.sampleCount = 0;
863
+ series.sampleSumUs = 0;
864
+ series.sampleMinUs = null;
865
+ series.sampleMaxUs = null;
866
+ series.invalidTiming = 0;
867
+ series.histogram.fill(0);
868
+ };
869
+ var snapshotAndReset = (table) => {
870
+ const snapshot = /* @__PURE__ */ new Map();
871
+ for (const [executionHandle, series] of table) {
872
+ if (seriesHasMarks(series)) snapshot.set(executionHandle, copySeries(series));
873
+ resetSeries(series);
874
+ }
875
+ return snapshot;
876
+ };
877
+ var createExecutionMetricsCollector = (options) => {
878
+ const limits = { ...defaultLimits(), ...options.limits };
879
+ const clock = options.clock ?? defaultClock();
880
+ const batchId = options.batchId ?? newExecutionMetricsBatchId;
881
+ const measurementFormat = options.sampledMeasurementFormat ? FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT : FUNCTION_METRICS_MEASUREMENT_FORMAT;
882
+ const coverage = emptyCoverage2();
883
+ const executionKeys = [];
884
+ const executionHandleByKey = /* @__PURE__ */ new Map();
885
+ const active = /* @__PURE__ */ new Map();
886
+ const queue = [];
887
+ let lastClosedMinute = Number.NEGATIVE_INFINITY;
888
+ let lastSeenMinute = Number.NEGATIVE_INFINITY;
889
+ let stateBytes = 0;
890
+ let activeSeries = 0;
891
+ let sealed = false;
892
+ const reserve = (bytes) => {
893
+ if (stateBytes > limits.maxStateBytes - bytes) {
894
+ note(coverage, "dropped_byte_budget");
895
+ return false;
896
+ }
897
+ stateBytes += bytes;
898
+ return true;
899
+ };
900
+ const internExecutionKey = (key) => {
901
+ if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
902
+ const existing = executionHandleByKey.get(key);
903
+ if (existing !== void 0) return existing;
904
+ if (executionKeys.length >= limits.maxExecutionTypes) {
905
+ note(coverage, "dropped_unexportable");
906
+ return void 0;
907
+ }
908
+ if (!reserve(key.length)) return void 0;
909
+ const handle = executionKeys.length;
910
+ executionKeys.push(key);
911
+ executionHandleByKey.set(key, handle);
912
+ return handle;
913
+ };
914
+ const ensureSeries = (minute, executionHandle) => {
915
+ let byExecution = active.get(minute);
916
+ if (!byExecution) {
917
+ byExecution = /* @__PURE__ */ new Map();
918
+ active.set(minute, byExecution);
919
+ }
920
+ const existing = byExecution.get(executionHandle);
921
+ if (existing) return existing;
922
+ if (activeSeries >= limits.maxActiveSeries) {
923
+ note(coverage, "dropped_active_series");
924
+ return void 0;
925
+ }
926
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
927
+ const series = {
928
+ started: 0,
929
+ completed: 0,
930
+ failed: 0,
931
+ sampleCount: 0,
932
+ sampleSumUs: 0,
933
+ sampleMinUs: null,
934
+ sampleMaxUs: null,
935
+ invalidTiming: 0,
936
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
937
+ bytes: SERIES_BYTES + HISTOGRAM_BYTES
938
+ };
939
+ byExecution.set(executionHandle, series);
940
+ activeSeries += 1;
941
+ return series;
942
+ };
943
+ const appendQueue = (entry) => {
944
+ if (discardedMarks(entry.series) === 0) {
945
+ stateBytes -= entry.bytes;
946
+ if (stateBytes < 0) stateBytes = 0;
947
+ return;
948
+ }
949
+ queue.push(entry);
950
+ queue.sort((left, right) => left.minute - right.minute);
951
+ while (queue.length > limits.maxQueuedMinutes) {
952
+ const dropped = queue.shift();
953
+ if (!dropped) break;
954
+ stateBytes -= dropped.bytes;
955
+ if (stateBytes < 0) stateBytes = 0;
956
+ note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
957
+ }
958
+ };
959
+ const closeMinute = (minute, table) => {
960
+ active.delete(minute);
961
+ activeSeries -= countSeries(table);
962
+ if (minute > lastClosedMinute) lastClosedMinute = minute;
963
+ appendQueue({ minute, series: table, bytes: tableBytes(table) });
964
+ };
965
+ const rotate = (currentMinute2) => {
966
+ for (const minute of [...active.keys()]) {
967
+ if (minute >= currentMinute2) continue;
968
+ const table = active.get(minute);
969
+ if (table) closeMinute(minute, table);
970
+ }
971
+ const closedThrough = currentMinute2 - 1;
972
+ if (closedThrough > lastClosedMinute) lastClosedMinute = closedThrough;
973
+ };
974
+ const rotateIfNeeded = (minute) => {
975
+ if (minute === lastSeenMinute) return;
976
+ lastSeenMinute = minute;
977
+ rotate(minute);
978
+ };
979
+ const snapshotActive = () => {
980
+ for (const [minute, table] of active) {
981
+ appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
982
+ }
983
+ };
984
+ const moveAllActive = () => {
985
+ for (const minute of [...active.keys()]) {
986
+ const table = active.get(minute);
987
+ if (table) closeMinute(minute, table);
988
+ }
989
+ };
990
+ const currentMinute = (allowClosed) => {
991
+ if (sealed) {
992
+ note(coverage, "dropped_unexportable");
993
+ return void 0;
994
+ }
995
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
996
+ rotateIfNeeded(minute);
997
+ if (minute <= lastClosedMinute && (!allowClosed || !active.has(minute))) {
998
+ note(coverage, "dropped_late_completion");
999
+ return void 0;
1000
+ }
1001
+ return minute;
1002
+ };
1003
+ const rememberSample = (series, durationUs, bucket) => {
1004
+ const sampleCount = series.sampleCount + 1;
1005
+ const sampleSumUs = series.sampleSumUs + durationUs;
1006
+ const previous = series.histogram[bucket];
1007
+ if (previous === void 0) return false;
1008
+ const cell = previous + 1;
1009
+ const sumFits = Number.isFinite(sampleSumUs) && sampleSumUs >= 0 && sampleSumUs <= Number.MAX_SAFE_INTEGER;
1010
+ if (!Number.isSafeInteger(sampleCount) || !Number.isSafeInteger(cell) || !sumFits) return false;
1011
+ series.histogram[bucket] = cell;
1012
+ series.sampleCount = sampleCount;
1013
+ series.sampleSumUs = sampleSumUs;
1014
+ series.sampleMinUs = series.sampleMinUs === null ? durationUs : Math.min(series.sampleMinUs, durationUs);
1015
+ series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
1016
+ return true;
1017
+ };
1018
+ const rememberStart = (handle) => {
1019
+ const minute = currentMinute(false);
1020
+ if (minute === void 0) return false;
1021
+ const series = ensureSeries(minute, handle);
1022
+ if (!series) return false;
1023
+ const started = series.started + 1;
1024
+ if (!Number.isSafeInteger(started)) {
1025
+ note(coverage, "dropped_unexportable");
1026
+ return false;
1027
+ }
1028
+ series.started = started;
1029
+ return true;
1030
+ };
1031
+ const bindIdentity = (state, key) => {
1032
+ if (state.finished || state.dropped || state.handle !== void 0) return;
1033
+ if (!key) return;
1034
+ const handle = internExecutionKey(key);
1035
+ if (handle === void 0) {
1036
+ state.dropped = true;
1037
+ return;
1038
+ }
1039
+ state.handle = handle;
1040
+ if (state.started) return;
1041
+ if (rememberStart(handle)) state.started = true;
1042
+ };
1043
+ const finishExecution = (state, input) => {
1044
+ if (state.finished) return;
1045
+ state.finished = true;
1046
+ if (state.dropped) return;
1047
+ if (state.handle === void 0) {
1048
+ note(coverage, "skipped_unresolved_execution_type");
1049
+ return;
1050
+ }
1051
+ if (!state.started) {
1052
+ if (!rememberStart(state.handle)) return;
1053
+ state.started = true;
1054
+ }
1055
+ const minute = currentMinute(true);
1056
+ if (minute === void 0) return;
1057
+ const series = ensureSeries(minute, state.handle);
1058
+ if (!series) return;
1059
+ const completed = series.completed + 1;
1060
+ const failed = series.failed + (input.failed ? 1 : 0);
1061
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failed)) {
1062
+ note(coverage, "dropped_unexportable");
1063
+ return;
1064
+ }
1065
+ if (input.measure) {
1066
+ if (input.startedNs === void 0 || input.endedNs === void 0) {
1067
+ const invalidTiming = series.invalidTiming + 1;
1068
+ if (!Number.isSafeInteger(invalidTiming)) {
1069
+ note(coverage, "dropped_unexportable");
1070
+ return;
1071
+ }
1072
+ series.invalidTiming = invalidTiming;
1073
+ } else {
1074
+ const elapsed = input.endedNs - input.startedNs;
1075
+ const durationUs = Number(elapsed) / 1e3;
1076
+ const placed = durationHistogramBucket(durationUs);
1077
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
1078
+ const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
1079
+ if (!sampled) {
1080
+ const invalidTiming = series.invalidTiming + 1;
1081
+ if (!Number.isSafeInteger(invalidTiming)) {
1082
+ note(coverage, "dropped_unexportable");
1083
+ return;
1084
+ }
1085
+ series.invalidTiming = invalidTiming;
1086
+ }
1087
+ }
1088
+ }
1089
+ series.completed = completed;
1090
+ series.failed = failed;
1091
+ };
1092
+ const drain = (drainOptions) => {
1093
+ if (!sealed) {
1094
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
1095
+ if (drainOptions?.flushAll) snapshotActive();
1096
+ }
1097
+ const batches = executionMetricsBatchesFromQueue({
1098
+ environment: options.environment,
1099
+ release: options.release,
1100
+ producerId: options.producerId,
1101
+ batchId,
1102
+ maxExecutionTypes: limits.maxExecutionTypes,
1103
+ maxMinuteRows: limits.maxMinuteRows,
1104
+ executionKeys,
1105
+ queued: queue,
1106
+ coverage: { ...coverage, covered_bucket_starts: [] },
1107
+ measurementFormat
1108
+ });
1109
+ if (batches.length === 0) return [];
1110
+ for (const queued of queue) stateBytes -= queued.bytes;
1111
+ if (stateBytes < 0) stateBytes = 0;
1112
+ queue.length = 0;
1113
+ coverage.skipped_unresolved_execution_type = 0;
1114
+ coverage.dropped_active_series = 0;
1115
+ coverage.dropped_byte_budget = 0;
1116
+ coverage.dropped_queue_budget = 0;
1117
+ coverage.dropped_late_completion = 0;
1118
+ coverage.dropped_unexportable = 0;
1119
+ return batches;
1120
+ };
1121
+ return {
1122
+ createState: () => ({
1123
+ handle: void 0,
1124
+ started: false,
1125
+ finished: false,
1126
+ dropped: false
1127
+ }),
1128
+ bindIdentity,
1129
+ finishExecution,
1130
+ drain,
1131
+ seal: () => {
1132
+ if (sealed) return;
1133
+ sealed = true;
1134
+ moveAllActive();
1135
+ }
1136
+ };
1137
+ };
1138
+
1139
+ // src/function-metrics/send-function-metrics-batch.ts
1140
+ var REQUEST_TIMEOUT_MS = 2e4;
1141
+ var abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
1142
+ var retryAfterMs = (response) => {
1143
+ const header = response.headers.get("retry-after");
1144
+ if (!header) return null;
1145
+ const seconds = Number(header);
1146
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
1147
+ const date = Date.parse(header);
1148
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
1149
+ };
1150
+ var backoffMs = (attempt, random) => {
1151
+ const base = Math.min(3e4, 500 * 2 ** attempt);
1152
+ return Math.floor(base * (0.5 + random()));
1153
+ };
1154
+ var fetchUntilAborted = (fetchFn, url, init) => new Promise((resolve, reject) => {
1155
+ const onAbort = () => reject(abortError());
1156
+ init.signal.addEventListener("abort", onAbort, { once: true });
1157
+ if (init.signal.aborted) {
1158
+ init.signal.removeEventListener("abort", onAbort);
1159
+ reject(abortError());
1160
+ return;
1161
+ }
1162
+ void fetchFn(url, init).then(
1163
+ (value) => {
1164
+ init.signal.removeEventListener("abort", onAbort);
1165
+ resolve(value);
1166
+ },
1167
+ (error) => {
1168
+ init.signal.removeEventListener("abort", onAbort);
1169
+ reject(error);
1170
+ }
1171
+ );
1172
+ });
1173
+ var sendFunctionMetricsBatch = async (input) => {
1174
+ if (input.signal.aborted) return { outcome: "aborted" };
1175
+ const nowMs = input.nowMs ?? Date.now;
1176
+ if (input.upload.expiresAtMs <= nowMs())
1177
+ return { outcome: "terminal", status: null, halt: false };
1178
+ const request = new AbortController();
1179
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS);
1180
+ timer.unref?.();
1181
+ const onParentAbort = () => request.abort();
1182
+ input.signal.addEventListener("abort", onParentAbort, { once: true });
1183
+ if (input.signal.aborted) request.abort();
1184
+ const headers = {
1185
+ Authorization: `Bearer ${input.ingestToken}`,
1186
+ "Content-Type": "application/json",
1187
+ Accept: "application/json"
1188
+ };
1189
+ if (input.upload.gzip) headers["Content-Encoding"] = "gzip";
1190
+ try {
1191
+ const response = await fetchUntilAborted(input.fetch, input.url, {
1192
+ method: "POST",
1193
+ headers,
1194
+ body: input.upload.body,
1195
+ signal: request.signal
1196
+ });
1197
+ if (response.ok) return { outcome: "ok" };
1198
+ if (response.status === 429) {
1199
+ return {
1200
+ outcome: "retry",
1201
+ waitMs: retryAfterMs(response) ?? backoffMs(input.attempt, input.random ?? Math.random)
1202
+ };
1203
+ }
1204
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
1205
+ return { outcome: "terminal", status: response.status, halt: true };
1206
+ }
1207
+ if (response.status >= 400 && response.status < 500) {
1208
+ return { outcome: "terminal", status: response.status, halt: false };
1209
+ }
1210
+ return {
1211
+ outcome: "retry",
1212
+ waitMs: backoffMs(input.attempt, input.random ?? Math.random)
1213
+ };
1214
+ } catch {
1215
+ if (input.signal.aborted) return { outcome: "aborted" };
1216
+ return { outcome: "retry", waitMs: backoffMs(input.attempt, input.random ?? Math.random) };
1217
+ } finally {
1218
+ clearTimeout(timer);
1219
+ input.signal.removeEventListener("abort", onParentAbort);
1220
+ }
1221
+ };
1222
+
1223
+ // src/execution-metrics/encode-execution-metrics-upload.ts
1224
+ import {
1225
+ encodeJsonRequestBodyAsync,
1226
+ FUNCTION_METRICS_BUCKET_LATENESS_MS,
1227
+ FUNCTION_METRICS_MAX_DECODED_BYTES,
1228
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS2,
1229
+ parseFunctionMetricsBucketStart
1230
+ } from "@rasputin-ai/core";
1231
+ var minuteMarks = (minute) => {
1232
+ const next = minute.started_executions + minute.completed_executions;
1233
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
1234
+ };
1235
+ var expiresAtMsFor = (batch, nowMs) => {
1236
+ let oldest;
1237
+ for (const start of batch.coverage.covered_bucket_starts) {
1238
+ const bucket = parseFunctionMetricsBucketStart(start);
1239
+ if (bucket === void 0) continue;
1240
+ if (oldest === void 0 || bucket < oldest) oldest = bucket;
1241
+ }
1242
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1243
+ return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1244
+ };
1245
+ var zeroLossCoverage = (coverage) => ({
1246
+ ...coverage,
1247
+ skipped_unresolved_execution_type: 0,
1248
+ dropped_active_series: 0,
1249
+ dropped_byte_budget: 0,
1250
+ dropped_queue_budget: 0,
1251
+ dropped_late_completion: 0,
1252
+ dropped_unexportable: 0
1253
+ });
1254
+ var projectMinutes = (source, minutes, coverage, batchId) => {
1255
+ const typeIndexes = /* @__PURE__ */ new Map();
1256
+ const executionTypes = [];
1257
+ const remappedMinutes = [];
1258
+ for (const minute of minutes) {
1259
+ let executionTypeIndex = typeIndexes.get(minute.execution_type_index);
1260
+ if (executionTypeIndex === void 0) {
1261
+ const entry = source.execution_types[minute.execution_type_index];
1262
+ if (!entry) continue;
1263
+ executionTypeIndex = executionTypes.length;
1264
+ typeIndexes.set(minute.execution_type_index, executionTypeIndex);
1265
+ executionTypes.push(entry);
1266
+ }
1267
+ remappedMinutes.push({ ...minute, execution_type_index: executionTypeIndex });
1268
+ }
1269
+ const covered = [...new Set(remappedMinutes.map((minute) => minute.bucket_start))].sort();
1270
+ return {
1271
+ ...source,
1272
+ batch_id: batchId,
1273
+ execution_types: executionTypes,
1274
+ minutes: remappedMinutes,
1275
+ coverage: { ...coverage, covered_bucket_starts: covered }
1276
+ };
1277
+ };
1278
+ var withLoss = (batch, loss) => ({
1279
+ ...batch,
1280
+ coverage: {
1281
+ ...batch.coverage,
1282
+ dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
1283
+ dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
1284
+ }
1285
+ });
1286
+ var encodeOne = async (batch, nowMs, signal) => {
1287
+ const decodedBytes = new TextEncoder().encode(JSON.stringify(batch));
1288
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES) return void 0;
1289
+ const encoded = await encodeJsonRequestBodyAsync(decodedBytes, void 0, signal);
1290
+ return {
1291
+ decodedBytes,
1292
+ body: encoded.body,
1293
+ gzip: encoded.gzip,
1294
+ batchId: batch.batch_id,
1295
+ expiresAtMs: expiresAtMsFor(batch, nowMs)
1296
+ };
1297
+ };
1298
+ var encodeFitting = async (batch, nowMs, signal) => {
1299
+ const encoded = await encodeOne(batch, nowMs, signal);
1300
+ if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
1301
+ if (batch.minutes.length <= 1) {
1302
+ return {
1303
+ uploads: [],
1304
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
1305
+ };
1306
+ }
1307
+ const mid = Math.ceil(batch.minutes.length / 2);
1308
+ const first = projectMinutes(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
1309
+ const rest = projectMinutes(
1310
+ batch,
1311
+ batch.minutes.slice(mid),
1312
+ zeroLossCoverage(batch.coverage),
1313
+ newExecutionMetricsBatchId()
1314
+ );
1315
+ const left = await encodeFitting(first, nowMs, signal);
1316
+ const right = await encodeFitting(rest, nowMs, signal);
1317
+ return {
1318
+ uploads: [...left.uploads, ...right.uploads],
1319
+ droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
1320
+ };
1321
+ };
1322
+ var encodeExecutionMetricsUploads = async (batches, input) => {
1323
+ const uploads = [];
1324
+ let extra = {
1325
+ dropped_unexportable: 0,
1326
+ dropped_queue_budget: input.queueDrops ?? 0
1327
+ };
1328
+ for (const batch of batches) {
1329
+ const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
1330
+ extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
1331
+ uploads.push(...fitted.uploads);
1332
+ }
1333
+ return uploads;
1334
+ };
1335
+
1336
+ // src/execution-metrics/execution-metrics-exporter.ts
1337
+ var MAX_QUEUE_ITEMS = 32;
1338
+ var MAX_QUEUE_BYTES = 4 * 1024 * 1024;
1339
+ var DEFAULT_SCHEDULE_MS = 6e4;
1340
+ var FLUSH_MS = 1e4;
1341
+ var SHUTDOWN_FLUSH_MS = 2e3;
1342
+ var MAX_ATTEMPTS = 8;
1343
+ var sleep = (ms, signal) => new Promise((resolve) => {
1344
+ if (ms <= 0 || signal.aborted) {
1345
+ resolve();
1346
+ return;
1347
+ }
1348
+ const timer = setTimeout(finish, ms);
1349
+ timer.unref?.();
1350
+ const onAbort = () => {
1351
+ clearTimeout(timer);
1352
+ finish();
1353
+ };
1354
+ function finish() {
1355
+ signal.removeEventListener("abort", onAbort);
1356
+ resolve();
1357
+ }
1358
+ signal.addEventListener("abort", onAbort);
1359
+ if (signal.aborted) onAbort();
1360
+ });
1361
+ var createExecutionMetricsExporter = (input) => {
1362
+ const nowMs = input.nowMs ?? Date.now;
1363
+ const random = input.random ?? Math.random;
1364
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
1365
+ const queue = [];
1366
+ let queueBytes = 0;
1367
+ let queueDrops = 0;
1368
+ let timer;
1369
+ let closed = false;
1370
+ let halted = false;
1371
+ let stopped = false;
1372
+ let workAbort;
1373
+ let work;
1374
+ let sent = 0;
1375
+ let dropped = 0;
1376
+ let warnedHalt = null;
1377
+ const dropOldest = () => {
1378
+ const oldest = queue.shift();
1379
+ if (!oldest) return;
1380
+ queueBytes -= oldest.upload.decodedBytes.byteLength;
1381
+ if (queueBytes < 0) queueBytes = 0;
1382
+ queueDrops += 1;
1383
+ dropped += 1;
1384
+ };
1385
+ const enqueue = (upload) => {
1386
+ queue.push({ upload, attempt: 0 });
1387
+ queueBytes += upload.decodedBytes.byteLength;
1388
+ while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
1389
+ };
1390
+ const drainAndEnqueue = async (flushAll2) => {
1391
+ if (halted || stopped) return;
1392
+ const batches = input.collector.drain({ flushAll: flushAll2 });
1393
+ if (batches.length === 0) return;
1394
+ const encoded = await encodeExecutionMetricsUploads(batches, {
1395
+ nowMs: nowMs(),
1396
+ queueDrops
1397
+ });
1398
+ if (encoded.length === 0 || halted || stopped) return;
1399
+ queueDrops = 0;
1400
+ for (const upload of encoded) enqueue(upload);
1401
+ };
1402
+ const warnHalt = (status) => {
1403
+ if (warnedHalt === status) return;
1404
+ warnedHalt = status;
1405
+ if (status === 401 || status === 403) {
1406
+ console.warn("[rasputin] execution metrics export stopped: authentication failed");
1407
+ return;
1408
+ }
1409
+ if (status === 404) {
1410
+ console.warn("[rasputin] execution metrics export stopped: ingest route is unavailable");
1411
+ }
1412
+ };
1413
+ const pump = async (signal) => {
1414
+ while (queue.length > 0 && !halted && !stopped && !signal.aborted) {
1415
+ const item = queue[0];
1416
+ if (!item) return;
1417
+ if (item.upload.expiresAtMs <= nowMs()) {
1418
+ queue.shift();
1419
+ queueBytes -= item.upload.decodedBytes.byteLength;
1420
+ dropped += 1;
1421
+ continue;
1422
+ }
1423
+ if (item.attempt >= MAX_ATTEMPTS) {
1424
+ queue.shift();
1425
+ queueBytes -= item.upload.decodedBytes.byteLength;
1426
+ dropped += 1;
1427
+ continue;
1428
+ }
1429
+ const result = await sendFunctionMetricsBatch({
1430
+ url: input.url,
1431
+ ingestToken: input.ingestToken,
1432
+ upload: item.upload,
1433
+ fetch: input.fetch,
1434
+ signal,
1435
+ attempt: item.attempt,
1436
+ random,
1437
+ nowMs
1438
+ });
1439
+ if (result.outcome === "aborted") return;
1440
+ if (result.outcome === "ok") {
1441
+ queue.shift();
1442
+ queueBytes -= item.upload.decodedBytes.byteLength;
1443
+ sent += 1;
1444
+ continue;
1445
+ }
1446
+ if (result.outcome === "terminal") {
1447
+ queue.shift();
1448
+ queueBytes -= item.upload.decodedBytes.byteLength;
1449
+ dropped += 1;
1450
+ if (result.halt) {
1451
+ halted = true;
1452
+ warnHalt(result.status);
1453
+ }
1454
+ continue;
1455
+ }
1456
+ item.attempt += 1;
1457
+ await sleep(result.waitMs, signal);
1458
+ }
1459
+ };
1460
+ const abortCurrent = () => {
1461
+ workAbort?.abort();
1462
+ };
1463
+ const raceUntilAborted = async (running, signal) => {
1464
+ if (signal.aborted) return;
1465
+ await new Promise((resolve) => {
1466
+ let settled = false;
1467
+ const finish = () => {
1468
+ if (settled) return;
1469
+ settled = true;
1470
+ signal.removeEventListener("abort", finish);
1471
+ resolve();
1472
+ };
1473
+ signal.addEventListener("abort", finish);
1474
+ if (signal.aborted) {
1475
+ finish();
1476
+ return;
1477
+ }
1478
+ void running.then(finish, finish);
1479
+ });
1480
+ };
1481
+ const runWork = async (signal, task) => {
1482
+ const onAbort = () => abortCurrent();
1483
+ signal.addEventListener("abort", onAbort);
1484
+ if (signal.aborted) abortCurrent();
1485
+ try {
1486
+ while (work) {
1487
+ const previous = work;
1488
+ await raceUntilAborted(previous, signal);
1489
+ if (signal.aborted || halted) return;
1490
+ if (work === previous) return;
1491
+ }
1492
+ if (halted) return;
1493
+ const inner = new AbortController();
1494
+ workAbort = inner;
1495
+ if (signal.aborted) {
1496
+ workAbort = void 0;
1497
+ return;
1498
+ }
1499
+ const running = task(inner.signal).finally(() => {
1500
+ if (workAbort === inner) workAbort = void 0;
1501
+ if (work === running) work = void 0;
1502
+ });
1503
+ work = running;
1504
+ await raceUntilAborted(running, signal);
1505
+ } finally {
1506
+ signal.removeEventListener("abort", onAbort);
1507
+ }
1508
+ };
1509
+ const tick = async () => {
1510
+ if (closed || halted) return;
1511
+ try {
1512
+ await runWork(new AbortController().signal, async (signal) => {
1513
+ if (closed || halted) return;
1514
+ await drainAndEnqueue(false);
1515
+ await pump(signal);
1516
+ });
1517
+ } catch {
1518
+ }
1519
+ if (!closed && !halted) arm();
1520
+ };
1521
+ const arm = () => {
1522
+ if (closed || halted) return;
1523
+ const delay = Math.max(1e3, Math.floor(scheduleMs * (0.85 + random() * 0.3)));
1524
+ timer = setTimeout(() => {
1525
+ void tick();
1526
+ }, delay);
1527
+ timer.unref?.();
1528
+ };
1529
+ arm();
1530
+ const flush = async (timeoutMs) => {
1531
+ if (closed || halted) return;
1532
+ const abort = new AbortController();
1533
+ const budget = timeoutMs ?? FLUSH_MS;
1534
+ const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
1535
+ try {
1536
+ await runWork(abort.signal, async (signal) => {
1537
+ if (closed || halted) return;
1538
+ await drainAndEnqueue(true);
1539
+ await pump(signal);
1540
+ });
1541
+ } catch {
1542
+ } finally {
1543
+ clearTimeout(timeout);
1544
+ }
1545
+ };
1546
+ return {
1547
+ flush,
1548
+ close: async () => {
1549
+ if (closed) return;
1550
+ closed = true;
1551
+ if (timer) clearTimeout(timer);
1552
+ timer = void 0;
1553
+ const abort = new AbortController();
1554
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
1555
+ abortCurrent();
1556
+ try {
1557
+ await runWork(abort.signal, async (signal) => {
1558
+ input.collector.seal();
1559
+ await drainAndEnqueue(false);
1560
+ await pump(signal);
1561
+ });
1562
+ } catch {
1563
+ } finally {
1564
+ clearTimeout(timeout);
1565
+ stopped = true;
1566
+ input.collector.seal();
1567
+ queue.length = 0;
1568
+ queueBytes = 0;
1569
+ }
1570
+ },
1571
+ getStats: () => ({ sent, dropped, halted })
1572
+ };
1573
+ };
1574
+
1575
+ // src/execution-metrics/bind-execution-metrics.ts
1576
+ var SLOT = Symbol.for("rasputin.executionMetrics.runtime.v1");
1577
+ var releasedHandles = /* @__PURE__ */ new WeakSet();
1578
+ var isRuntime = (value) => {
1579
+ if (typeof value !== "object" || value === null) return false;
1580
+ return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
1581
+ };
1582
+ var bindingIdentity = (input) => `${input.ingestToken}
1583
+ ${input.url}
1584
+ ${input.environment}
1585
+ ${input.release}
1586
+ ${input.sampledMeasurementFormat ? "1" : "0"}`;
1587
+ var warnIncompatible = (runtime) => {
1588
+ if (runtime.warnedMismatch) return;
1589
+ runtime.warnedMismatch = true;
1590
+ console.warn(
1591
+ "[rasputin] execution metrics already running with a different configuration; this client will not collect execution metrics"
1592
+ );
1593
+ };
1594
+ var createBindings = (input) => {
1595
+ const collector = createExecutionMetricsCollector({
1596
+ environment: input.environment,
1597
+ producerId: randomUUID2(),
1598
+ release: input.release,
1599
+ sampledMeasurementFormat: input.sampledMeasurementFormat
1600
+ });
1601
+ return {
1602
+ collector,
1603
+ exporter: createExecutionMetricsExporter({
1604
+ collector,
1605
+ url: input.url,
1606
+ ingestToken: input.ingestToken,
1607
+ fetch: input.fetch ?? defaultIngestFetch()
1608
+ })
1609
+ };
1610
+ };
1611
+ var bindExecutionMetrics = (input) => {
1612
+ if (!input.clientEnabled) return void 0;
1613
+ if (input.options?.enabled === false) return void 0;
1614
+ const release = input.release.trim().toLowerCase();
1615
+ if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
1616
+ const url = resolveEndpointUrls2(input.apiUrl).executionMetricsUrl;
1617
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
1618
+ const key = bindingIdentity({
1619
+ ingestToken: input.ingestToken,
1620
+ url,
1621
+ environment: input.environment,
1622
+ release,
1623
+ sampledMeasurementFormat
1624
+ });
1625
+ const existing = Reflect.get(globalThis, SLOT);
1626
+ if (isRuntime(existing)) {
1627
+ if (existing.identity !== key) {
1628
+ warnIncompatible(existing);
1629
+ return void 0;
1630
+ }
1631
+ existing.refs += 1;
1632
+ return { collector: existing.collector, exporter: existing.exporter };
1633
+ }
1634
+ const bindings2 = createBindings({
1635
+ release,
1636
+ ingestToken: input.ingestToken,
1637
+ url,
1638
+ environment: input.environment,
1639
+ fetch: input.fetch,
1640
+ sampledMeasurementFormat
1641
+ });
1642
+ Reflect.set(globalThis, SLOT, {
1643
+ ...bindings2,
1644
+ refs: 1,
1645
+ identity: key,
1646
+ warnedMismatch: false
1647
+ });
1648
+ return bindings2;
1649
+ };
1650
+ var releaseExecutionMetricsBindings = async (bindings2) => {
1651
+ if (!bindings2 || releasedHandles.has(bindings2)) return;
1652
+ releasedHandles.add(bindings2);
1653
+ const existing = Reflect.get(globalThis, SLOT);
1654
+ if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
1655
+ existing.refs -= 1;
1656
+ if (existing.refs > 0) return;
1657
+ Reflect.deleteProperty(globalThis, SLOT);
1658
+ }
1659
+ await bindings2.exporter.close();
1660
+ };
1661
+
650
1662
  // src/execution-recorder/execution-recorder.ts
651
1663
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
652
1664
  import {
@@ -701,11 +1713,30 @@ var executionTypeKey = (metadata) => {
701
1713
  var isHttpClientErrorStatus = (status) => {
702
1714
  return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
703
1715
  };
1716
+ var isHttpServerErrorStatus = (status) => {
1717
+ return typeof status === "number" && Number.isFinite(status) && status >= 500;
1718
+ };
1719
+ var executionOutcomeFailed = (input) => input.hasError || input.runFailed || isHttpServerErrorStatus(input.status);
704
1720
 
705
1721
  // src/execution-recorder/function-plan.ts
706
1722
  var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
707
1723
  var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
708
1724
 
1725
+ // src/runtime-timing/call-duration.ts
1726
+ var planCallDuration = (sampler, input) => {
1727
+ if (!sampler) return { selected: true, measure: true };
1728
+ if (!input.executionType) return { selected: false, measure: input.forceMeasure };
1729
+ const selected = sampler.take(input.executionType, input.callerFunctionId, input.functionId);
1730
+ return { selected, measure: selected || input.forceMeasure };
1731
+ };
1732
+
1733
+ // src/runtime-timing/execution-duration.ts
1734
+ var planExecutionDuration = (sampler, executionType) => {
1735
+ if (!sampler) return { selected: true };
1736
+ if (!executionType) return { selected: false };
1737
+ return { selected: sampler.takeExecution(executionType) };
1738
+ };
1739
+
709
1740
  // src/function-metrics/function-metric-declaration-registry.ts
710
1741
  var REGISTRY_SYMBOL = Symbol.for("rasputin.functionMetrics.declarations.v1");
711
1742
  var getRegistry2 = () => {
@@ -730,58 +1761,93 @@ var registerFunctionMetricDeclarations = (declarations) => {
730
1761
  var functionMetricDeclarationFor = (runtimeId) => getRegistry2().byRuntimeId.get(runtimeId);
731
1762
 
732
1763
  // src/function-metrics/intern-prepared-metrics.ts
733
- import { functionMetricsTraceDeclaration } from "@rasputin-ai/core";
734
- var internPreparedMetrics = (collector, plan) => {
1764
+ import {
1765
+ functionMetricsTraceDeclaration
1766
+ } from "@rasputin-ai/core";
1767
+ var declarationForPreparedPlan = (plan) => {
735
1768
  if (plan.excluded) return void 0;
736
- if (plan.metricsHandle !== void 0) return plan.metricsHandle;
737
1769
  const declaration = plan.metricsDeclaration ?? functionMetricDeclarationFor(plan.functionId) ?? functionMetricsTraceDeclaration({
738
1770
  runtimeId: plan.functionId
739
1771
  });
740
1772
  plan.metricsDeclaration = declaration;
1773
+ return declaration;
1774
+ };
1775
+ var internPreparedMetrics = (collector, plan) => {
1776
+ if (plan.excluded) return void 0;
1777
+ if (plan.metricsHandle !== void 0) return plan.metricsHandle;
1778
+ const declaration = declarationForPreparedPlan(plan);
741
1779
  const handle = collector.internDeclaration(declaration);
742
1780
  if (handle !== void 0) plan.metricsHandle = handle;
743
1781
  return handle;
744
1782
  };
745
1783
 
746
1784
  // src/function-metrics/settle-function-metrics.ts
747
- var finishMetricsCall = (collector, functionHandle, executionHandle, startedNs, failed, endedNs) => {
1785
+ var finishMetricsCall = (collector, functionHandle, executionHandle, failed, timing) => {
748
1786
  try {
749
- collector.finishCall(functionHandle, executionHandle, startedNs, failed, endedNs);
1787
+ collector.finishCall(functionHandle, executionHandle, failed, timing);
750
1788
  } catch {
751
1789
  }
752
1790
  };
753
1791
  var thenOf = (value) => {
754
- if (typeof value !== "object" && typeof value !== "function" || value === null) {
1792
+ try {
1793
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
1794
+ return void 0;
1795
+ }
1796
+ if (!("then" in value)) return void 0;
1797
+ const then = value.then;
1798
+ if (typeof then !== "function") return void 0;
1799
+ return (onFulfilled, onRejected) => {
1800
+ Reflect.apply(then, value, [onFulfilled, onRejected]);
1801
+ };
1802
+ } catch {
1803
+ return void 0;
1804
+ }
1805
+ };
1806
+ var tryCallClock = () => {
1807
+ try {
1808
+ return process.hrtime.bigint();
1809
+ } catch {
755
1810
  return void 0;
756
1811
  }
757
- if (!("then" in value)) return void 0;
758
- const then = value.then;
759
- if (typeof then !== "function") return void 0;
760
- return (onFulfilled, onRejected) => {
761
- Reflect.apply(then, value, [onFulfilled, onRejected]);
762
- };
763
1812
  };
764
- var startMetricsCall = (collector, functionHandle, executionHandle, startedNs) => {
1813
+ var startMetricsCall = (collector, functionHandle, executionHandle, options) => {
765
1814
  if (!collector || functionHandle === void 0) return void 0;
766
1815
  try {
767
- return collector.startCall(functionHandle, executionHandle, startedNs);
1816
+ return collector.startCall(functionHandle, executionHandle, options);
768
1817
  } catch {
769
1818
  return void 0;
770
1819
  }
771
1820
  };
772
- var completeMetricsResult = (collector, functionHandle, executionHandle, startedNs, value) => {
1821
+ var completeMetricsResult = (collector, functionHandle, executionHandle, value, timing, onSettled) => {
773
1822
  const then = thenOf(value);
774
1823
  if (!then) {
775
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false);
1824
+ finishMetricsCall(collector, functionHandle, executionHandle, false, timing);
776
1825
  return;
777
1826
  }
1827
+ let completed = false;
1828
+ const complete = (failed) => {
1829
+ if (completed) return;
1830
+ completed = true;
1831
+ const endedNs = timing !== void 0 ? tryCallClock() : void 0;
1832
+ finishMetricsCall(
1833
+ collector,
1834
+ functionHandle,
1835
+ executionHandle,
1836
+ failed,
1837
+ timing === void 0 ? void 0 : { startedNs: timing.startedNs, endedNs }
1838
+ );
1839
+ try {
1840
+ onSettled?.(endedNs);
1841
+ } catch {
1842
+ }
1843
+ };
778
1844
  try {
779
1845
  then(
780
- () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false),
781
- () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true)
1846
+ () => complete(false),
1847
+ () => complete(true)
782
1848
  );
783
1849
  } catch {
784
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
1850
+ complete(true);
785
1851
  }
786
1852
  };
787
1853
 
@@ -821,6 +1887,14 @@ var emptyStats = () => ({
821
1887
  adaptiveRefreshFailures: 0,
822
1888
  lastAdaptiveFailureKind: null
823
1889
  });
1890
+ var metricsStorage = new AsyncLocalStorage();
1891
+ var tryCallClock2 = () => {
1892
+ try {
1893
+ return process.hrtime.bigint();
1894
+ } catch {
1895
+ return void 0;
1896
+ }
1897
+ };
824
1898
  var mergeMetadata = (store, metadata) => {
825
1899
  if (metadata.kind) store.execution.kind = metadata.kind;
826
1900
  if (metadata.name !== void 0) store.execution.name = metadata.name;
@@ -834,32 +1908,100 @@ var definitionOf = (input) => {
834
1908
  return input;
835
1909
  };
836
1910
  var bindExecutionHandle = (collector, store) => {
1911
+ if (!collector) return;
837
1912
  store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
838
1913
  };
839
- var runWithMetrics = (collector, plan, executionHandle, callback) => {
1914
+ var bindExecutionMetricsIdentity = (collector, store) => {
1915
+ if (!collector || !store.executionMetrics) return;
1916
+ collector.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
1917
+ };
1918
+ var settleStarted = (collector, functionHandle, executionHandle, started, value, failed, endedNs) => {
1919
+ if (!started || functionHandle === void 0 || executionHandle === void 0) return;
1920
+ const timing = started.measure ? { startedNs: started.startedNs, endedNs } : void 0;
1921
+ if (failed) {
1922
+ finishMetricsCall(collector, functionHandle, executionHandle, true, timing);
1923
+ return;
1924
+ }
1925
+ completeMetricsResult(collector, functionHandle, executionHandle, value, timing);
1926
+ };
1927
+ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1928
+ if (!collector) return callback();
1929
+ const duration = planCallDuration(durationSampler, {
1930
+ forceMeasure: false,
1931
+ executionType: store ? executionTypeKey(store.execution) : void 0,
1932
+ callerFunctionId: store?.currentFunctionId ?? "",
1933
+ functionId: plan.functionId
1934
+ });
1935
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
840
1936
  const functionHandle = internPreparedMetrics(collector, plan);
841
- const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
842
- try {
843
- const result = callback();
844
- if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
845
- completeMetricsResult(collector, functionHandle, executionHandle, startedNs, result);
846
- }
847
- return result;
848
- } catch (error) {
849
- if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
850
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
1937
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
1938
+ measure: duration.selected,
1939
+ ...duration.selected ? { startedNs } : {}
1940
+ });
1941
+ const invoke = () => {
1942
+ try {
1943
+ const result = callback();
1944
+ settleStarted(
1945
+ collector,
1946
+ functionHandle,
1947
+ store?.executionHandle,
1948
+ started,
1949
+ result,
1950
+ false,
1951
+ started?.measure && !(result instanceof Promise) ? tryCallClock2() : void 0
1952
+ );
1953
+ return result;
1954
+ } catch (error) {
1955
+ settleStarted(
1956
+ collector,
1957
+ functionHandle,
1958
+ store?.executionHandle,
1959
+ started,
1960
+ error,
1961
+ true,
1962
+ started?.measure ? tryCallClock2() : void 0
1963
+ );
1964
+ throw error;
851
1965
  }
852
- throw error;
853
- }
1966
+ };
1967
+ if (!store || !durationSampler) return invoke();
1968
+ return metricsStorage.run({ ...store, currentFunctionId: plan.functionId }, invoke);
854
1969
  };
855
- var metricsHandle = (collector, plan, executionHandle) => {
1970
+ var metricsHandle = (collector, durationSampler, plan, store) => {
1971
+ if (!collector) return passthroughHandle();
1972
+ const duration = planCallDuration(durationSampler, {
1973
+ forceMeasure: false,
1974
+ executionType: store ? executionTypeKey(store.execution) : void 0,
1975
+ callerFunctionId: store?.currentFunctionId ?? "",
1976
+ functionId: plan.functionId
1977
+ });
1978
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
856
1979
  const functionHandle = internPreparedMetrics(collector, plan);
857
- const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
858
- if (startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
1980
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
1981
+ measure: duration.selected,
1982
+ ...duration.selected ? { startedNs } : {}
1983
+ });
1984
+ if (!started || functionHandle === void 0 || store?.executionHandle === void 0) {
859
1985
  return passthroughHandle();
860
1986
  }
1987
+ const executionHandle = store.executionHandle;
861
1988
  let failed = false;
862
1989
  let settled = false;
1990
+ let previousFunctionId = store.currentFunctionId;
1991
+ let callerClaimed = false;
1992
+ const claimCaller = () => {
1993
+ if (callerClaimed || !durationSampler) return;
1994
+ previousFunctionId = store.currentFunctionId;
1995
+ store.currentFunctionId = plan.functionId;
1996
+ callerClaimed = true;
1997
+ };
1998
+ const releaseCaller = () => {
1999
+ if (!callerClaimed) return;
2000
+ callerClaimed = false;
2001
+ if (previousFunctionId === void 0) delete store.currentFunctionId;
2002
+ else store.currentFunctionId = previousFunctionId;
2003
+ };
2004
+ claimCaller();
863
2005
  return {
864
2006
  leave: (value) => value,
865
2007
  fail: () => {
@@ -868,20 +2010,36 @@ var metricsHandle = (collector, plan, executionHandle) => {
868
2010
  end: () => {
869
2011
  if (settled) return;
870
2012
  settled = true;
871
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, failed);
2013
+ releaseCaller();
2014
+ const endedNs = started.measure ? tryCallClock2() : void 0;
2015
+ finishMetricsCall(
2016
+ collector,
2017
+ functionHandle,
2018
+ executionHandle,
2019
+ failed,
2020
+ started.measure ? { startedNs: started.startedNs, endedNs } : void 0
2021
+ );
872
2022
  },
873
2023
  run: function __rasputinHandleRun__4(callback) {
874
2024
  return runExactlyOnce((invoke) => invoke(), callback);
875
2025
  },
876
- suspend: (value) => value,
877
- resume: (value) => value
2026
+ suspend: (value) => {
2027
+ releaseCaller();
2028
+ return value;
2029
+ },
2030
+ resume: (value) => {
2031
+ claimCaller();
2032
+ return value;
2033
+ }
878
2034
  };
879
2035
  };
880
- var createMetricsOnlyRuntime = (collector) => {
881
- const storage = new AsyncLocalStorage();
2036
+ var createMetricsOnlyRuntime = (input) => {
2037
+ const collector = input.functionMetrics;
2038
+ const executionMetrics = input.executionMetrics;
2039
+ const durationSampler = input.durationSampler;
882
2040
  const preparedModules = /* @__PURE__ */ new WeakMap();
883
2041
  let nextRuntimePlanId = 1;
884
- const currentHandle = () => storage.getStore()?.executionHandle;
2042
+ const currentStore = () => metricsStorage.getStore();
885
2043
  const planFor = (definition) => ({
886
2044
  runtimePlanId: nextRuntimePlanId++,
887
2045
  definition,
@@ -907,9 +2065,9 @@ var createMetricsOnlyRuntime = (collector) => {
907
2065
  preparedModules.set(plans, prepared);
908
2066
  return prepared;
909
2067
  };
910
- const runPrepared = (plan, _args, callback) => runWithMetrics(collector, plan, currentHandle(), callback);
911
- function trace(input, fn) {
912
- const definition = typeof input === "string" ? definitionOf(input) : { ...input, functionId: runtimeFunctionId2(input) };
2068
+ const runPrepared = (plan, _args, callback) => runWithMetrics(collector, durationSampler, plan, currentStore(), callback);
2069
+ function trace(input2, fn) {
2070
+ const definition = typeof input2 === "string" ? definitionOf(input2) : { ...input2, functionId: runtimeFunctionId2(input2) };
913
2071
  const plan = planFor(definition);
914
2072
  return function __rasputinHandleRun__4(...args) {
915
2073
  if (new.target) {
@@ -918,6 +2076,28 @@ var createMetricsOnlyRuntime = (collector) => {
918
2076
  return runPrepared(plan, args, () => fn.apply(this, args));
919
2077
  };
920
2078
  }
2079
+ const finishScope = (store, next) => {
2080
+ if (next) {
2081
+ mergeMetadata(store, next);
2082
+ bindExecutionHandle(collector, store);
2083
+ bindExecutionMetricsIdentity(executionMetrics, store);
2084
+ }
2085
+ if (!executionMetrics || !store.executionMetrics) return;
2086
+ if (store.executionMetrics.finished) return;
2087
+ const endedNs = tryCallClock2();
2088
+ const executionKey = executionTypeKey(store.execution);
2089
+ bindExecutionMetricsIdentity(executionMetrics, store);
2090
+ executionMetrics.finishExecution(store.executionMetrics, {
2091
+ failed: executionOutcomeFailed({
2092
+ hasError: store.hasError,
2093
+ runFailed: store.runFailed,
2094
+ status: store.execution.request?.status
2095
+ }),
2096
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
2097
+ startedNs: store.startedAtNs,
2098
+ ...endedNs === void 0 ? {} : { endedNs }
2099
+ });
2100
+ };
921
2101
  return {
922
2102
  createScope: (metadata) => {
923
2103
  const store = {
@@ -925,22 +2105,35 @@ var createMetricsOnlyRuntime = (collector) => {
925
2105
  ...metadata,
926
2106
  ...metadata.request ? { request: { ...metadata.request } } : {}
927
2107
  },
928
- executionHandle: void 0
2108
+ executionHandle: void 0,
2109
+ startedAtNs: tryCallClock2() ?? 0n,
2110
+ hasError: false,
2111
+ runFailed: false
929
2112
  };
930
2113
  bindExecutionHandle(collector, store);
2114
+ if (executionMetrics) {
2115
+ store.executionMetrics = executionMetrics.createState();
2116
+ bindExecutionMetricsIdentity(executionMetrics, store);
2117
+ }
931
2118
  return {
932
- run: (callback) => storage.run(store, callback),
933
- getErrorState: () => void 0,
934
- observeError: () => inertErrorObservation(),
935
- finish: (next) => {
936
- if (next) {
937
- mergeMetadata(store, next);
938
- bindExecutionHandle(collector, store);
2119
+ run: (callback) => metricsStorage.run(store, () => {
2120
+ try {
2121
+ return callback();
2122
+ } catch (error) {
2123
+ store.runFailed = true;
2124
+ throw error;
939
2125
  }
2126
+ }),
2127
+ getErrorState: () => void 0,
2128
+ observeError: () => {
2129
+ store.hasError = true;
2130
+ return inertErrorObservation();
940
2131
  },
2132
+ finish: (next) => finishScope(store, next),
941
2133
  mergeMetadata: (next) => {
942
2134
  mergeMetadata(store, next);
943
2135
  bindExecutionHandle(collector, store);
2136
+ bindExecutionMetricsIdentity(executionMetrics, store);
944
2137
  }
945
2138
  };
946
2139
  },
@@ -952,10 +2145,11 @@ var createMetricsOnlyRuntime = (collector) => {
952
2145
  },
953
2146
  prepareFunctionPlans: (plans) => prepareEncoded(plans),
954
2147
  runPreparedFunction: runPrepared,
955
- enterPreparedFunction: (plan) => metricsHandle(collector, plan, currentHandle()),
2148
+ enterPreparedFunction: (plan) => metricsHandle(collector, durationSampler, plan, currentStore()),
956
2149
  trace,
957
2150
  getStats: () => emptyStats(),
958
2151
  close: () => {
2152
+ durationSampler?.stop();
959
2153
  }
960
2154
  };
961
2155
  };
@@ -973,68 +2167,6 @@ var sanitizeFullCaptureDurationMs = (value) => {
973
2167
  Math.max(MIN_FULL_CAPTURE_DURATION_MS, Math.floor(value))
974
2168
  );
975
2169
  };
976
- var sanitizeDynamicDurationSampling = (value) => value === true;
977
-
978
- // src/execution-recorder/dynamic-duration-sampling.ts
979
- var DYNAMIC_DURATION_SAMPLE_STAGES = [
980
- { below: 10, divisor: 1 },
981
- { below: 30, divisor: 2 },
982
- { below: 100, divisor: 3 },
983
- { below: 500, divisor: 11 },
984
- { below: 1e3, divisor: 23 },
985
- { below: 5e3, divisor: 53 }
986
- ];
987
- var DYNAMIC_DURATION_SAMPLE_TAIL_AFTER = 5e3;
988
- var DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR = 100;
989
- var DYNAMIC_DURATION_SAMPLE_RESET_MS = 60 * 60 * 1e3;
990
- var MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS = 4096;
991
- var dynamicDurationSampleDivisor = (index) => {
992
- for (const stage of DYNAMIC_DURATION_SAMPLE_STAGES) {
993
- if (index < stage.below) return stage.divisor;
994
- }
995
- return DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
996
- };
997
- var shouldSampleDynamicDuration = (index) => {
998
- return index % dynamicDurationSampleDivisor(index) === 0;
999
- };
1000
- var nextDurationSampleIndex = (index) => {
1001
- if (index < Number.MAX_SAFE_INTEGER) return index + 1;
1002
- return DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + (index - DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + 1) % DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
1003
- };
1004
- var createDynamicDurationSampleBuckets = (options) => {
1005
- const buckets = /* @__PURE__ */ new Map();
1006
- const maxBuckets = options.maxBuckets ?? MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS;
1007
- const resetMs = options.resetMs ?? DYNAMIC_DURATION_SAMPLE_RESET_MS;
1008
- let lastResetAtMs = options.nowMs();
1009
- const reset = () => {
1010
- buckets.clear();
1011
- lastResetAtMs = options.nowMs();
1012
- };
1013
- const resetTimer = setInterval(reset, resetMs);
1014
- resetTimer.unref?.();
1015
- return {
1016
- take: (executionType, callerFunctionId, functionId) => {
1017
- if (options.nowMs() - lastResetAtMs >= resetMs) reset();
1018
- const key = `${executionType}\0${callerFunctionId}\0${functionId}`;
1019
- const existing = buckets.get(key);
1020
- if (existing !== void 0) {
1021
- buckets.delete(key);
1022
- buckets.set(key, nextDurationSampleIndex(existing));
1023
- return shouldSampleDynamicDuration(existing);
1024
- }
1025
- while (buckets.size >= maxBuckets) {
1026
- const oldest = buckets.keys().next().value;
1027
- if (oldest === void 0) break;
1028
- buckets.delete(oldest);
1029
- }
1030
- buckets.set(key, nextDurationSampleIndex(0));
1031
- return shouldSampleDynamicDuration(0);
1032
- },
1033
- stop: () => {
1034
- clearInterval(resetTimer);
1035
- }
1036
- };
1037
- };
1038
2170
 
1039
2171
  // src/execution-recorder/execution-journal.ts
1040
2172
  var KIND_ENTER = 1;
@@ -1133,6 +2265,15 @@ var ExecutionJournal = class {
1133
2265
  }
1134
2266
  this.openCallIds.delete(callId);
1135
2267
  }
2268
+ setCallTiming(callId, timestampNs, durationNs) {
2269
+ for (let index = this.length - 1; index >= 0; index--) {
2270
+ if (this.callId[index] !== callId) continue;
2271
+ if (this.kind[index] !== KIND_EXIT && this.kind[index] !== KIND_THROW) continue;
2272
+ this.timestampNs[index] = timestampNs;
2273
+ this.durationNs[index] = durationNs;
2274
+ return;
2275
+ }
2276
+ }
1136
2277
  dropCall() {
1137
2278
  this.dropped += 2;
1138
2279
  }
@@ -3070,24 +4211,49 @@ var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
3070
4211
  var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
3071
4212
  var createExecutionRecorder = (options, hooks = {}) => {
3072
4213
  if (!options?.enabled) {
3073
- return hooks.functionMetrics ? createMetricsOnlyRuntime(hooks.functionMetrics) : noOpExecution;
4214
+ return hooks.functionMetrics || hooks.executionMetrics ? createMetricsOnlyRuntime({
4215
+ functionMetrics: hooks.functionMetrics,
4216
+ executionMetrics: hooks.executionMetrics,
4217
+ durationSampler: hooks.durationSampler
4218
+ }) : noOpExecution;
3074
4219
  }
3075
4220
  const functionMetrics = hooks.functionMetrics;
4221
+ const executionMetrics = hooks.executionMetrics;
4222
+ const durationSampler = hooks.durationSampler;
3076
4223
  const bindMetricsExecution = (recording) => {
3077
4224
  if (!functionMetrics) return;
3078
4225
  recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
3079
4226
  executionTypeKey(recording.execution)
3080
4227
  );
3081
4228
  };
4229
+ const bindExecutionMetricsIdentity2 = (recording) => {
4230
+ if (!executionMetrics || !recording.executionMetrics) return;
4231
+ executionMetrics.bindIdentity(
4232
+ recording.executionMetrics,
4233
+ executionTypeKey(recording.execution)
4234
+ );
4235
+ };
3082
4236
  warnIfMissingAsyncContextFrame();
3083
4237
  const adaptiveEnabled = options.adaptive?.enabled === true;
3084
4238
  const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
3085
4239
  options.adaptive?.fullCaptureDurationMs
3086
4240
  );
3087
- const durationSamplingEnabled = adaptiveEnabled && sanitizeDynamicDurationSampling(options.adaptive?.dynamicDurationSampling);
4241
+ const trackCallers = durationSampler !== void 0;
3088
4242
  const readCallClock = () => process.hrtime.bigint();
4243
+ const tryCallClock3 = () => {
4244
+ try {
4245
+ return readCallClock();
4246
+ } catch {
4247
+ return void 0;
4248
+ }
4249
+ };
4250
+ const invocationStart = (measure) => {
4251
+ if (!measure) return { timed: false, startedAtNs: 0n };
4252
+ const startedAtNs = tryCallClock3();
4253
+ if (startedAtNs === void 0) return { timed: false, startedAtNs: 0n };
4254
+ return { timed: true, startedAtNs };
4255
+ };
3089
4256
  const nowMs = () => hooks.nowMs?.() ?? Date.now();
3090
- const durationSamples = durationSamplingEnabled ? createDynamicDurationSampleBuckets({ nowMs }) : void 0;
3091
4257
  const localActivations = /* @__PURE__ */ new Map();
3092
4258
  const policySnapshotFor = () => hooks.policySnapshot?.() ?? localActivations;
3093
4259
  const keyIsActive = (snapshot, key, atMs) => {
@@ -3272,21 +4438,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
3272
4438
  }
3273
4439
  };
3274
4440
  const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
3275
- const durationSamplingApplies = (recording) => durationSamplingEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess;
3276
4441
  const callStoreFor = (store, functionId, callId) => {
3277
4442
  const next = { ...store, currentCallId: callId };
3278
- if (durationSamplingEnabled) next.currentFunctionId = functionId;
4443
+ if (trackCallers) next.currentFunctionId = functionId;
3279
4444
  return next;
3280
4445
  };
3281
4446
  const samplingStore = (store, functionId) => {
3282
- return durationSamplingEnabled ? { ...store, currentFunctionId: functionId } : store;
3283
- };
3284
- const decideCallTiming = (recording, plan, callerFunctionId) => {
3285
- if (!durationSamplingApplies(recording) || !durationSamples) return true;
3286
- const typeKey = executionTypeKey(recording.execution);
3287
- if (!typeKey) return true;
3288
- return durationSamples.take(typeKey, callerFunctionId ?? "", plan.functionId);
3289
- };
4447
+ return trackCallers ? { ...store, currentFunctionId: functionId } : store;
4448
+ };
4449
+ const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess);
4450
+ const planInvocationDuration = (recording, plan, callerFunctionId) => planCallDuration(durationSampler, {
4451
+ forceMeasure: recorderForceMeasure(recording),
4452
+ executionType: executionTypeKey(recording.execution),
4453
+ callerFunctionId: callerFunctionId ?? "",
4454
+ functionId: plan.functionId
4455
+ });
3290
4456
  const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
3291
4457
  const tryAdmitLiveSession = (recording) => {
3292
4458
  if (recording.retainSuccess || recording.finished) return;
@@ -3499,7 +4665,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3499
4665
  },
3500
4666
  functions: functions.slice(),
3501
4667
  events: fullyTimed ? asFullyTimedEvents(events) : events.slice(),
3502
- ...fullyTimed || !durationSamplingEnabled ? {} : { durationSampling: { policy: "progressive" } },
4668
+ ...fullyTimed || !durationSampler ? {} : { durationSampling: { policy: "progressive" } },
3503
4669
  ...truncated ? { truncated: { ...truncated } } : {},
3504
4670
  ...capture ? { capture: { ...capture } } : {}
3505
4671
  };
@@ -3769,7 +4935,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3769
4935
  }
3770
4936
  };
3771
4937
  };
3772
- const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs) => {
4938
+ const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
3773
4939
  if (!recording.journal) {
3774
4940
  return;
3775
4941
  }
@@ -3779,17 +4945,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
3779
4945
  const callId = ++recording.nextCallId;
3780
4946
  const capturedError = serializedError(recording, error, callId);
3781
4947
  const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3782
- const endedAtNs = readCallClock();
4948
+ const endedAtNs = timed ? completedAtNs : void 0;
3783
4949
  const droppedBefore = recording.journal.dropped;
3784
4950
  const retained = recording.journal.forceCompletedCall(
3785
4951
  plan.runtimePlanId,
3786
4952
  callId,
3787
4953
  parentCallId,
3788
- timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4954
+ timed && endedAtNs !== void 0 ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
3789
4955
  recordedArgs,
3790
4956
  KIND_THROW,
3791
- endedAtNs - recording.startedAtNs,
3792
- timed ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
4957
+ timed && endedAtNs !== void 0 ? endedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4958
+ timed && endedAtNs !== void 0 ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
3793
4959
  capturedError.value
3794
4960
  );
3795
4961
  if (retained) {
@@ -3821,6 +4987,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
3821
4987
  appendSuppressedPlaceholder(recording, suppressed);
3822
4988
  }
3823
4989
  };
4990
+ const addSuppressedDuration = (suppressed, startedAtNs, endedAtNs) => {
4991
+ if (!suppressed.firstTimed) {
4992
+ suppressed.firstTimestampNs = startedAtNs;
4993
+ suppressed.firstTimed = true;
4994
+ }
4995
+ suppressed.lastTimestampNs = endedAtNs;
4996
+ suppressed.lastTimed = true;
4997
+ suppressed.sampledDurationCount++;
4998
+ suppressed.sampledDurationNs += endedAtNs - startedAtNs;
4999
+ };
3824
5000
  const releaseJournalIfIdle = (recording) => {
3825
5001
  if (!recording.finished || recording.hasError || recording.inFlightCalls > 0) return;
3826
5002
  if (!recording.journal) return;
@@ -3893,6 +5069,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
3893
5069
  if (metadata) {
3894
5070
  mergeExecutionMetadata(recording.execution, metadata);
3895
5071
  bindMetricsExecution(recording);
5072
+ bindExecutionMetricsIdentity2(recording);
5073
+ }
5074
+ if (executionMetrics && recording.executionMetrics) {
5075
+ const executionKey = executionTypeKey(recording.execution);
5076
+ bindExecutionMetricsIdentity2(recording);
5077
+ executionMetrics.finishExecution(recording.executionMetrics, {
5078
+ failed: executionOutcomeFailed({
5079
+ hasError: recording.hasError,
5080
+ runFailed: recording.runFailed === true,
5081
+ status: recording.execution.request?.status
5082
+ }),
5083
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
5084
+ startedNs: recording.startedAtNs,
5085
+ endedNs: recorderStartedAtNs
5086
+ });
3896
5087
  }
3897
5088
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3898
5089
  if (recording.runFailed && !recording.hasError) {
@@ -3963,6 +5154,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
3963
5154
  };
3964
5155
  if (identityComplete) tryAdmitLiveSession(recording);
3965
5156
  bindMetricsExecution(recording);
5157
+ if (executionMetrics) {
5158
+ recording.executionMetrics = executionMetrics.createState();
5159
+ bindExecutionMetricsIdentity2(recording);
5160
+ }
3966
5161
  stats.activeExecutions++;
3967
5162
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3968
5163
  liveRecordings.push(recording);
@@ -4015,6 +5210,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4015
5210
  mergeExecutionMetadata(recording.execution, nextMetadata);
4016
5211
  completeIdentityFromSnapshot(recording);
4017
5212
  bindMetricsExecution(recording);
5213
+ bindExecutionMetricsIdentity2(recording);
4018
5214
  } catch {
4019
5215
  }
4020
5216
  }
@@ -4031,18 +5227,53 @@ var createExecutionRecorder = (options, hooks = {}) => {
4031
5227
  }
4032
5228
  };
4033
5229
  const runPreparedFunctionFromStore = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5230
+ const duration = plan.excluded ? { selected: false, measure: false } : store ? planInvocationDuration(store.recording, plan, store.currentFunctionId) : { selected: false, measure: false };
5231
+ const startedNs = duration.measure ? tryCallClock3() : void 0;
4034
5232
  const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
4035
5233
  const executionHandle = store?.recording.metricsExecutionHandle;
4036
- const startedNs = startMetricsCall(functionMetrics, functionHandle, executionHandle);
5234
+ const metricsStart = startMetricsCall(functionMetrics, functionHandle, executionHandle, {
5235
+ measure: duration.selected,
5236
+ ...duration.selected ? { startedNs } : {}
5237
+ });
5238
+ const sharedClock = {
5239
+ start: startedNs,
5240
+ timed: startedNs !== void 0,
5241
+ selected: duration.selected
5242
+ };
5243
+ const applyRecorderEnd = (endedNs) => {
5244
+ if (endedNs === void 0) return;
5245
+ sharedClock.end = endedNs;
5246
+ sharedClock.applyEnd?.(endedNs);
5247
+ };
4037
5248
  const settle = (value, failed) => {
4038
- if (!functionMetrics || startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
5249
+ const pending = !failed && value instanceof Promise;
5250
+ if (!pending && sharedClock.timed && sharedClock.end === void 0) {
5251
+ sharedClock.end = tryCallClock3();
5252
+ }
5253
+ if (!functionMetrics || !metricsStart || functionHandle === void 0 || executionHandle === void 0) {
4039
5254
  return;
4040
5255
  }
5256
+ const timing = sharedClock.selected ? { startedNs: sharedClock.start, endedNs: sharedClock.end } : void 0;
4041
5257
  if (failed) {
4042
- finishMetricsCall(functionMetrics, functionHandle, executionHandle, startedNs, true);
5258
+ finishMetricsCall(functionMetrics, functionHandle, executionHandle, true, timing);
4043
5259
  return;
4044
5260
  }
4045
- completeMetricsResult(functionMetrics, functionHandle, executionHandle, startedNs, value);
5261
+ completeMetricsResult(
5262
+ functionMetrics,
5263
+ functionHandle,
5264
+ executionHandle,
5265
+ value,
5266
+ timing,
5267
+ (endedNs) => {
5268
+ if (endedNs !== void 0) {
5269
+ applyRecorderEnd(endedNs);
5270
+ return;
5271
+ }
5272
+ if (!sharedClock.selected && sharedClock.timed) {
5273
+ applyRecorderEnd(tryCallClock3());
5274
+ }
5275
+ }
5276
+ );
4046
5277
  };
4047
5278
  let startedCallback = false;
4048
5279
  try {
@@ -4054,7 +5285,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4054
5285
  startedCallback = true;
4055
5286
  return callback();
4056
5287
  },
4057
- omitValues
5288
+ omitValues,
5289
+ sharedClock
4058
5290
  );
4059
5291
  settle(result, false);
4060
5292
  return result;
@@ -4068,7 +5300,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4068
5300
  return result;
4069
5301
  }
4070
5302
  };
4071
- const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5303
+ const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues, sharedClock) {
4072
5304
  const omitCallValues = omitValues === true || plan.omitCallValues;
4073
5305
  if (!store) return callback();
4074
5306
  if (plan.disabled) {
@@ -4104,9 +5336,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4104
5336
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
4105
5337
  } catch {
4106
5338
  }
4107
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
5339
+ const timed = sharedClock.timed;
5340
+ const startedAtNs = sharedClock.start ?? 0n;
4108
5341
  if (group.observedCalls > capturedCallLimitFor(recording)) {
4109
- const startedAtNs2 = timed ? readCallClock() : 0n;
4110
5342
  try {
4111
5343
  const result = runStore(
4112
5344
  samplingStore(store, plan.functionId),
@@ -4114,23 +5346,48 @@ var createExecutionRecorder = (options, hooks = {}) => {
4114
5346
  return callback();
4115
5347
  }
4116
5348
  );
4117
- recordSuppressedCall(
4118
- recording,
4119
- group,
4120
- parentCallId,
4121
- startedAtNs2,
4122
- timed ? readCallClock() : 0n,
4123
- timed
4124
- );
5349
+ if (result instanceof Promise) {
5350
+ recordSuppressedCall(recording, group, parentCallId, startedAtNs, 0n, false);
5351
+ if (timed) {
5352
+ const suppressed = group.suppressed;
5353
+ sharedClock.applyEnd = (endedNs) => {
5354
+ if (endedNs === void 0 || recording.finished || !suppressed || group.suppressed !== suppressed) {
5355
+ return;
5356
+ }
5357
+ addSuppressedDuration(suppressed, startedAtNs, endedNs);
5358
+ };
5359
+ }
5360
+ } else {
5361
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5362
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5363
+ recordSuppressedCall(
5364
+ recording,
5365
+ group,
5366
+ parentCallId,
5367
+ startedAtNs,
5368
+ endedAtNs ?? 0n,
5369
+ endedAtNs !== void 0
5370
+ );
5371
+ }
4125
5372
  settleInFlight(recording);
4126
5373
  return result;
4127
5374
  } catch (error) {
4128
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs2, error, timed);
5375
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5376
+ captureCompletedThrow(
5377
+ recording,
5378
+ plan,
5379
+ args,
5380
+ parentCallId,
5381
+ startedAtNs,
5382
+ error,
5383
+ timed,
5384
+ void 0,
5385
+ sharedClock.end
5386
+ );
4129
5387
  settleInFlight(recording);
4130
5388
  throw error;
4131
5389
  }
4132
5390
  }
4133
- const startedAtNs = timed ? readCallClock() : 0n;
4134
5391
  if (!journal) {
4135
5392
  memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes);
4136
5393
  return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
@@ -4159,7 +5416,18 @@ var createExecutionRecorder = (options, hooks = {}) => {
4159
5416
  callback,
4160
5417
  captureSuccess,
4161
5418
  (error) => {
4162
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs, error, timed);
5419
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5420
+ captureCompletedThrow(
5421
+ recording,
5422
+ plan,
5423
+ args,
5424
+ parentCallId,
5425
+ startedAtNs,
5426
+ error,
5427
+ timed,
5428
+ void 0,
5429
+ sharedClock.end
5430
+ );
4163
5431
  settleInFlight(recording);
4164
5432
  }
4165
5433
  );
@@ -4179,7 +5447,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4179
5447
  });
4180
5448
  }
4181
5449
  const callId = ++recording.nextCallId;
4182
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
5450
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
4183
5451
  const capturedArgs = enterPayload(recording, omitCallValues, args);
4184
5452
  try {
4185
5453
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -4205,7 +5473,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4205
5473
  callback,
4206
5474
  (value) => {
4207
5475
  if (recording.journal) {
4208
- const endedAtNs = timed ? readCallClock() : void 0;
5476
+ const pending = value instanceof Promise;
5477
+ const endedAtNs = timed && !pending ? tryCallClock3() : void 0;
5478
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
4209
5479
  const returnValue = exitPayload(recording, omitCallValues, value);
4210
5480
  if (endedAtNs !== void 0) {
4211
5481
  recording.journal.finishCall(
@@ -4224,6 +5494,19 @@ var createExecutionRecorder = (options, hooks = {}) => {
4224
5494
  returnValue
4225
5495
  );
4226
5496
  }
5497
+ if (pending && timed) {
5498
+ const journal2 = recording.journal;
5499
+ sharedClock.applyEnd = (endedNs) => {
5500
+ if (endedNs === void 0 || recording.finished || recording.journal !== journal2) {
5501
+ return;
5502
+ }
5503
+ journal2.setCallTiming(
5504
+ callId,
5505
+ endedNs - recording.startedAtNs,
5506
+ endedNs - startedAtNs
5507
+ );
5508
+ };
5509
+ }
4227
5510
  stats.functionCallsCaptured++;
4228
5511
  }
4229
5512
  settleInFlight(recording);
@@ -4234,14 +5517,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
4234
5517
  return;
4235
5518
  }
4236
5519
  const capturedError = serializedError(recording, error, callId);
4237
- const endedAtNs = readCallClock();
4238
- recording.journal.finishCall(
4239
- KIND_THROW,
4240
- callId,
4241
- endedAtNs - recording.startedAtNs,
4242
- timed ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
4243
- capturedError.value
4244
- );
5520
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5521
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5522
+ if (endedAtNs !== void 0) {
5523
+ recording.journal.finishCall(
5524
+ KIND_THROW,
5525
+ callId,
5526
+ endedAtNs - recording.startedAtNs,
5527
+ endedAtNs - startedAtNs,
5528
+ capturedError.value
5529
+ );
5530
+ } else {
5531
+ recording.journal.finishCall(
5532
+ KIND_THROW,
5533
+ callId,
5534
+ TIMING_UNAVAILABLE,
5535
+ TIMING_UNAVAILABLE,
5536
+ capturedError.value
5537
+ );
5538
+ }
4245
5539
  stats.functionCallsCaptured++;
4246
5540
  capturedError.commit();
4247
5541
  settleInFlight(recording);
@@ -4270,21 +5564,24 @@ var createExecutionRecorder = (options, hooks = {}) => {
4270
5564
  this.group = group;
4271
5565
  this.captureDroppedThrow = captureDroppedThrow;
4272
5566
  this.callerClaimed = false;
5567
+ this.completedAtNs = void 0;
5568
+ this.metricsSelected = false;
4273
5569
  this.metricsOpen = false;
5570
+ this.metricsMeasure = false;
4274
5571
  this.metricsFailed = false;
4275
5572
  this.metricsFunctionHandle = 0;
4276
5573
  this.metricsExecutionHandle = 0;
4277
- this.metricsStartedNs = 0n;
5574
+ this.metricsStartedNs = void 0;
4278
5575
  }
4279
5576
  claimCaller() {
4280
- if (this.callerClaimed || !durationSamplingEnabled || !this.plan) return;
5577
+ if (this.callerClaimed || !trackCallers || !this.plan) return;
4281
5578
  if (this.activeStore !== this.parentStore) return;
4282
5579
  this.previousFunctionId = this.parentStore.currentFunctionId;
4283
5580
  this.parentStore.currentFunctionId = this.plan.functionId;
4284
5581
  this.callerClaimed = true;
4285
5582
  }
4286
5583
  reclaimCaller() {
4287
- if (!durationSamplingEnabled || !this.plan || this.activeStore !== this.parentStore) return;
5584
+ if (!trackCallers || !this.plan || this.activeStore !== this.parentStore) return;
4288
5585
  this.parentStore.currentFunctionId = this.plan.functionId;
4289
5586
  this.callerClaimed = true;
4290
5587
  }
@@ -4310,6 +5607,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4310
5607
  if (this.status === "failed") return;
4311
5608
  this.status = "failed";
4312
5609
  this.metricsFailed = true;
5610
+ if (this.timed && this.completedAtNs === void 0) {
5611
+ this.completedAtNs = tryCallClock3();
5612
+ }
4313
5613
  if (this.mode === "captured") writeCapturedThrow(this, error);
4314
5614
  else if (this.mode === "suppressed" && this.plan) {
4315
5615
  captureCompletedThrow(
@@ -4320,7 +5620,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4320
5620
  this.startedAtNs,
4321
5621
  error,
4322
5622
  this.timed,
4323
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5623
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5624
+ this.completedAtNs
4324
5625
  );
4325
5626
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
4326
5627
  captureCompletedThrow(
@@ -4331,25 +5632,28 @@ var createExecutionRecorder = (options, hooks = {}) => {
4331
5632
  this.startedAtNs,
4332
5633
  error,
4333
5634
  this.timed,
4334
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5635
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5636
+ this.completedAtNs
4335
5637
  );
4336
5638
  }
4337
5639
  } catch {
4338
5640
  }
4339
5641
  }
4340
5642
  end() {
4341
- let endedAtNs;
5643
+ let endedAtNs = this.completedAtNs;
5644
+ if (endedAtNs === void 0 && this.timed) {
5645
+ endedAtNs = tryCallClock3();
5646
+ this.completedAtNs = endedAtNs;
5647
+ }
4342
5648
  if (this.metricsOpen && functionMetrics) {
4343
5649
  this.metricsOpen = false;
4344
5650
  try {
4345
- endedAtNs = readCallClock();
4346
5651
  finishMetricsCall(
4347
5652
  functionMetrics,
4348
5653
  this.metricsFunctionHandle,
4349
5654
  this.metricsExecutionHandle,
4350
- this.metricsStartedNs,
4351
5655
  this.metricsFailed,
4352
- endedAtNs
5656
+ this.metricsMeasure ? { startedNs: this.metricsStartedNs, endedNs: endedAtNs } : void 0
4353
5657
  );
4354
5658
  } catch {
4355
5659
  }
@@ -4369,8 +5673,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4369
5673
  this.group,
4370
5674
  this.parentCallId,
4371
5675
  this.startedAtNs,
4372
- this.timed ? endedAtNs ?? readCallClock() : 0n,
4373
- this.timed
5676
+ endedAtNs ?? 0n,
5677
+ this.timed && endedAtNs !== void 0
4374
5678
  );
4375
5679
  } else if (this.mode === "dropped") {
4376
5680
  const droppedBefore = this.recording.journal?.dropped ?? 0;
@@ -4444,7 +5748,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4444
5748
  };
4445
5749
  const writeCapturedExit = (frame, value, completedAtNs) => {
4446
5750
  if (!frame.recording.journal) return;
4447
- const endedAtNs = frame.timed ? completedAtNs ?? readCallClock() : void 0;
5751
+ const endedAtNs = frame.timed ? completedAtNs : void 0;
4448
5752
  const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
4449
5753
  if (endedAtNs !== void 0) {
4450
5754
  frame.recording.journal.finishCall(
@@ -4467,37 +5771,47 @@ var createExecutionRecorder = (options, hooks = {}) => {
4467
5771
  };
4468
5772
  const writeCapturedThrow = (frame, error) => {
4469
5773
  if (!frame.recording.journal) return;
4470
- const endedAtNs = readCallClock();
5774
+ const endedAtNs = frame.timed ? frame.completedAtNs : void 0;
4471
5775
  const capturedError = serializedError(frame.recording, error, frame.callId);
4472
- frame.recording.journal.finishCall(
4473
- KIND_THROW,
4474
- frame.callId,
4475
- endedAtNs - frame.recording.startedAtNs,
4476
- frame.timed ? endedAtNs - frame.startedAtNs : TIMING_UNAVAILABLE,
4477
- capturedError.value
4478
- );
5776
+ if (endedAtNs !== void 0) {
5777
+ frame.recording.journal.finishCall(
5778
+ KIND_THROW,
5779
+ frame.callId,
5780
+ endedAtNs - frame.recording.startedAtNs,
5781
+ endedAtNs - frame.startedAtNs,
5782
+ capturedError.value
5783
+ );
5784
+ } else {
5785
+ frame.recording.journal.finishCall(
5786
+ KIND_THROW,
5787
+ frame.callId,
5788
+ TIMING_UNAVAILABLE,
5789
+ TIMING_UNAVAILABLE,
5790
+ capturedError.value
5791
+ );
5792
+ }
4479
5793
  stats.functionCallsCaptured++;
4480
5794
  capturedError.commit();
4481
5795
  };
4482
5796
  const armCallFrameMetrics = (frame, plan) => {
4483
5797
  if (!functionMetrics || plan.excluded) return;
4484
5798
  const functionHandle = internPreparedMetrics(functionMetrics, plan);
4485
- const reuseStart = frame.timed && frame.startedAtNs !== 0n ? frame.startedAtNs : void 0;
4486
- const startedNs = startMetricsCall(
5799
+ const started = startMetricsCall(
4487
5800
  functionMetrics,
4488
5801
  functionHandle,
4489
5802
  frame.recording.metricsExecutionHandle,
4490
- reuseStart
5803
+ frame.metricsSelected ? { measure: true, startedNs: frame.timed ? frame.startedAtNs : void 0 } : { measure: false }
4491
5804
  );
4492
- if (startedNs === void 0 || functionHandle === void 0) return;
5805
+ if (!started || functionHandle === void 0) return;
4493
5806
  const executionHandle = frame.recording.metricsExecutionHandle;
4494
5807
  if (executionHandle === void 0) return;
4495
5808
  frame.metricsOpen = true;
5809
+ frame.metricsMeasure = started.measure;
4496
5810
  frame.metricsFunctionHandle = functionHandle;
4497
5811
  frame.metricsExecutionHandle = executionHandle;
4498
- frame.metricsStartedNs = startedNs;
5812
+ frame.metricsStartedNs = started.startedNs;
4499
5813
  };
4500
- const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow) => {
5814
+ const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected) => {
4501
5815
  const frame = new CallFrame(
4502
5816
  mode,
4503
5817
  recording,
@@ -4513,6 +5827,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4513
5827
  group,
4514
5828
  captureDroppedThrow
4515
5829
  );
5830
+ frame.metricsSelected = selected;
4516
5831
  frame.claimCaller();
4517
5832
  enterStore(frame, parentStore);
4518
5833
  armCallFrameMetrics(frame, plan);
@@ -4526,6 +5841,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4526
5841
  }
4527
5842
  if (store.recording.finished) {
4528
5843
  if (!store.recording.budgetExpired && !store.recording.evicted) return noopHandle2;
5844
+ const duration2 = planInvocationDuration(store.recording, plan, store.currentFunctionId);
5845
+ const start2 = invocationStart(duration2.measure);
4529
5846
  const expiredStore = { recording: store.recording };
4530
5847
  const expired = new CallFrame(
4531
5848
  "expired",
@@ -4536,12 +5853,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
4536
5853
  EMPTY_ARGS,
4537
5854
  false,
4538
5855
  void 0,
4539
- 0n,
4540
- true,
5856
+ start2.startedAtNs,
5857
+ start2.timed,
4541
5858
  0,
4542
5859
  void 0,
4543
5860
  false
4544
5861
  );
5862
+ expired.metricsSelected = duration2.selected;
4545
5863
  armCallFrameMetrics(expired, plan);
4546
5864
  return expired;
4547
5865
  }
@@ -4551,6 +5869,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4551
5869
  const parentCallId = store.currentCallId;
4552
5870
  if (skipCapture(store, plan)) {
4553
5871
  stats.functionCallsExcluded++;
5872
+ const excludedDuration = plan.excluded ? { selected: false, measure: false } : planInvocationDuration(recording, plan, store.currentFunctionId);
5873
+ const start2 = invocationStart(excludedDuration.measure);
4554
5874
  const excludedStore = { ...store, suppressCapture: true };
4555
5875
  const frame = new CallFrame(
4556
5876
  "excluded",
@@ -4561,12 +5881,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
4561
5881
  EMPTY_ARGS,
4562
5882
  false,
4563
5883
  void 0,
4564
- 0n,
4565
- true,
5884
+ start2.startedAtNs,
5885
+ start2.timed,
4566
5886
  0,
4567
5887
  void 0,
4568
5888
  false
4569
5889
  );
5890
+ frame.metricsSelected = excludedDuration.selected;
4570
5891
  enterStore(frame, excludedStore);
4571
5892
  armCallFrameMetrics(frame, plan);
4572
5893
  return frame;
@@ -4579,8 +5900,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
4579
5900
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
4580
5901
  } catch {
4581
5902
  }
4582
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
4583
- const startedAtNs = timed ? readCallClock() : 0n;
5903
+ const duration = planInvocationDuration(recording, plan, store.currentFunctionId);
5904
+ const start = invocationStart(duration.measure);
5905
+ const timed = start.timed;
5906
+ const startedAtNs = start.startedAtNs;
4584
5907
  const parentStore = store;
4585
5908
  const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
4586
5909
  if (group.observedCalls > capturedCallLimitFor(recording)) {
@@ -4595,7 +5918,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4595
5918
  startedAtNs,
4596
5919
  timed,
4597
5920
  group,
4598
- false
5921
+ false,
5922
+ duration.selected
4599
5923
  );
4600
5924
  }
4601
5925
  if (!journal) {
@@ -4611,7 +5935,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4611
5935
  startedAtNs,
4612
5936
  timed,
4613
5937
  group,
4614
- false
5938
+ false,
5939
+ duration.selected
4615
5940
  );
4616
5941
  }
4617
5942
  if (!journal.canStartCall()) {
@@ -4626,7 +5951,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4626
5951
  startedAtNs,
4627
5952
  timed,
4628
5953
  group,
4629
- true
5954
+ true,
5955
+ duration.selected
4630
5956
  );
4631
5957
  }
4632
5958
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
@@ -4641,11 +5967,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
4641
5967
  startedAtNs,
4642
5968
  timed,
4643
5969
  group,
4644
- false
5970
+ false,
5971
+ duration.selected
4645
5972
  );
4646
5973
  }
4647
5974
  const callId = ++recording.nextCallId;
4648
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
5975
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
4649
5976
  const capturedArgs = enterPayload(recording, omitCallValues, args);
4650
5977
  try {
4651
5978
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -4662,7 +5989,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4662
5989
  startedAtNs,
4663
5990
  timed,
4664
5991
  group,
4665
- false
5992
+ false,
5993
+ duration.selected
4666
5994
  );
4667
5995
  }
4668
5996
  const callStore = callStoreFor(store, plan.functionId, callId);
@@ -4681,6 +6009,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4681
6009
  group,
4682
6010
  false
4683
6011
  );
6012
+ captured.metricsSelected = duration.selected;
4684
6013
  enterStore(captured, callStore);
4685
6014
  armCallFrameMetrics(captured, plan);
4686
6015
  return captured;
@@ -4750,7 +6079,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4750
6079
  enterPreparedFunction,
4751
6080
  trace,
4752
6081
  close: () => {
4753
- durationSamples?.stop();
6082
+ durationSampler?.stop();
4754
6083
  },
4755
6084
  getStats: () => ({
4756
6085
  ...stats,
@@ -4807,14 +6136,14 @@ var installAutomaticExecutionRuntime = (execution) => {
4807
6136
  // src/execution-recorder/bind-adaptive-recorder.ts
4808
6137
  import {
4809
6138
  resolveClientActivation,
4810
- resolveEndpointUrls as resolveEndpointUrls2
6139
+ resolveEndpointUrls as resolveEndpointUrls3
4811
6140
  } from "@rasputin-ai/core";
4812
6141
 
4813
6142
  // src/execution-recorder/execution-recording-sync.ts
4814
6143
  import {
4815
6144
  copyRedactKeys,
4816
- defaultIngestFetch,
4817
- encodeJsonRequestBodyAsync,
6145
+ defaultIngestFetch as defaultIngestFetch2,
6146
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
4818
6147
  MAX_REDACT_KEYS
4819
6148
  } from "@rasputin-ai/core";
4820
6149
 
@@ -4997,7 +6326,7 @@ var MAX_CACHE_ENTRIES = 1024;
4997
6326
  var MAX_PENDING_NOTIFIES = 32;
4998
6327
  var MAX_PENDING_TYPES = 64;
4999
6328
  var DEFAULT_POLL_INTERVAL_MS = 1e4;
5000
- var REQUEST_TIMEOUT_MS = 5e3;
6329
+ var REQUEST_TIMEOUT_MS2 = 5e3;
5001
6330
  var MAX_RETRIES = 5;
5002
6331
  var MAX_POLL_JITTER_MS = 2e3;
5003
6332
  var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
@@ -5012,7 +6341,7 @@ var classifyHttpFailure = (status) => {
5012
6341
  if (status >= 500) return "server_error";
5013
6342
  return "non_retryable_http";
5014
6343
  };
5015
- var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
6344
+ var backoffMs2 = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
5016
6345
  var abortFrom = (parent, child) => {
5017
6346
  const onAbort = () => child.abort();
5018
6347
  parent.addEventListener("abort", onAbort, { once: true });
@@ -5022,7 +6351,7 @@ var abortFrom = (parent, child) => {
5022
6351
  var createExecutionRecordingCoordinator = (options) => {
5023
6352
  const environment = options.environment;
5024
6353
  const nowMs = () => options.nowMs?.() ?? Date.now();
5025
- const fetchFn = options.fetch ?? defaultIngestFetch();
6354
+ const fetchFn = options.fetch ?? defaultIngestFetch2();
5026
6355
  const instanceId = crypto.randomUUID();
5027
6356
  const startedAt = /* @__PURE__ */ new Date();
5028
6357
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
@@ -5159,7 +6488,7 @@ var createExecutionRecordingCoordinator = (options) => {
5159
6488
  };
5160
6489
  const withRequestTimeout = async (signal, run) => {
5161
6490
  const request = new AbortController();
5162
- const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS);
6491
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
5163
6492
  timer.unref?.();
5164
6493
  const stopParent = abortFrom(signal, request);
5165
6494
  const stopCancel = abortFrom(cancelWork.signal, request);
@@ -5219,7 +6548,7 @@ var createExecutionRecordingCoordinator = (options) => {
5219
6548
  notifyFailures++;
5220
6549
  return false;
5221
6550
  }
5222
- await wait(backoffMs(attempt), signal);
6551
+ await wait(backoffMs2(attempt), signal);
5223
6552
  } catch (error) {
5224
6553
  if (signal.aborted || error instanceof Error && error.name === "AbortError") {
5225
6554
  rememberFailure("aborted");
@@ -5230,7 +6559,7 @@ var createExecutionRecordingCoordinator = (options) => {
5230
6559
  notifyFailures++;
5231
6560
  return false;
5232
6561
  }
5233
- await wait(backoffMs(attempt), signal);
6562
+ await wait(backoffMs2(attempt), signal);
5234
6563
  }
5235
6564
  }
5236
6565
  return false;
@@ -5428,7 +6757,7 @@ var createExecutionRecordingCoordinator = (options) => {
5428
6757
  if (combined.aborted) return false;
5429
6758
  let encoded;
5430
6759
  try {
5431
- encoded = await encodeJsonRequestBodyAsync(
6760
+ encoded = await encodeJsonRequestBodyAsync2(
5432
6761
  {
5433
6762
  instance_id: instanceId,
5434
6763
  recordings: batch.map((item) => ({
@@ -5479,7 +6808,7 @@ var createExecutionRecordingCoordinator = (options) => {
5479
6808
  rememberFailure(kind);
5480
6809
  if (kind === "non_retryable_http") return true;
5481
6810
  if (attempt === MAX_RETRIES) return false;
5482
- await wait(backoffMs(attempt), combined);
6811
+ await wait(backoffMs2(attempt), combined);
5483
6812
  } catch (error) {
5484
6813
  if (combined.aborted || error instanceof Error && error.name === "AbortError") {
5485
6814
  rememberFailure("aborted");
@@ -5487,7 +6816,7 @@ var createExecutionRecordingCoordinator = (options) => {
5487
6816
  }
5488
6817
  rememberFailure("network_error");
5489
6818
  if (attempt === MAX_RETRIES) return false;
5490
- await wait(backoffMs(attempt), combined);
6819
+ await wait(backoffMs2(attempt), combined);
5491
6820
  }
5492
6821
  }
5493
6822
  return false;
@@ -5661,9 +6990,9 @@ var bindAdaptiveRecorder = (input) => {
5661
6990
  const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
5662
6991
  environment: activation.environment,
5663
6992
  ingestToken: activation.ingestToken,
5664
- activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5665
- syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5666
- recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
6993
+ activateUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingActivateUrl,
6994
+ syncUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingSyncUrl,
6995
+ recordingsUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingRecordingsUrl,
5667
6996
  sdkName: input.sdkName,
5668
6997
  sdkVersion: input.sdkVersion,
5669
6998
  release: activation.release,
@@ -5683,6 +7012,8 @@ var bindAdaptiveRecorder = (input) => {
5683
7012
  recorderHooks.onSessionRecording = coordinator.enqueueRecording;
5684
7013
  }
5685
7014
  if (input.functionMetrics) recorderHooks.functionMetrics = input.functionMetrics;
7015
+ if (input.executionMetrics) recorderHooks.executionMetrics = input.executionMetrics;
7016
+ if (input.durationSampler) recorderHooks.durationSampler = input.durationSampler;
5686
7017
  const runtime = createExecutionRecorder(
5687
7018
  { ...options, enabled: input.recorderEnabled },
5688
7019
  recorderHooks
@@ -5691,34 +7022,35 @@ var bindAdaptiveRecorder = (input) => {
5691
7022
  };
5692
7023
 
5693
7024
  // src/function-metrics/bind-function-metrics.ts
5694
- import { randomUUID as randomUUID2 } from "node:crypto";
7025
+ import { randomUUID as randomUUID4 } from "node:crypto";
5695
7026
  import {
5696
- defaultIngestFetch as defaultIngestFetch2,
5697
- resolveEndpointUrls as resolveEndpointUrls3
7027
+ defaultIngestFetch as defaultIngestFetch3,
7028
+ resolveEndpointUrls as resolveEndpointUrls4
5698
7029
  } from "@rasputin-ai/core";
5699
7030
 
5700
7031
  // src/function-metrics/function-metrics-collector.ts
5701
7032
  import {
5702
- durationHistogramBucket,
5703
- FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
5704
- FUNCTION_METRICS_MAX_ACTIVE_SERIES,
5705
- FUNCTION_METRICS_MAX_BUFFERED_MS,
5706
- FUNCTION_METRICS_MAX_EXECUTION_TYPES,
7033
+ durationHistogramBucket as durationHistogramBucket2,
7034
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT as FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2,
7035
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES as FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7036
+ FUNCTION_METRICS_MAX_BUFFERED_MS as FUNCTION_METRICS_MAX_BUFFERED_MS2,
7037
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES as FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
5707
7038
  FUNCTION_METRICS_MAX_FUNCTIONS,
5708
- FUNCTION_METRICS_MAX_MINUTE_ROWS,
5709
- FUNCTION_METRICS_MAX_STATE_BYTES,
5710
- FUNCTION_METRICS_MINUTE_MS,
7039
+ FUNCTION_METRICS_MAX_MINUTE_ROWS as FUNCTION_METRICS_MAX_MINUTE_ROWS2,
7040
+ FUNCTION_METRICS_MAX_STATE_BYTES as FUNCTION_METRICS_MAX_STATE_BYTES2,
7041
+ FUNCTION_METRICS_MEASUREMENT_FORMAT as FUNCTION_METRICS_MEASUREMENT_FORMAT2,
7042
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS3,
7043
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT as FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2,
5711
7044
  functionIdentityKey,
5712
- isCanonicalFunctionMetricsExecutionKey
7045
+ isCanonicalFunctionMetricsExecutionKey as isCanonicalFunctionMetricsExecutionKey2
5713
7046
  } from "@rasputin-ai/core";
5714
7047
 
5715
7048
  // src/function-metrics/function-metrics-batches.ts
5716
- import { randomUUID } from "node:crypto";
7049
+ import { randomUUID as randomUUID3 } from "node:crypto";
5717
7050
  import {
5718
- FUNCTION_METRICS_MEASUREMENT_FORMAT,
5719
7051
  FUNCTION_METRICS_SCHEMA_VERSION
5720
7052
  } from "@rasputin-ai/core";
5721
- var emptyCoverage = (buckets) => ({
7053
+ var emptyCoverage3 = (buckets) => ({
5722
7054
  covered_bucket_starts: buckets,
5723
7055
  skipped_unresolved_execution_type: 0,
5724
7056
  dropped_active_series: 0,
@@ -5727,8 +7059,8 @@ var emptyCoverage = (buckets) => ({
5727
7059
  dropped_late_completion: 0,
5728
7060
  dropped_unexportable: 0
5729
7061
  });
5730
- var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
5731
- var sparseHistogram = (histogram) => {
7062
+ var bucketStart2 = (minute) => new Date(minute * 6e4).toISOString();
7063
+ var sparseHistogram2 = (histogram) => {
5732
7064
  const cells = [];
5733
7065
  for (let index = 0; index < histogram.length; index += 1) {
5734
7066
  const count = histogram[index] ?? 0;
@@ -5736,10 +7068,10 @@ var sparseHistogram = (histogram) => {
5736
7068
  }
5737
7069
  return cells;
5738
7070
  };
5739
- var toMinute = (row, functionIndex, executionTypeIndex) => ({
7071
+ var toMinute2 = (row, functionIndex, executionTypeIndex) => ({
5740
7072
  function_index: functionIndex,
5741
7073
  execution_type_index: executionTypeIndex,
5742
- bucket_start: bucketStart(row.minute),
7074
+ bucket_start: bucketStart2(row.minute),
5743
7075
  started_calls: row.series.started,
5744
7076
  completed_calls: row.series.completed,
5745
7077
  failed_calls: row.series.failed,
@@ -5747,7 +7079,7 @@ var toMinute = (row, functionIndex, executionTypeIndex) => ({
5747
7079
  duration_sample_sum_us: row.series.sampleSumUs,
5748
7080
  duration_sample_min_us: row.series.sampleMinUs,
5749
7081
  duration_sample_max_us: row.series.sampleMaxUs,
5750
- duration_histogram: sparseHistogram(row.series.histogram),
7082
+ duration_histogram: sparseHistogram2(row.series.histogram),
5751
7083
  invalid_timing_count: row.series.invalidTiming
5752
7084
  });
5753
7085
  var rowsFromQueue = (queued) => {
@@ -5797,7 +7129,7 @@ var chunkRows = (rows, maxFunctions, maxExecutionTypes, maxMinuteRows) => {
5797
7129
  flush();
5798
7130
  return chunks;
5799
7131
  };
5800
- var batchForChunk = (draft, rows, coverage) => {
7132
+ var batchForChunk2 = (draft, rows, coverage) => {
5801
7133
  const functionIndexes = /* @__PURE__ */ new Map();
5802
7134
  const executionIndexes = /* @__PURE__ */ new Map();
5803
7135
  const functions = [];
@@ -5820,12 +7152,12 @@ var batchForChunk = (draft, rows, coverage) => {
5820
7152
  executionIndexes.set(row.executionHandle, executionTypeIndex);
5821
7153
  executionTypes.push({ execution_key: executionKey });
5822
7154
  }
5823
- minutes.push(toMinute(row, functionIndex, executionTypeIndex));
7155
+ minutes.push(toMinute2(row, functionIndex, executionTypeIndex));
5824
7156
  }
5825
7157
  const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
5826
7158
  return {
5827
7159
  schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5828
- measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
7160
+ measurement_format: draft.measurementFormat,
5829
7161
  producer_id: draft.producerId,
5830
7162
  batch_id: draft.batchId(),
5831
7163
  environment: draft.environment,
@@ -5846,7 +7178,7 @@ var functionMetricsBatchesFromQueue = (draft) => {
5846
7178
  return [
5847
7179
  {
5848
7180
  schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5849
- measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
7181
+ measurement_format: draft.measurementFormat,
5850
7182
  producer_id: draft.producerId,
5851
7183
  batch_id: draft.batchId(),
5852
7184
  environment: draft.environment,
@@ -5860,29 +7192,29 @@ var functionMetricsBatchesFromQueue = (draft) => {
5860
7192
  }
5861
7193
  const chunks = chunkRows(rows, draft.maxFunctions, draft.maxExecutionTypes, draft.maxMinuteRows);
5862
7194
  return chunks.map(
5863
- (chunk, index) => batchForChunk(draft, chunk, index === 0 ? draft.coverage : emptyCoverage([]))
7195
+ (chunk, index) => batchForChunk2(draft, chunk, index === 0 ? draft.coverage : emptyCoverage3([]))
5864
7196
  );
5865
7197
  };
5866
- var newFunctionMetricsBatchId = () => randomUUID();
7198
+ var newFunctionMetricsBatchId = () => randomUUID3();
5867
7199
 
5868
7200
  // src/function-metrics/function-metrics-collector.ts
5869
- var SERIES_BYTES = 256;
5870
- var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
7201
+ var SERIES_BYTES2 = 256;
7202
+ var HISTOGRAM_BYTES2 = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2 * 4;
5871
7203
  var DECLARATION_BYTES = 1024;
5872
- var MAX_ELAPSED_NS = BigInt(Number.MAX_SAFE_INTEGER);
5873
- var defaultLimits = () => ({
5874
- maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES,
5875
- maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES,
5876
- maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS / FUNCTION_METRICS_MINUTE_MS,
7204
+ var MAX_ELAPSED_NS2 = BigInt(Number.MAX_SAFE_INTEGER);
7205
+ var defaultLimits2 = () => ({
7206
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7207
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES2,
7208
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS2 / FUNCTION_METRICS_MINUTE_MS3,
5877
7209
  maxFunctions: FUNCTION_METRICS_MAX_FUNCTIONS,
5878
- maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
5879
- maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
7210
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
7211
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS2
5880
7212
  });
5881
- var defaultClock = () => ({
7213
+ var defaultClock2 = () => ({
5882
7214
  monotonicNs: () => process.hrtime.bigint(),
5883
7215
  wallTimeMs: () => Date.now()
5884
7216
  });
5885
- var emptyCoverage2 = () => ({
7217
+ var emptyCoverage4 = () => ({
5886
7218
  covered_bucket_starts: [],
5887
7219
  skipped_unresolved_execution_type: 0,
5888
7220
  dropped_active_series: 0,
@@ -5891,23 +7223,23 @@ var emptyCoverage2 = () => ({
5891
7223
  dropped_late_completion: 0,
5892
7224
  dropped_unexportable: 0
5893
7225
  });
5894
- var note = (coverage, counter, amount = 1) => {
7226
+ var note2 = (coverage, counter, amount = 1) => {
5895
7227
  const next = coverage[counter] + amount;
5896
7228
  coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
5897
7229
  };
5898
- var countSeries = (table) => {
7230
+ var countSeries2 = (table) => {
5899
7231
  let count = 0;
5900
7232
  for (const byExecution of table.values()) count += byExecution.size;
5901
7233
  return count;
5902
7234
  };
5903
- var tableBytes = (table) => {
7235
+ var tableBytes2 = (table) => {
5904
7236
  let bytes = 0;
5905
7237
  for (const byExecution of table.values()) {
5906
7238
  for (const series of byExecution.values()) bytes += series.bytes;
5907
7239
  }
5908
7240
  return bytes;
5909
7241
  };
5910
- var discardedMarks = (table) => {
7242
+ var discardedMarks2 = (table) => {
5911
7243
  let marks = 0;
5912
7244
  for (const byExecution of table.values()) {
5913
7245
  for (const series of byExecution.values()) {
@@ -5917,12 +7249,12 @@ var discardedMarks = (table) => {
5917
7249
  }
5918
7250
  return marks;
5919
7251
  };
5920
- var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
5921
- var copySeries = (series) => ({
7252
+ var seriesHasMarks2 = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
7253
+ var copySeries2 = (series) => ({
5922
7254
  ...series,
5923
7255
  histogram: series.histogram.slice()
5924
7256
  });
5925
- var resetSeries = (series) => {
7257
+ var resetSeries2 = (series) => {
5926
7258
  series.started = 0;
5927
7259
  series.completed = 0;
5928
7260
  series.failed = 0;
@@ -5933,13 +7265,13 @@ var resetSeries = (series) => {
5933
7265
  series.invalidTiming = 0;
5934
7266
  series.histogram.fill(0);
5935
7267
  };
5936
- var snapshotAndReset = (table) => {
7268
+ var snapshotAndReset2 = (table) => {
5937
7269
  const snapshot = /* @__PURE__ */ new Map();
5938
7270
  for (const [functionHandle, byExecution] of table) {
5939
7271
  const copied = /* @__PURE__ */ new Map();
5940
7272
  for (const [executionHandle, series] of byExecution) {
5941
- if (seriesHasMarks(series)) copied.set(executionHandle, copySeries(series));
5942
- resetSeries(series);
7273
+ if (seriesHasMarks2(series)) copied.set(executionHandle, copySeries2(series));
7274
+ resetSeries2(series);
5943
7275
  }
5944
7276
  if (copied.size > 0) snapshot.set(functionHandle, copied);
5945
7277
  }
@@ -5954,10 +7286,11 @@ var declarationAccepted = (declaration) => {
5954
7286
  return true;
5955
7287
  };
5956
7288
  var createFunctionMetricsCollector = (options) => {
5957
- const limits = { ...defaultLimits(), ...options.limits };
5958
- const clock = options.clock ?? defaultClock();
7289
+ const limits = { ...defaultLimits2(), ...options.limits };
7290
+ const clock = options.clock ?? defaultClock2();
5959
7291
  const batchId = options.batchId ?? newFunctionMetricsBatchId;
5960
- const coverage = emptyCoverage2();
7292
+ const measurementFormat = options.sampledMeasurementFormat ? FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2 : FUNCTION_METRICS_MEASUREMENT_FORMAT2;
7293
+ const coverage = emptyCoverage4();
5961
7294
  const functions = [];
5962
7295
  const functionHandleByRuntimeId = /* @__PURE__ */ new Map();
5963
7296
  const executionKeys = [];
@@ -5971,7 +7304,7 @@ var createFunctionMetricsCollector = (options) => {
5971
7304
  let sealed = false;
5972
7305
  const reserve = (bytes) => {
5973
7306
  if (stateBytes > limits.maxStateBytes - bytes) {
5974
- note(coverage, "dropped_byte_budget");
7307
+ note2(coverage, "dropped_byte_budget");
5975
7308
  return false;
5976
7309
  }
5977
7310
  stateBytes += bytes;
@@ -5979,17 +7312,17 @@ var createFunctionMetricsCollector = (options) => {
5979
7312
  };
5980
7313
  const internDeclaration = (declaration) => {
5981
7314
  if (!declaration) {
5982
- note(coverage, "dropped_unexportable");
7315
+ note2(coverage, "dropped_unexportable");
5983
7316
  return void 0;
5984
7317
  }
5985
7318
  const existing = functionHandleByRuntimeId.get(declaration.runtime_id);
5986
7319
  if (existing !== void 0) return existing;
5987
7320
  if (!declarationAccepted(declaration)) {
5988
- note(coverage, "dropped_unexportable");
7321
+ note2(coverage, "dropped_unexportable");
5989
7322
  return void 0;
5990
7323
  }
5991
7324
  if (functions.length >= limits.maxFunctions) {
5992
- note(coverage, "dropped_unexportable");
7325
+ note2(coverage, "dropped_unexportable");
5993
7326
  return void 0;
5994
7327
  }
5995
7328
  if (!reserve(DECLARATION_BYTES + declaration.runtime_id.length)) return void 0;
@@ -5999,11 +7332,11 @@ var createFunctionMetricsCollector = (options) => {
5999
7332
  return handle;
6000
7333
  };
6001
7334
  const internExecutionKey = (key) => {
6002
- if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
7335
+ if (!key || !isCanonicalFunctionMetricsExecutionKey2(key)) return void 0;
6003
7336
  const existing = executionHandleByKey.get(key);
6004
7337
  if (existing !== void 0) return existing;
6005
7338
  if (executionKeys.length >= limits.maxExecutionTypes) {
6006
- note(coverage, "dropped_unexportable");
7339
+ note2(coverage, "dropped_unexportable");
6007
7340
  return void 0;
6008
7341
  }
6009
7342
  if (!reserve(key.length)) return void 0;
@@ -6026,10 +7359,10 @@ var createFunctionMetricsCollector = (options) => {
6026
7359
  const existing = byExecution.get(executionHandle);
6027
7360
  if (existing) return existing;
6028
7361
  if (activeSeries >= limits.maxActiveSeries) {
6029
- note(coverage, "dropped_active_series");
7362
+ note2(coverage, "dropped_active_series");
6030
7363
  return void 0;
6031
7364
  }
6032
- if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
7365
+ if (!reserve(SERIES_BYTES2 + HISTOGRAM_BYTES2)) return void 0;
6033
7366
  const series = {
6034
7367
  started: 0,
6035
7368
  completed: 0,
@@ -6039,15 +7372,15 @@ var createFunctionMetricsCollector = (options) => {
6039
7372
  sampleMinUs: null,
6040
7373
  sampleMaxUs: null,
6041
7374
  invalidTiming: 0,
6042
- histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
6043
- bytes: SERIES_BYTES + HISTOGRAM_BYTES
7375
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2),
7376
+ bytes: SERIES_BYTES2 + HISTOGRAM_BYTES2
6044
7377
  };
6045
7378
  byExecution.set(executionHandle, series);
6046
7379
  activeSeries += 1;
6047
7380
  return series;
6048
7381
  };
6049
7382
  const appendQueue = (entry) => {
6050
- if (discardedMarks(entry.series) === 0) {
7383
+ if (discardedMarks2(entry.series) === 0) {
6051
7384
  stateBytes -= entry.bytes;
6052
7385
  if (stateBytes < 0) stateBytes = 0;
6053
7386
  return;
@@ -6059,14 +7392,14 @@ var createFunctionMetricsCollector = (options) => {
6059
7392
  if (!dropped) break;
6060
7393
  stateBytes -= dropped.bytes;
6061
7394
  if (stateBytes < 0) stateBytes = 0;
6062
- note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
7395
+ note2(coverage, "dropped_queue_budget", discardedMarks2(dropped.series));
6063
7396
  }
6064
7397
  };
6065
7398
  const closeMinute = (minute, table) => {
6066
7399
  active.delete(minute);
6067
- activeSeries -= countSeries(table);
7400
+ activeSeries -= countSeries2(table);
6068
7401
  if (minute > lastClosedMinute) lastClosedMinute = minute;
6069
- appendQueue({ minute, series: table, bytes: tableBytes(table) });
7402
+ appendQueue({ minute, series: table, bytes: tableBytes2(table) });
6070
7403
  };
6071
7404
  const rotate = (currentMinute) => {
6072
7405
  for (const minute of [...active.keys()]) {
@@ -6084,7 +7417,7 @@ var createFunctionMetricsCollector = (options) => {
6084
7417
  };
6085
7418
  const snapshotActive = () => {
6086
7419
  for (const [minute, table] of active) {
6087
- appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
7420
+ appendQueue({ minute, series: snapshotAndReset2(table), bytes: 0 });
6088
7421
  }
6089
7422
  };
6090
7423
  const moveAllActive = () => {
@@ -6108,14 +7441,34 @@ var createFunctionMetricsCollector = (options) => {
6108
7441
  series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
6109
7442
  return true;
6110
7443
  };
7444
+ const rememberOutcome = (series, failed) => {
7445
+ const completed = series.completed + 1;
7446
+ const failures = series.failed + (failed ? 1 : 0);
7447
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
7448
+ series.completed = completed;
7449
+ series.failed = failures;
7450
+ return true;
7451
+ };
7452
+ const rememberInvalidTiming = (series, failed) => {
7453
+ const completed = series.completed + 1;
7454
+ const failures = series.failed + (failed ? 1 : 0);
7455
+ const invalidTiming = series.invalidTiming + 1;
7456
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures) || !Number.isSafeInteger(invalidTiming)) {
7457
+ return false;
7458
+ }
7459
+ series.completed = completed;
7460
+ series.failed = failures;
7461
+ series.invalidTiming = invalidTiming;
7462
+ return true;
7463
+ };
6111
7464
  const rememberCompletion = (series, startedNs, failed, endedNs) => {
6112
7465
  const completed = series.completed + 1;
6113
7466
  const failures = series.failed + (failed ? 1 : 0);
6114
7467
  if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
6115
7468
  const elapsed = endedNs - startedNs;
6116
7469
  const durationUs = Number(elapsed) / 1e3;
6117
- const placed = durationHistogramBucket(durationUs);
6118
- const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
7470
+ const placed = durationHistogramBucket2(durationUs);
7471
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS2;
6119
7472
  const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
6120
7473
  if (!sampled) {
6121
7474
  const invalidTiming = series.invalidTiming + 1;
@@ -6126,73 +7479,99 @@ var createFunctionMetricsCollector = (options) => {
6126
7479
  series.failed = failures;
6127
7480
  return true;
6128
7481
  };
6129
- const startCall = (functionHandle, executionHandle, startedNs) => {
7482
+ const startCall = (functionHandle, executionHandle, callOptions) => {
6130
7483
  if (sealed) {
6131
- note(coverage, "dropped_unexportable");
7484
+ note2(coverage, "dropped_unexportable");
6132
7485
  return void 0;
6133
7486
  }
6134
7487
  if (executionHandle === void 0) {
6135
- note(coverage, "skipped_unresolved_execution_type");
7488
+ note2(coverage, "skipped_unresolved_execution_type");
6136
7489
  return void 0;
6137
7490
  }
6138
- const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
7491
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
6139
7492
  rotateIfNeeded(minute);
6140
7493
  if (minute <= lastClosedMinute) {
6141
- note(coverage, "dropped_late_completion");
7494
+ note2(coverage, "dropped_late_completion");
6142
7495
  return void 0;
6143
7496
  }
6144
7497
  const series = ensureSeries(minute, functionHandle, executionHandle);
6145
7498
  if (!series) return void 0;
6146
7499
  const started = series.started + 1;
6147
7500
  if (!Number.isSafeInteger(started)) {
6148
- note(coverage, "dropped_unexportable");
7501
+ note2(coverage, "dropped_unexportable");
6149
7502
  return void 0;
6150
7503
  }
6151
7504
  series.started = started;
6152
- return startedNs ?? clock.monotonicNs();
7505
+ const measure = callOptions?.measure !== false;
7506
+ if (!measure) return { measure: false };
7507
+ if (callOptions && "startedNs" in callOptions) {
7508
+ return { measure: true, startedNs: callOptions.startedNs };
7509
+ }
7510
+ try {
7511
+ return { measure: true, startedNs: clock.monotonicNs() };
7512
+ } catch {
7513
+ return { measure: true };
7514
+ }
6153
7515
  };
6154
- const finishCall = (functionHandle, executionHandle, startedNs, failed, endedNs) => {
7516
+ const finishCall = (functionHandle, executionHandle, failed, timing) => {
6155
7517
  if (sealed) {
6156
- note(coverage, "dropped_late_completion");
7518
+ note2(coverage, "dropped_late_completion");
6157
7519
  return;
6158
7520
  }
6159
- const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
7521
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
6160
7522
  rotateIfNeeded(minute);
6161
7523
  if (minute <= lastClosedMinute && !active.has(minute)) {
6162
- note(coverage, "dropped_late_completion");
7524
+ note2(coverage, "dropped_late_completion");
6163
7525
  return;
6164
7526
  }
6165
7527
  const series = ensureSeries(minute, functionHandle, executionHandle);
6166
7528
  if (!series) return;
6167
- const remembered = rememberCompletion(
6168
- series,
6169
- startedNs,
6170
- failed,
6171
- endedNs ?? clock.monotonicNs()
6172
- );
6173
- if (!remembered) note(coverage, "dropped_unexportable");
7529
+ 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);
7530
+ if (!remembered) note2(coverage, "dropped_unexportable");
6174
7531
  };
6175
7532
  const beginCall = (input) => {
6176
7533
  const functionHandle = internDeclaration(input.declaration);
6177
7534
  if (functionHandle === void 0) return void 0;
6178
- if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey(input.executionKey)) {
7535
+ if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey2(input.executionKey)) {
6179
7536
  startCall(functionHandle, void 0);
6180
7537
  return void 0;
6181
7538
  }
6182
7539
  const executionHandle = internExecutionKey(input.executionKey);
6183
7540
  if (executionHandle === void 0) return void 0;
6184
- const startedNs = startCall(functionHandle, executionHandle);
6185
- if (startedNs === void 0) return void 0;
6186
- return { settled: false, functionHandle, executionHandle, startedNs };
7541
+ const started = startCall(functionHandle, executionHandle, {
7542
+ measure: input.measure,
7543
+ ..."startedNs" in input ? { startedNs: input.startedNs } : {}
7544
+ });
7545
+ if (!started) return void 0;
7546
+ return {
7547
+ settled: false,
7548
+ functionHandle,
7549
+ executionHandle,
7550
+ startedNs: started.startedNs,
7551
+ measure: started.measure
7552
+ };
6187
7553
  };
6188
7554
  const completeCall = (call, failed) => {
6189
7555
  if (!call || call.settled) return;
6190
7556
  call.settled = true;
6191
- finishCall(call.functionHandle, call.executionHandle, call.startedNs, failed);
7557
+ if (!call.measure) {
7558
+ finishCall(call.functionHandle, call.executionHandle, failed);
7559
+ return;
7560
+ }
7561
+ let endedNs;
7562
+ try {
7563
+ endedNs = clock.monotonicNs();
7564
+ } catch {
7565
+ endedNs = void 0;
7566
+ }
7567
+ finishCall(call.functionHandle, call.executionHandle, failed, {
7568
+ startedNs: call.startedNs,
7569
+ endedNs
7570
+ });
6192
7571
  };
6193
7572
  const drain = (drainOptions) => {
6194
7573
  if (!sealed) {
6195
- rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
7574
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3));
6196
7575
  if (drainOptions?.flushAll) snapshotActive();
6197
7576
  }
6198
7577
  const batches = functionMetricsBatchesFromQueue({
@@ -6206,7 +7585,8 @@ var createFunctionMetricsCollector = (options) => {
6206
7585
  functions,
6207
7586
  executionKeys,
6208
7587
  queued: queue,
6209
- coverage: { ...coverage, covered_bucket_starts: [] }
7588
+ coverage: { ...coverage, covered_bucket_starts: [] },
7589
+ measurementFormat
6210
7590
  });
6211
7591
  if (batches.length === 0) return [];
6212
7592
  for (const queued of queue) stateBytes -= queued.bytes;
@@ -6239,27 +7619,27 @@ var createFunctionMetricsCollector = (options) => {
6239
7619
  // src/function-metrics/encode-function-metrics-upload.ts
6240
7620
  import {
6241
7621
  encodeFunctionMetricsBatch,
6242
- encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
6243
- FUNCTION_METRICS_BUCKET_LATENESS_MS,
6244
- FUNCTION_METRICS_MAX_DECODED_BYTES,
6245
- FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS2,
6246
- parseFunctionMetricsBucketStart
7622
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync3,
7623
+ FUNCTION_METRICS_BUCKET_LATENESS_MS as FUNCTION_METRICS_BUCKET_LATENESS_MS2,
7624
+ FUNCTION_METRICS_MAX_DECODED_BYTES as FUNCTION_METRICS_MAX_DECODED_BYTES2,
7625
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS4,
7626
+ parseFunctionMetricsBucketStart as parseFunctionMetricsBucketStart2
6247
7627
  } from "@rasputin-ai/core";
6248
- var minuteMarks = (minute) => {
7628
+ var minuteMarks2 = (minute) => {
6249
7629
  const next = minute.started_calls + minute.completed_calls;
6250
7630
  return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
6251
7631
  };
6252
- var expiresAtMsFor = (batch, nowMs) => {
7632
+ var expiresAtMsFor2 = (batch, nowMs) => {
6253
7633
  let oldest;
6254
7634
  for (const start of batch.coverage.covered_bucket_starts) {
6255
- const bucket = parseFunctionMetricsBucketStart(start);
7635
+ const bucket = parseFunctionMetricsBucketStart2(start);
6256
7636
  if (bucket === void 0) continue;
6257
7637
  if (oldest === void 0 || bucket < oldest) oldest = bucket;
6258
7638
  }
6259
- if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
6260
- return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
7639
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
7640
+ return oldest + FUNCTION_METRICS_MINUTE_MS4 + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
6261
7641
  };
6262
- var zeroLossCoverage = (coverage) => ({
7642
+ var zeroLossCoverage2 = (coverage) => ({
6263
7643
  ...coverage,
6264
7644
  skipped_unresolved_execution_type: 0,
6265
7645
  dropped_active_series: 0,
@@ -6268,7 +7648,7 @@ var zeroLossCoverage = (coverage) => ({
6268
7648
  dropped_late_completion: 0,
6269
7649
  dropped_unexportable: 0
6270
7650
  });
6271
- var projectMinutes = (source, minutes, coverage, batchId) => {
7651
+ var projectMinutes2 = (source, minutes, coverage, batchId) => {
6272
7652
  const functionIndexes = /* @__PURE__ */ new Map();
6273
7653
  const typeIndexes = /* @__PURE__ */ new Map();
6274
7654
  const functions = [];
@@ -6307,7 +7687,7 @@ var projectMinutes = (source, minutes, coverage, batchId) => {
6307
7687
  coverage: { ...coverage, covered_bucket_starts: covered }
6308
7688
  };
6309
7689
  };
6310
- var withLoss = (batch, loss) => ({
7690
+ var withLoss2 = (batch, loss) => ({
6311
7691
  ...batch,
6312
7692
  coverage: {
6313
7693
  ...batch.coverage,
@@ -6315,37 +7695,37 @@ var withLoss = (batch, loss) => ({
6315
7695
  dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
6316
7696
  }
6317
7697
  });
6318
- var encodeOne = async (batch, nowMs, signal) => {
7698
+ var encodeOne2 = async (batch, nowMs, signal) => {
6319
7699
  const decodedBytes = encodeFunctionMetricsBatch(batch);
6320
- if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES) return void 0;
6321
- const encoded = await encodeJsonRequestBodyAsync2(decodedBytes, void 0, signal);
7700
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES2) return void 0;
7701
+ const encoded = await encodeJsonRequestBodyAsync3(decodedBytes, void 0, signal);
6322
7702
  return {
6323
7703
  decodedBytes,
6324
7704
  body: encoded.body,
6325
7705
  gzip: encoded.gzip,
6326
7706
  batchId: batch.batch_id,
6327
- expiresAtMs: expiresAtMsFor(batch, nowMs)
7707
+ expiresAtMs: expiresAtMsFor2(batch, nowMs)
6328
7708
  };
6329
7709
  };
6330
- var encodeFitting = async (batch, nowMs, signal) => {
6331
- const encoded = await encodeOne(batch, nowMs, signal);
7710
+ var encodeFitting2 = async (batch, nowMs, signal) => {
7711
+ const encoded = await encodeOne2(batch, nowMs, signal);
6332
7712
  if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
6333
7713
  if (batch.minutes.length <= 1) {
6334
7714
  return {
6335
7715
  uploads: [],
6336
- droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
7716
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks2(minute), 0)
6337
7717
  };
6338
7718
  }
6339
7719
  const mid = Math.ceil(batch.minutes.length / 2);
6340
- const first = projectMinutes(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
6341
- const rest = projectMinutes(
7720
+ const first = projectMinutes2(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
7721
+ const rest = projectMinutes2(
6342
7722
  batch,
6343
7723
  batch.minutes.slice(mid),
6344
- zeroLossCoverage(batch.coverage),
7724
+ zeroLossCoverage2(batch.coverage),
6345
7725
  newFunctionMetricsBatchId()
6346
7726
  );
6347
- const left = await encodeFitting(first, nowMs, signal);
6348
- const right = await encodeFitting(rest, nowMs, signal);
7727
+ const left = await encodeFitting2(first, nowMs, signal);
7728
+ const right = await encodeFitting2(rest, nowMs, signal);
6349
7729
  return {
6350
7730
  uploads: [...left.uploads, ...right.uploads],
6351
7731
  droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
@@ -6358,105 +7738,21 @@ var encodeFunctionMetricsUploads = async (batches, input) => {
6358
7738
  dropped_queue_budget: input.queueDrops ?? 0
6359
7739
  };
6360
7740
  for (const batch of batches) {
6361
- const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
7741
+ const fitted = await encodeFitting2(withLoss2(batch, extra), input.nowMs, input.signal);
6362
7742
  extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
6363
7743
  uploads.push(...fitted.uploads);
6364
7744
  }
6365
7745
  return uploads;
6366
7746
  };
6367
7747
 
6368
- // src/function-metrics/send-function-metrics-batch.ts
6369
- var REQUEST_TIMEOUT_MS2 = 2e4;
6370
- var abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
6371
- var retryAfterMs = (response) => {
6372
- const header = response.headers.get("retry-after");
6373
- if (!header) return null;
6374
- const seconds = Number(header);
6375
- if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
6376
- const date = Date.parse(header);
6377
- return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
6378
- };
6379
- var backoffMs2 = (attempt, random) => {
6380
- const base = Math.min(3e4, 500 * 2 ** attempt);
6381
- return Math.floor(base * (0.5 + random()));
6382
- };
6383
- var fetchUntilAborted = (fetchFn, url, init) => new Promise((resolve, reject) => {
6384
- const onAbort = () => reject(abortError());
6385
- init.signal.addEventListener("abort", onAbort, { once: true });
6386
- if (init.signal.aborted) {
6387
- init.signal.removeEventListener("abort", onAbort);
6388
- reject(abortError());
6389
- return;
6390
- }
6391
- void fetchFn(url, init).then(
6392
- (value) => {
6393
- init.signal.removeEventListener("abort", onAbort);
6394
- resolve(value);
6395
- },
6396
- (error) => {
6397
- init.signal.removeEventListener("abort", onAbort);
6398
- reject(error);
6399
- }
6400
- );
6401
- });
6402
- var sendFunctionMetricsBatch = async (input) => {
6403
- if (input.signal.aborted) return { outcome: "aborted" };
6404
- const nowMs = input.nowMs ?? Date.now;
6405
- if (input.upload.expiresAtMs <= nowMs())
6406
- return { outcome: "terminal", status: null, halt: false };
6407
- const request = new AbortController();
6408
- const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
6409
- timer.unref?.();
6410
- const onParentAbort = () => request.abort();
6411
- input.signal.addEventListener("abort", onParentAbort, { once: true });
6412
- if (input.signal.aborted) request.abort();
6413
- const headers = {
6414
- Authorization: `Bearer ${input.ingestToken}`,
6415
- "Content-Type": "application/json",
6416
- Accept: "application/json"
6417
- };
6418
- if (input.upload.gzip) headers["Content-Encoding"] = "gzip";
6419
- try {
6420
- const response = await fetchUntilAborted(input.fetch, input.url, {
6421
- method: "POST",
6422
- headers,
6423
- body: input.upload.body,
6424
- signal: request.signal
6425
- });
6426
- if (response.ok) return { outcome: "ok" };
6427
- if (response.status === 429) {
6428
- return {
6429
- outcome: "retry",
6430
- waitMs: retryAfterMs(response) ?? backoffMs2(input.attempt, input.random ?? Math.random)
6431
- };
6432
- }
6433
- if (response.status === 401 || response.status === 403 || response.status === 404) {
6434
- return { outcome: "terminal", status: response.status, halt: true };
6435
- }
6436
- if (response.status >= 400 && response.status < 500) {
6437
- return { outcome: "terminal", status: response.status, halt: false };
6438
- }
6439
- return {
6440
- outcome: "retry",
6441
- waitMs: backoffMs2(input.attempt, input.random ?? Math.random)
6442
- };
6443
- } catch {
6444
- if (input.signal.aborted) return { outcome: "aborted" };
6445
- return { outcome: "retry", waitMs: backoffMs2(input.attempt, input.random ?? Math.random) };
6446
- } finally {
6447
- clearTimeout(timer);
6448
- input.signal.removeEventListener("abort", onParentAbort);
6449
- }
6450
- };
6451
-
6452
7748
  // src/function-metrics/function-metrics-exporter.ts
6453
- var MAX_QUEUE_ITEMS = 32;
6454
- var MAX_QUEUE_BYTES = 4 * 1024 * 1024;
6455
- var DEFAULT_SCHEDULE_MS = 6e4;
6456
- var FLUSH_MS = 1e4;
6457
- var SHUTDOWN_FLUSH_MS = 2e3;
6458
- var MAX_ATTEMPTS = 8;
6459
- var sleep = (ms, signal) => new Promise((resolve) => {
7749
+ var MAX_QUEUE_ITEMS2 = 32;
7750
+ var MAX_QUEUE_BYTES2 = 4 * 1024 * 1024;
7751
+ var DEFAULT_SCHEDULE_MS2 = 6e4;
7752
+ var FLUSH_MS2 = 1e4;
7753
+ var SHUTDOWN_FLUSH_MS2 = 2e3;
7754
+ var MAX_ATTEMPTS2 = 8;
7755
+ var sleep2 = (ms, signal) => new Promise((resolve) => {
6460
7756
  if (ms <= 0 || signal.aborted) {
6461
7757
  resolve();
6462
7758
  return;
@@ -6477,7 +7773,7 @@ var sleep = (ms, signal) => new Promise((resolve) => {
6477
7773
  var createFunctionMetricsExporter = (input) => {
6478
7774
  const nowMs = input.nowMs ?? Date.now;
6479
7775
  const random = input.random ?? Math.random;
6480
- const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
7776
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS2;
6481
7777
  const queue = [];
6482
7778
  let queueBytes = 0;
6483
7779
  let queueDrops = 0;
@@ -6501,7 +7797,7 @@ var createFunctionMetricsExporter = (input) => {
6501
7797
  const enqueue = (upload) => {
6502
7798
  queue.push({ upload, attempt: 0 });
6503
7799
  queueBytes += upload.decodedBytes.byteLength;
6504
- while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
7800
+ while (queue.length > MAX_QUEUE_ITEMS2 || queueBytes > MAX_QUEUE_BYTES2) dropOldest();
6505
7801
  };
6506
7802
  const drainAndEnqueue = async (flushAll2) => {
6507
7803
  if (halted || stopped) return;
@@ -6536,7 +7832,7 @@ var createFunctionMetricsExporter = (input) => {
6536
7832
  dropped += 1;
6537
7833
  continue;
6538
7834
  }
6539
- if (item.attempt >= MAX_ATTEMPTS) {
7835
+ if (item.attempt >= MAX_ATTEMPTS2) {
6540
7836
  queue.shift();
6541
7837
  queueBytes -= item.upload.decodedBytes.byteLength;
6542
7838
  dropped += 1;
@@ -6570,7 +7866,7 @@ var createFunctionMetricsExporter = (input) => {
6570
7866
  continue;
6571
7867
  }
6572
7868
  item.attempt += 1;
6573
- await sleep(result.waitMs, signal);
7869
+ await sleep2(result.waitMs, signal);
6574
7870
  }
6575
7871
  };
6576
7872
  const abortCurrent = () => {
@@ -6646,7 +7942,7 @@ var createFunctionMetricsExporter = (input) => {
6646
7942
  const flush = async (timeoutMs) => {
6647
7943
  if (closed || halted) return;
6648
7944
  const abort = new AbortController();
6649
- const budget = timeoutMs ?? FLUSH_MS;
7945
+ const budget = timeoutMs ?? FLUSH_MS2;
6650
7946
  const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
6651
7947
  try {
6652
7948
  await runWork(abort.signal, async (signal) => {
@@ -6667,7 +7963,7 @@ var createFunctionMetricsExporter = (input) => {
6667
7963
  if (timer) clearTimeout(timer);
6668
7964
  timer = void 0;
6669
7965
  const abort = new AbortController();
6670
- const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
7966
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS2);
6671
7967
  abortCurrent();
6672
7968
  try {
6673
7969
  await runWork(abort.signal, async (signal) => {
@@ -6700,29 +7996,31 @@ var installFunctionMetricDeclarationSink = () => {
6700
7996
  };
6701
7997
 
6702
7998
  // src/function-metrics/bind-function-metrics.ts
6703
- var SLOT = Symbol.for("rasputin.functionMetrics.runtime.v1");
6704
- var releasedHandles = /* @__PURE__ */ new WeakSet();
6705
- var isRuntime = (value) => {
7999
+ var SLOT2 = Symbol.for("rasputin.functionMetrics.runtime.v1");
8000
+ var releasedHandles2 = /* @__PURE__ */ new WeakSet();
8001
+ var isRuntime2 = (value) => {
6706
8002
  if (typeof value !== "object" || value === null) return false;
6707
8003
  return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
6708
8004
  };
6709
- var bindingIdentity = (input) => `${input.ingestToken}
8005
+ var bindingIdentity2 = (input) => `${input.ingestToken}
6710
8006
  ${input.url}
6711
8007
  ${input.environment}
6712
- ${input.release}`;
6713
- var warnIncompatible = (runtime) => {
8008
+ ${input.release}
8009
+ ${input.sampledMeasurementFormat ? "1" : "0"}`;
8010
+ var warnIncompatible2 = (runtime) => {
6714
8011
  if (runtime.warnedMismatch) return;
6715
8012
  runtime.warnedMismatch = true;
6716
8013
  console.warn(
6717
8014
  "[rasputin] function metrics already running with a different configuration; this client will not collect function metrics"
6718
8015
  );
6719
8016
  };
6720
- var createBindings = (input) => {
8017
+ var createBindings2 = (input) => {
6721
8018
  installFunctionMetricDeclarationSink();
6722
8019
  const collector = createFunctionMetricsCollector({
6723
8020
  environment: input.environment,
6724
- producerId: randomUUID2(),
6725
- release: input.release
8021
+ producerId: randomUUID4(),
8022
+ release: input.release,
8023
+ sampledMeasurementFormat: input.sampledMeasurementFormat
6726
8024
  });
6727
8025
  return {
6728
8026
  collector,
@@ -6730,7 +8028,7 @@ var createBindings = (input) => {
6730
8028
  collector,
6731
8029
  url: input.url,
6732
8030
  ingestToken: input.ingestToken,
6733
- fetch: input.fetch ?? defaultIngestFetch2()
8031
+ fetch: input.fetch ?? defaultIngestFetch3()
6734
8032
  })
6735
8033
  };
6736
8034
  };
@@ -6739,30 +8037,33 @@ var bindFunctionMetrics = (input) => {
6739
8037
  if (input.options?.enabled === false) return void 0;
6740
8038
  const release = input.release.trim().toLowerCase();
6741
8039
  if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
6742
- const url = resolveEndpointUrls3(input.apiUrl).functionMetricsUrl;
6743
- const key = bindingIdentity({
8040
+ const url = resolveEndpointUrls4(input.apiUrl).functionMetricsUrl;
8041
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
8042
+ const key = bindingIdentity2({
6744
8043
  ingestToken: input.ingestToken,
6745
8044
  url,
6746
8045
  environment: input.environment,
6747
- release
8046
+ release,
8047
+ sampledMeasurementFormat
6748
8048
  });
6749
- const existing = Reflect.get(globalThis, SLOT);
6750
- if (isRuntime(existing)) {
8049
+ const existing = Reflect.get(globalThis, SLOT2);
8050
+ if (isRuntime2(existing)) {
6751
8051
  if (existing.identity !== key) {
6752
- warnIncompatible(existing);
8052
+ warnIncompatible2(existing);
6753
8053
  return void 0;
6754
8054
  }
6755
8055
  existing.refs += 1;
6756
8056
  return { collector: existing.collector, exporter: existing.exporter };
6757
8057
  }
6758
- const bindings2 = createBindings({
8058
+ const bindings2 = createBindings2({
6759
8059
  release,
6760
8060
  ingestToken: input.ingestToken,
6761
8061
  url,
6762
8062
  environment: input.environment,
6763
- fetch: input.fetch
8063
+ fetch: input.fetch,
8064
+ sampledMeasurementFormat
6764
8065
  });
6765
- Reflect.set(globalThis, SLOT, {
8066
+ Reflect.set(globalThis, SLOT2, {
6766
8067
  ...bindings2,
6767
8068
  refs: 1,
6768
8069
  identity: key,
@@ -6771,13 +8072,13 @@ var bindFunctionMetrics = (input) => {
6771
8072
  return bindings2;
6772
8073
  };
6773
8074
  var releaseFunctionMetricsBindings = async (bindings2) => {
6774
- if (!bindings2 || releasedHandles.has(bindings2)) return;
6775
- releasedHandles.add(bindings2);
6776
- const existing = Reflect.get(globalThis, SLOT);
6777
- if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
8075
+ if (!bindings2 || releasedHandles2.has(bindings2)) return;
8076
+ releasedHandles2.add(bindings2);
8077
+ const existing = Reflect.get(globalThis, SLOT2);
8078
+ if (isRuntime2(existing) && existing.exporter === bindings2.exporter) {
6778
8079
  existing.refs -= 1;
6779
8080
  if (existing.refs > 0) return;
6780
- Reflect.deleteProperty(globalThis, SLOT);
8081
+ Reflect.deleteProperty(globalThis, SLOT2);
6781
8082
  }
6782
8083
  await bindings2.exporter.close();
6783
8084
  };
@@ -6917,13 +8218,84 @@ var installGlobalHandlers = (client, options = {}) => {
6917
8218
  if (registered.length === 0) uninstallProcess?.();
6918
8219
  };
6919
8220
  };
8221
+
8222
+ // src/runtime-timing/dynamic-duration-sampling.ts
8223
+ var DYNAMIC_DURATION_SAMPLE_STAGES = [
8224
+ { below: 10, divisor: 1 },
8225
+ { below: 30, divisor: 2 },
8226
+ { below: 100, divisor: 3 },
8227
+ { below: 500, divisor: 11 },
8228
+ { below: 1e3, divisor: 23 },
8229
+ { below: 5e3, divisor: 53 }
8230
+ ];
8231
+ var MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS = 4096;
8232
+ var DYNAMIC_DURATION_SAMPLE_TAIL_AFTER = 5e3;
8233
+ var DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR = 100;
8234
+ var DYNAMIC_DURATION_SAMPLE_RESET_MS = 60 * 60 * 1e3;
8235
+ var EXECUTION_DURATION_SAMPLE_PREFIX = "\0execution-metrics\0";
8236
+ var dynamicDurationSampleDivisor = (index) => {
8237
+ for (const stage of DYNAMIC_DURATION_SAMPLE_STAGES) {
8238
+ if (index < stage.below) return stage.divisor;
8239
+ }
8240
+ return DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8241
+ };
8242
+ var shouldSampleDynamicDuration = (index) => {
8243
+ return index % dynamicDurationSampleDivisor(index) === 0;
8244
+ };
8245
+ var nextDurationSampleIndex = (index) => {
8246
+ if (index < Number.MAX_SAFE_INTEGER) return index + 1;
8247
+ return DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + (index - DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + 1) % DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8248
+ };
8249
+ var createDynamicDurationSampleBuckets = (options) => {
8250
+ const functionBuckets = /* @__PURE__ */ new Map();
8251
+ const executionBuckets = /* @__PURE__ */ new Map();
8252
+ const maxBuckets = options.maxBuckets ?? MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS;
8253
+ const resetMs = options.resetMs ?? DYNAMIC_DURATION_SAMPLE_RESET_MS;
8254
+ let lastResetAtMs = options.nowMs();
8255
+ let stopped = false;
8256
+ const reset = () => {
8257
+ functionBuckets.clear();
8258
+ executionBuckets.clear();
8259
+ lastResetAtMs = options.nowMs();
8260
+ };
8261
+ const resetTimer = setInterval(reset, resetMs);
8262
+ resetTimer.unref?.();
8263
+ const takeKey = (buckets, key) => {
8264
+ if (options.nowMs() - lastResetAtMs >= resetMs) reset();
8265
+ const existing = buckets.get(key);
8266
+ if (existing !== void 0) {
8267
+ buckets.delete(key);
8268
+ buckets.set(key, nextDurationSampleIndex(existing));
8269
+ return shouldSampleDynamicDuration(existing);
8270
+ }
8271
+ while (buckets.size >= maxBuckets) {
8272
+ const oldest = buckets.keys().next().value;
8273
+ if (oldest === void 0) break;
8274
+ buckets.delete(oldest);
8275
+ }
8276
+ buckets.set(key, nextDurationSampleIndex(0));
8277
+ return shouldSampleDynamicDuration(0);
8278
+ };
8279
+ return {
8280
+ take: (executionType, callerFunctionId, functionId) => takeKey(functionBuckets, `${executionType}\0${callerFunctionId}\0${functionId}`),
8281
+ takeExecution: (executionType) => takeKey(executionBuckets, `${EXECUTION_DURATION_SAMPLE_PREFIX}${executionType}`),
8282
+ stop: () => {
8283
+ if (stopped) return;
8284
+ stopped = true;
8285
+ clearInterval(resetTimer);
8286
+ }
8287
+ };
8288
+ };
6920
8289
  export {
6921
8290
  bindAdaptiveRecorder,
8291
+ bindExecutionMetrics,
6922
8292
  bindFunctionMetrics,
8293
+ createDynamicDurationSampleBuckets,
6923
8294
  createExecutionRecorder,
6924
8295
  inertErrorObservation,
6925
8296
  installAutomaticExecutionRuntime,
6926
8297
  installGlobalHandlers,
8298
+ releaseExecutionMetricsBindings,
6927
8299
  releaseFunctionMetricsBindings,
6928
8300
  scheduleInstrumentationManifestUpload
6929
8301
  };