@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/index.js CHANGED
@@ -678,6 +678,1018 @@ var scheduleInstrumentationManifestUpload = (options) => {
678
678
  };
679
679
  };
680
680
 
681
+ // src/execution-metrics/bind-execution-metrics.ts
682
+ import { randomUUID as randomUUID2 } from "node:crypto";
683
+ import {
684
+ defaultIngestFetch,
685
+ resolveEndpointUrls as resolveEndpointUrls2
686
+ } from "@rasputin-ai/core";
687
+
688
+ // src/execution-metrics/execution-metrics-collector.ts
689
+ import {
690
+ durationHistogramBucket,
691
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
692
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES,
693
+ FUNCTION_METRICS_MAX_BUFFERED_MS,
694
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES,
695
+ FUNCTION_METRICS_MAX_MINUTE_ROWS,
696
+ FUNCTION_METRICS_MAX_STATE_BYTES,
697
+ FUNCTION_METRICS_MEASUREMENT_FORMAT,
698
+ FUNCTION_METRICS_MINUTE_MS,
699
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT,
700
+ isCanonicalFunctionMetricsExecutionKey
701
+ } from "@rasputin-ai/core";
702
+
703
+ // src/execution-metrics/execution-metrics-batches.ts
704
+ import { randomUUID } from "node:crypto";
705
+ import {
706
+ EXECUTION_METRICS_SCHEMA_VERSION
707
+ } from "@rasputin-ai/core";
708
+ var emptyCoverage = (buckets) => ({
709
+ covered_bucket_starts: buckets,
710
+ skipped_unresolved_execution_type: 0,
711
+ dropped_active_series: 0,
712
+ dropped_byte_budget: 0,
713
+ dropped_queue_budget: 0,
714
+ dropped_late_completion: 0,
715
+ dropped_unexportable: 0
716
+ });
717
+ var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
718
+ var sparseHistogram = (histogram) => {
719
+ const cells = [];
720
+ for (let index = 0; index < histogram.length; index += 1) {
721
+ const count = histogram[index] ?? 0;
722
+ if (count > 0) cells.push([index, count]);
723
+ }
724
+ return cells;
725
+ };
726
+ var toMinute = (unit, executionTypeIndex) => ({
727
+ execution_type_index: executionTypeIndex,
728
+ bucket_start: bucketStart(unit.minute),
729
+ started_executions: unit.series.started,
730
+ completed_executions: unit.series.completed,
731
+ failed_executions: unit.series.failed,
732
+ duration_sample_count: unit.series.sampleCount,
733
+ duration_sample_sum_us: unit.series.sampleSumUs,
734
+ duration_sample_min_us: unit.series.sampleMinUs,
735
+ duration_sample_max_us: unit.series.sampleMaxUs,
736
+ duration_histogram: sparseHistogram(unit.series.histogram),
737
+ invalid_timing_count: unit.series.invalidTiming
738
+ });
739
+ var unitsFromQueue = (queued) => {
740
+ const units = [];
741
+ for (const queuedMinute of queued) {
742
+ for (const [executionHandle, series] of queuedMinute.series) {
743
+ units.push({ minute: queuedMinute.minute, executionHandle, series });
744
+ }
745
+ }
746
+ units.sort((left, right) => {
747
+ if (left.minute !== right.minute) return left.minute - right.minute;
748
+ return left.executionHandle - right.executionHandle;
749
+ });
750
+ return units;
751
+ };
752
+ var unitMarks = (series) => {
753
+ const next = series.started + series.completed;
754
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
755
+ };
756
+ var chunkUnits = (units, maxExecutionTypes, maxMinuteRows) => {
757
+ const chunks = [];
758
+ let current = [];
759
+ let executionTypes = /* @__PURE__ */ new Set();
760
+ let droppedUnexportable = 0;
761
+ const flush = () => {
762
+ if (current.length === 0) return;
763
+ chunks.push(current);
764
+ current = [];
765
+ executionTypes = /* @__PURE__ */ new Set();
766
+ };
767
+ for (const unit of units) {
768
+ if (maxMinuteRows < 1) {
769
+ droppedUnexportable += unitMarks(unit.series);
770
+ continue;
771
+ }
772
+ const nextTypes = executionTypes.has(unit.executionHandle) ? executionTypes.size : executionTypes.size + 1;
773
+ if (current.length >= maxMinuteRows || nextTypes > maxExecutionTypes) flush();
774
+ current.push(unit);
775
+ executionTypes.add(unit.executionHandle);
776
+ }
777
+ flush();
778
+ return { chunks, droppedUnexportable };
779
+ };
780
+ var batchForChunk = (draft, units, coverage) => {
781
+ const executionIndexes = /* @__PURE__ */ new Map();
782
+ const executionTypes = [];
783
+ const minutes = [];
784
+ for (const unit of units) {
785
+ let executionTypeIndex = executionIndexes.get(unit.executionHandle);
786
+ if (executionTypeIndex === void 0) {
787
+ const executionKey = draft.executionKeys[unit.executionHandle];
788
+ if (!executionKey) continue;
789
+ executionTypeIndex = executionTypes.length;
790
+ executionIndexes.set(unit.executionHandle, executionTypeIndex);
791
+ executionTypes.push({ execution_key: executionKey });
792
+ }
793
+ minutes.push(toMinute(unit, executionTypeIndex));
794
+ }
795
+ const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
796
+ return {
797
+ schema_version: EXECUTION_METRICS_SCHEMA_VERSION,
798
+ measurement_format: draft.measurementFormat,
799
+ producer_id: draft.producerId,
800
+ batch_id: draft.batchId(),
801
+ environment: draft.environment,
802
+ release: draft.release,
803
+ execution_types: executionTypes,
804
+ minutes,
805
+ coverage: { ...coverage, covered_bucket_starts: covered }
806
+ };
807
+ };
808
+ var lossOnlyBatch = (draft, coverage) => ({
809
+ schema_version: EXECUTION_METRICS_SCHEMA_VERSION,
810
+ measurement_format: draft.measurementFormat,
811
+ producer_id: draft.producerId,
812
+ batch_id: draft.batchId(),
813
+ environment: draft.environment,
814
+ release: draft.release,
815
+ execution_types: [],
816
+ minutes: [],
817
+ coverage
818
+ });
819
+ var executionMetricsBatchesFromQueue = (draft) => {
820
+ const units = unitsFromQueue(draft.queued);
821
+ const { chunks, droppedUnexportable } = chunkUnits(
822
+ units,
823
+ draft.maxExecutionTypes,
824
+ draft.maxMinuteRows
825
+ );
826
+ const coverage = {
827
+ ...draft.coverage,
828
+ dropped_unexportable: draft.coverage.dropped_unexportable + droppedUnexportable
829
+ };
830
+ if (chunks.length === 0) {
831
+ const hasLoss = Object.entries(coverage).some(([key, value]) => {
832
+ return key !== "covered_bucket_starts" && typeof value === "number" && value > 0;
833
+ });
834
+ return hasLoss ? [lossOnlyBatch(draft, coverage)] : [];
835
+ }
836
+ return chunks.map(
837
+ (chunk, index) => batchForChunk(draft, chunk, index === 0 ? coverage : emptyCoverage([]))
838
+ );
839
+ };
840
+ var newExecutionMetricsBatchId = () => randomUUID();
841
+
842
+ // src/execution-metrics/execution-metrics-collector.ts
843
+ var SERIES_BYTES = 256;
844
+ var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
845
+ var MAX_ELAPSED_NS = BigInt(Number.MAX_SAFE_INTEGER);
846
+ var defaultLimits = () => ({
847
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES,
848
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES,
849
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS / FUNCTION_METRICS_MINUTE_MS,
850
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
851
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
852
+ });
853
+ var defaultClock = () => ({
854
+ monotonicNs: () => process.hrtime.bigint(),
855
+ wallTimeMs: () => Date.now()
856
+ });
857
+ var emptyCoverage2 = () => ({
858
+ covered_bucket_starts: [],
859
+ skipped_unresolved_execution_type: 0,
860
+ dropped_active_series: 0,
861
+ dropped_byte_budget: 0,
862
+ dropped_queue_budget: 0,
863
+ dropped_late_completion: 0,
864
+ dropped_unexportable: 0
865
+ });
866
+ var note = (coverage, counter, amount = 1) => {
867
+ const next = coverage[counter] + amount;
868
+ coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
869
+ };
870
+ var countSeries = (table) => table.size;
871
+ var tableBytes = (table) => {
872
+ let bytes = 0;
873
+ for (const series of table.values()) bytes += series.bytes;
874
+ return bytes;
875
+ };
876
+ var discardedMarks = (table) => {
877
+ let marks = 0;
878
+ for (const series of table.values()) {
879
+ const next = marks + series.started + series.completed;
880
+ marks = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
881
+ }
882
+ return marks;
883
+ };
884
+ var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
885
+ var copySeries = (series) => ({
886
+ ...series,
887
+ histogram: series.histogram.slice()
888
+ });
889
+ var resetSeries = (series) => {
890
+ series.started = 0;
891
+ series.completed = 0;
892
+ series.failed = 0;
893
+ series.sampleCount = 0;
894
+ series.sampleSumUs = 0;
895
+ series.sampleMinUs = null;
896
+ series.sampleMaxUs = null;
897
+ series.invalidTiming = 0;
898
+ series.histogram.fill(0);
899
+ };
900
+ var snapshotAndReset = (table) => {
901
+ const snapshot = /* @__PURE__ */ new Map();
902
+ for (const [executionHandle, series] of table) {
903
+ if (seriesHasMarks(series)) snapshot.set(executionHandle, copySeries(series));
904
+ resetSeries(series);
905
+ }
906
+ return snapshot;
907
+ };
908
+ var createExecutionMetricsCollector = (options) => {
909
+ const limits = { ...defaultLimits(), ...options.limits };
910
+ const clock = options.clock ?? defaultClock();
911
+ const batchId = options.batchId ?? newExecutionMetricsBatchId;
912
+ const measurementFormat = options.sampledMeasurementFormat ? FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT : FUNCTION_METRICS_MEASUREMENT_FORMAT;
913
+ const coverage = emptyCoverage2();
914
+ const executionKeys = [];
915
+ const executionHandleByKey = /* @__PURE__ */ new Map();
916
+ const active = /* @__PURE__ */ new Map();
917
+ const queue = [];
918
+ let lastClosedMinute = Number.NEGATIVE_INFINITY;
919
+ let lastSeenMinute = Number.NEGATIVE_INFINITY;
920
+ let stateBytes = 0;
921
+ let activeSeries = 0;
922
+ let sealed = false;
923
+ const reserve = (bytes) => {
924
+ if (stateBytes > limits.maxStateBytes - bytes) {
925
+ note(coverage, "dropped_byte_budget");
926
+ return false;
927
+ }
928
+ stateBytes += bytes;
929
+ return true;
930
+ };
931
+ const internExecutionKey = (key) => {
932
+ if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
933
+ const existing = executionHandleByKey.get(key);
934
+ if (existing !== void 0) return existing;
935
+ if (executionKeys.length >= limits.maxExecutionTypes) {
936
+ note(coverage, "dropped_unexportable");
937
+ return void 0;
938
+ }
939
+ if (!reserve(key.length)) return void 0;
940
+ const handle = executionKeys.length;
941
+ executionKeys.push(key);
942
+ executionHandleByKey.set(key, handle);
943
+ return handle;
944
+ };
945
+ const ensureSeries = (minute, executionHandle) => {
946
+ let byExecution = active.get(minute);
947
+ if (!byExecution) {
948
+ byExecution = /* @__PURE__ */ new Map();
949
+ active.set(minute, byExecution);
950
+ }
951
+ const existing = byExecution.get(executionHandle);
952
+ if (existing) return existing;
953
+ if (activeSeries >= limits.maxActiveSeries) {
954
+ note(coverage, "dropped_active_series");
955
+ return void 0;
956
+ }
957
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
958
+ const series = {
959
+ started: 0,
960
+ completed: 0,
961
+ failed: 0,
962
+ sampleCount: 0,
963
+ sampleSumUs: 0,
964
+ sampleMinUs: null,
965
+ sampleMaxUs: null,
966
+ invalidTiming: 0,
967
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
968
+ bytes: SERIES_BYTES + HISTOGRAM_BYTES
969
+ };
970
+ byExecution.set(executionHandle, series);
971
+ activeSeries += 1;
972
+ return series;
973
+ };
974
+ const appendQueue = (entry) => {
975
+ if (discardedMarks(entry.series) === 0) {
976
+ stateBytes -= entry.bytes;
977
+ if (stateBytes < 0) stateBytes = 0;
978
+ return;
979
+ }
980
+ queue.push(entry);
981
+ queue.sort((left, right) => left.minute - right.minute);
982
+ while (queue.length > limits.maxQueuedMinutes) {
983
+ const dropped = queue.shift();
984
+ if (!dropped) break;
985
+ stateBytes -= dropped.bytes;
986
+ if (stateBytes < 0) stateBytes = 0;
987
+ note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
988
+ }
989
+ };
990
+ const closeMinute = (minute, table) => {
991
+ active.delete(minute);
992
+ activeSeries -= countSeries(table);
993
+ if (minute > lastClosedMinute) lastClosedMinute = minute;
994
+ appendQueue({ minute, series: table, bytes: tableBytes(table) });
995
+ };
996
+ const rotate = (currentMinute2) => {
997
+ for (const minute of [...active.keys()]) {
998
+ if (minute >= currentMinute2) continue;
999
+ const table = active.get(minute);
1000
+ if (table) closeMinute(minute, table);
1001
+ }
1002
+ const closedThrough = currentMinute2 - 1;
1003
+ if (closedThrough > lastClosedMinute) lastClosedMinute = closedThrough;
1004
+ };
1005
+ const rotateIfNeeded = (minute) => {
1006
+ if (minute === lastSeenMinute) return;
1007
+ lastSeenMinute = minute;
1008
+ rotate(minute);
1009
+ };
1010
+ const snapshotActive = () => {
1011
+ for (const [minute, table] of active) {
1012
+ appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
1013
+ }
1014
+ };
1015
+ const moveAllActive = () => {
1016
+ for (const minute of [...active.keys()]) {
1017
+ const table = active.get(minute);
1018
+ if (table) closeMinute(minute, table);
1019
+ }
1020
+ };
1021
+ const currentMinute = (allowClosed) => {
1022
+ if (sealed) {
1023
+ note(coverage, "dropped_unexportable");
1024
+ return void 0;
1025
+ }
1026
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
1027
+ rotateIfNeeded(minute);
1028
+ if (minute <= lastClosedMinute && (!allowClosed || !active.has(minute))) {
1029
+ note(coverage, "dropped_late_completion");
1030
+ return void 0;
1031
+ }
1032
+ return minute;
1033
+ };
1034
+ const rememberSample = (series, durationUs, bucket) => {
1035
+ const sampleCount = series.sampleCount + 1;
1036
+ const sampleSumUs = series.sampleSumUs + durationUs;
1037
+ const previous = series.histogram[bucket];
1038
+ if (previous === void 0) return false;
1039
+ const cell = previous + 1;
1040
+ const sumFits = Number.isFinite(sampleSumUs) && sampleSumUs >= 0 && sampleSumUs <= Number.MAX_SAFE_INTEGER;
1041
+ if (!Number.isSafeInteger(sampleCount) || !Number.isSafeInteger(cell) || !sumFits) return false;
1042
+ series.histogram[bucket] = cell;
1043
+ series.sampleCount = sampleCount;
1044
+ series.sampleSumUs = sampleSumUs;
1045
+ series.sampleMinUs = series.sampleMinUs === null ? durationUs : Math.min(series.sampleMinUs, durationUs);
1046
+ series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
1047
+ return true;
1048
+ };
1049
+ const rememberStart = (handle) => {
1050
+ const minute = currentMinute(false);
1051
+ if (minute === void 0) return false;
1052
+ const series = ensureSeries(minute, handle);
1053
+ if (!series) return false;
1054
+ const started = series.started + 1;
1055
+ if (!Number.isSafeInteger(started)) {
1056
+ note(coverage, "dropped_unexportable");
1057
+ return false;
1058
+ }
1059
+ series.started = started;
1060
+ return true;
1061
+ };
1062
+ const bindIdentity = (state, key) => {
1063
+ if (state.finished || state.dropped || state.handle !== void 0) return;
1064
+ if (!key) return;
1065
+ const handle = internExecutionKey(key);
1066
+ if (handle === void 0) {
1067
+ state.dropped = true;
1068
+ return;
1069
+ }
1070
+ state.handle = handle;
1071
+ if (state.started) return;
1072
+ if (rememberStart(handle)) state.started = true;
1073
+ };
1074
+ const finishExecution = (state, input) => {
1075
+ if (state.finished) return;
1076
+ state.finished = true;
1077
+ if (state.dropped) return;
1078
+ if (state.handle === void 0) {
1079
+ note(coverage, "skipped_unresolved_execution_type");
1080
+ return;
1081
+ }
1082
+ if (!state.started) {
1083
+ if (!rememberStart(state.handle)) return;
1084
+ state.started = true;
1085
+ }
1086
+ const minute = currentMinute(true);
1087
+ if (minute === void 0) return;
1088
+ const series = ensureSeries(minute, state.handle);
1089
+ if (!series) return;
1090
+ const completed = series.completed + 1;
1091
+ const failed = series.failed + (input.failed ? 1 : 0);
1092
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failed)) {
1093
+ note(coverage, "dropped_unexportable");
1094
+ return;
1095
+ }
1096
+ if (input.measure) {
1097
+ if (input.startedNs === void 0 || input.endedNs === void 0) {
1098
+ const invalidTiming = series.invalidTiming + 1;
1099
+ if (!Number.isSafeInteger(invalidTiming)) {
1100
+ note(coverage, "dropped_unexportable");
1101
+ return;
1102
+ }
1103
+ series.invalidTiming = invalidTiming;
1104
+ } else {
1105
+ const elapsed = input.endedNs - input.startedNs;
1106
+ const durationUs = Number(elapsed) / 1e3;
1107
+ const placed = durationHistogramBucket(durationUs);
1108
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
1109
+ const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
1110
+ if (!sampled) {
1111
+ const invalidTiming = series.invalidTiming + 1;
1112
+ if (!Number.isSafeInteger(invalidTiming)) {
1113
+ note(coverage, "dropped_unexportable");
1114
+ return;
1115
+ }
1116
+ series.invalidTiming = invalidTiming;
1117
+ }
1118
+ }
1119
+ }
1120
+ series.completed = completed;
1121
+ series.failed = failed;
1122
+ };
1123
+ const drain = (drainOptions) => {
1124
+ if (!sealed) {
1125
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
1126
+ if (drainOptions?.flushAll) snapshotActive();
1127
+ }
1128
+ const batches = executionMetricsBatchesFromQueue({
1129
+ environment: options.environment,
1130
+ release: options.release,
1131
+ producerId: options.producerId,
1132
+ batchId,
1133
+ maxExecutionTypes: limits.maxExecutionTypes,
1134
+ maxMinuteRows: limits.maxMinuteRows,
1135
+ executionKeys,
1136
+ queued: queue,
1137
+ coverage: { ...coverage, covered_bucket_starts: [] },
1138
+ measurementFormat
1139
+ });
1140
+ if (batches.length === 0) return [];
1141
+ for (const queued of queue) stateBytes -= queued.bytes;
1142
+ if (stateBytes < 0) stateBytes = 0;
1143
+ queue.length = 0;
1144
+ coverage.skipped_unresolved_execution_type = 0;
1145
+ coverage.dropped_active_series = 0;
1146
+ coverage.dropped_byte_budget = 0;
1147
+ coverage.dropped_queue_budget = 0;
1148
+ coverage.dropped_late_completion = 0;
1149
+ coverage.dropped_unexportable = 0;
1150
+ return batches;
1151
+ };
1152
+ return {
1153
+ createState: () => ({
1154
+ handle: void 0,
1155
+ started: false,
1156
+ finished: false,
1157
+ dropped: false
1158
+ }),
1159
+ bindIdentity,
1160
+ finishExecution,
1161
+ drain,
1162
+ seal: () => {
1163
+ if (sealed) return;
1164
+ sealed = true;
1165
+ moveAllActive();
1166
+ }
1167
+ };
1168
+ };
1169
+
1170
+ // src/function-metrics/send-function-metrics-batch.ts
1171
+ var REQUEST_TIMEOUT_MS = 2e4;
1172
+ var abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
1173
+ var retryAfterMs = (response) => {
1174
+ const header = response.headers.get("retry-after");
1175
+ if (!header) return null;
1176
+ const seconds = Number(header);
1177
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
1178
+ const date = Date.parse(header);
1179
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
1180
+ };
1181
+ var backoffMs = (attempt, random) => {
1182
+ const base = Math.min(3e4, 500 * 2 ** attempt);
1183
+ return Math.floor(base * (0.5 + random()));
1184
+ };
1185
+ var fetchUntilAborted = (fetchFn, url, init) => new Promise((resolve, reject) => {
1186
+ const onAbort = () => reject(abortError());
1187
+ init.signal.addEventListener("abort", onAbort, { once: true });
1188
+ if (init.signal.aborted) {
1189
+ init.signal.removeEventListener("abort", onAbort);
1190
+ reject(abortError());
1191
+ return;
1192
+ }
1193
+ void fetchFn(url, init).then(
1194
+ (value) => {
1195
+ init.signal.removeEventListener("abort", onAbort);
1196
+ resolve(value);
1197
+ },
1198
+ (error) => {
1199
+ init.signal.removeEventListener("abort", onAbort);
1200
+ reject(error);
1201
+ }
1202
+ );
1203
+ });
1204
+ var sendFunctionMetricsBatch = async (input) => {
1205
+ if (input.signal.aborted) return { outcome: "aborted" };
1206
+ const nowMs = input.nowMs ?? Date.now;
1207
+ if (input.upload.expiresAtMs <= nowMs())
1208
+ return { outcome: "terminal", status: null, halt: false };
1209
+ const request = new AbortController();
1210
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS);
1211
+ timer.unref?.();
1212
+ const onParentAbort = () => request.abort();
1213
+ input.signal.addEventListener("abort", onParentAbort, { once: true });
1214
+ if (input.signal.aborted) request.abort();
1215
+ const headers = {
1216
+ Authorization: `Bearer ${input.ingestToken}`,
1217
+ "Content-Type": "application/json",
1218
+ Accept: "application/json"
1219
+ };
1220
+ if (input.upload.gzip) headers["Content-Encoding"] = "gzip";
1221
+ try {
1222
+ const response = await fetchUntilAborted(input.fetch, input.url, {
1223
+ method: "POST",
1224
+ headers,
1225
+ body: input.upload.body,
1226
+ signal: request.signal
1227
+ });
1228
+ if (response.ok) return { outcome: "ok" };
1229
+ if (response.status === 429) {
1230
+ return {
1231
+ outcome: "retry",
1232
+ waitMs: retryAfterMs(response) ?? backoffMs(input.attempt, input.random ?? Math.random)
1233
+ };
1234
+ }
1235
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
1236
+ return { outcome: "terminal", status: response.status, halt: true };
1237
+ }
1238
+ if (response.status >= 400 && response.status < 500) {
1239
+ return { outcome: "terminal", status: response.status, halt: false };
1240
+ }
1241
+ return {
1242
+ outcome: "retry",
1243
+ waitMs: backoffMs(input.attempt, input.random ?? Math.random)
1244
+ };
1245
+ } catch {
1246
+ if (input.signal.aborted) return { outcome: "aborted" };
1247
+ return { outcome: "retry", waitMs: backoffMs(input.attempt, input.random ?? Math.random) };
1248
+ } finally {
1249
+ clearTimeout(timer);
1250
+ input.signal.removeEventListener("abort", onParentAbort);
1251
+ }
1252
+ };
1253
+
1254
+ // src/execution-metrics/encode-execution-metrics-upload.ts
1255
+ import {
1256
+ encodeJsonRequestBodyAsync,
1257
+ FUNCTION_METRICS_BUCKET_LATENESS_MS,
1258
+ FUNCTION_METRICS_MAX_DECODED_BYTES,
1259
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS2,
1260
+ parseFunctionMetricsBucketStart
1261
+ } from "@rasputin-ai/core";
1262
+ var minuteMarks = (minute) => {
1263
+ const next = minute.started_executions + minute.completed_executions;
1264
+ return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
1265
+ };
1266
+ var expiresAtMsFor = (batch, nowMs) => {
1267
+ let oldest;
1268
+ for (const start of batch.coverage.covered_bucket_starts) {
1269
+ const bucket = parseFunctionMetricsBucketStart(start);
1270
+ if (bucket === void 0) continue;
1271
+ if (oldest === void 0 || bucket < oldest) oldest = bucket;
1272
+ }
1273
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1274
+ return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1275
+ };
1276
+ var zeroLossCoverage = (coverage) => ({
1277
+ ...coverage,
1278
+ skipped_unresolved_execution_type: 0,
1279
+ dropped_active_series: 0,
1280
+ dropped_byte_budget: 0,
1281
+ dropped_queue_budget: 0,
1282
+ dropped_late_completion: 0,
1283
+ dropped_unexportable: 0
1284
+ });
1285
+ var projectMinutes = (source, minutes, coverage, batchId) => {
1286
+ const typeIndexes = /* @__PURE__ */ new Map();
1287
+ const executionTypes = [];
1288
+ const remappedMinutes = [];
1289
+ for (const minute of minutes) {
1290
+ let executionTypeIndex = typeIndexes.get(minute.execution_type_index);
1291
+ if (executionTypeIndex === void 0) {
1292
+ const entry = source.execution_types[minute.execution_type_index];
1293
+ if (!entry) continue;
1294
+ executionTypeIndex = executionTypes.length;
1295
+ typeIndexes.set(minute.execution_type_index, executionTypeIndex);
1296
+ executionTypes.push(entry);
1297
+ }
1298
+ remappedMinutes.push({ ...minute, execution_type_index: executionTypeIndex });
1299
+ }
1300
+ const covered = [...new Set(remappedMinutes.map((minute) => minute.bucket_start))].sort();
1301
+ return {
1302
+ ...source,
1303
+ batch_id: batchId,
1304
+ execution_types: executionTypes,
1305
+ minutes: remappedMinutes,
1306
+ coverage: { ...coverage, covered_bucket_starts: covered }
1307
+ };
1308
+ };
1309
+ var withLoss = (batch, loss) => ({
1310
+ ...batch,
1311
+ coverage: {
1312
+ ...batch.coverage,
1313
+ dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
1314
+ dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
1315
+ }
1316
+ });
1317
+ var encodeOne = async (batch, nowMs, signal) => {
1318
+ const decodedBytes = new TextEncoder().encode(JSON.stringify(batch));
1319
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES) return void 0;
1320
+ const encoded = await encodeJsonRequestBodyAsync(decodedBytes, void 0, signal);
1321
+ return {
1322
+ decodedBytes,
1323
+ body: encoded.body,
1324
+ gzip: encoded.gzip,
1325
+ batchId: batch.batch_id,
1326
+ expiresAtMs: expiresAtMsFor(batch, nowMs)
1327
+ };
1328
+ };
1329
+ var encodeFitting = async (batch, nowMs, signal) => {
1330
+ const encoded = await encodeOne(batch, nowMs, signal);
1331
+ if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
1332
+ if (batch.minutes.length <= 1) {
1333
+ return {
1334
+ uploads: [],
1335
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
1336
+ };
1337
+ }
1338
+ const mid = Math.ceil(batch.minutes.length / 2);
1339
+ const first = projectMinutes(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
1340
+ const rest = projectMinutes(
1341
+ batch,
1342
+ batch.minutes.slice(mid),
1343
+ zeroLossCoverage(batch.coverage),
1344
+ newExecutionMetricsBatchId()
1345
+ );
1346
+ const left = await encodeFitting(first, nowMs, signal);
1347
+ const right = await encodeFitting(rest, nowMs, signal);
1348
+ return {
1349
+ uploads: [...left.uploads, ...right.uploads],
1350
+ droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
1351
+ };
1352
+ };
1353
+ var encodeExecutionMetricsUploads = async (batches, input) => {
1354
+ const uploads = [];
1355
+ let extra = {
1356
+ dropped_unexportable: 0,
1357
+ dropped_queue_budget: input.queueDrops ?? 0
1358
+ };
1359
+ for (const batch of batches) {
1360
+ const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
1361
+ extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
1362
+ uploads.push(...fitted.uploads);
1363
+ }
1364
+ return uploads;
1365
+ };
1366
+
1367
+ // src/execution-metrics/execution-metrics-exporter.ts
1368
+ var MAX_QUEUE_ITEMS = 32;
1369
+ var MAX_QUEUE_BYTES = 4 * 1024 * 1024;
1370
+ var DEFAULT_SCHEDULE_MS = 6e4;
1371
+ var FLUSH_MS = 1e4;
1372
+ var SHUTDOWN_FLUSH_MS = 2e3;
1373
+ var MAX_ATTEMPTS = 8;
1374
+ var sleep = (ms, signal) => new Promise((resolve) => {
1375
+ if (ms <= 0 || signal.aborted) {
1376
+ resolve();
1377
+ return;
1378
+ }
1379
+ const timer = setTimeout(finish, ms);
1380
+ timer.unref?.();
1381
+ const onAbort = () => {
1382
+ clearTimeout(timer);
1383
+ finish();
1384
+ };
1385
+ function finish() {
1386
+ signal.removeEventListener("abort", onAbort);
1387
+ resolve();
1388
+ }
1389
+ signal.addEventListener("abort", onAbort);
1390
+ if (signal.aborted) onAbort();
1391
+ });
1392
+ var createExecutionMetricsExporter = (input) => {
1393
+ const nowMs = input.nowMs ?? Date.now;
1394
+ const random = input.random ?? Math.random;
1395
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
1396
+ const queue = [];
1397
+ let queueBytes = 0;
1398
+ let queueDrops = 0;
1399
+ let timer;
1400
+ let closed = false;
1401
+ let halted = false;
1402
+ let stopped = false;
1403
+ let workAbort;
1404
+ let work;
1405
+ let sent = 0;
1406
+ let dropped = 0;
1407
+ let warnedHalt = null;
1408
+ const dropOldest = () => {
1409
+ const oldest = queue.shift();
1410
+ if (!oldest) return;
1411
+ queueBytes -= oldest.upload.decodedBytes.byteLength;
1412
+ if (queueBytes < 0) queueBytes = 0;
1413
+ queueDrops += 1;
1414
+ dropped += 1;
1415
+ };
1416
+ const enqueue = (upload) => {
1417
+ queue.push({ upload, attempt: 0 });
1418
+ queueBytes += upload.decodedBytes.byteLength;
1419
+ while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
1420
+ };
1421
+ const drainAndEnqueue = async (flushAll2) => {
1422
+ if (halted || stopped) return;
1423
+ const batches = input.collector.drain({ flushAll: flushAll2 });
1424
+ if (batches.length === 0) return;
1425
+ const encoded = await encodeExecutionMetricsUploads(batches, {
1426
+ nowMs: nowMs(),
1427
+ queueDrops
1428
+ });
1429
+ if (encoded.length === 0 || halted || stopped) return;
1430
+ queueDrops = 0;
1431
+ for (const upload of encoded) enqueue(upload);
1432
+ };
1433
+ const warnHalt = (status) => {
1434
+ if (warnedHalt === status) return;
1435
+ warnedHalt = status;
1436
+ if (status === 401 || status === 403) {
1437
+ console.warn("[rasputin] execution metrics export stopped: authentication failed");
1438
+ return;
1439
+ }
1440
+ if (status === 404) {
1441
+ console.warn("[rasputin] execution metrics export stopped: ingest route is unavailable");
1442
+ }
1443
+ };
1444
+ const pump = async (signal) => {
1445
+ while (queue.length > 0 && !halted && !stopped && !signal.aborted) {
1446
+ const item = queue[0];
1447
+ if (!item) return;
1448
+ if (item.upload.expiresAtMs <= nowMs()) {
1449
+ queue.shift();
1450
+ queueBytes -= item.upload.decodedBytes.byteLength;
1451
+ dropped += 1;
1452
+ continue;
1453
+ }
1454
+ if (item.attempt >= MAX_ATTEMPTS) {
1455
+ queue.shift();
1456
+ queueBytes -= item.upload.decodedBytes.byteLength;
1457
+ dropped += 1;
1458
+ continue;
1459
+ }
1460
+ const result = await sendFunctionMetricsBatch({
1461
+ url: input.url,
1462
+ ingestToken: input.ingestToken,
1463
+ upload: item.upload,
1464
+ fetch: input.fetch,
1465
+ signal,
1466
+ attempt: item.attempt,
1467
+ random,
1468
+ nowMs
1469
+ });
1470
+ if (result.outcome === "aborted") return;
1471
+ if (result.outcome === "ok") {
1472
+ queue.shift();
1473
+ queueBytes -= item.upload.decodedBytes.byteLength;
1474
+ sent += 1;
1475
+ continue;
1476
+ }
1477
+ if (result.outcome === "terminal") {
1478
+ queue.shift();
1479
+ queueBytes -= item.upload.decodedBytes.byteLength;
1480
+ dropped += 1;
1481
+ if (result.halt) {
1482
+ halted = true;
1483
+ warnHalt(result.status);
1484
+ }
1485
+ continue;
1486
+ }
1487
+ item.attempt += 1;
1488
+ await sleep(result.waitMs, signal);
1489
+ }
1490
+ };
1491
+ const abortCurrent = () => {
1492
+ workAbort?.abort();
1493
+ };
1494
+ const raceUntilAborted = async (running, signal) => {
1495
+ if (signal.aborted) return;
1496
+ await new Promise((resolve) => {
1497
+ let settled = false;
1498
+ const finish = () => {
1499
+ if (settled) return;
1500
+ settled = true;
1501
+ signal.removeEventListener("abort", finish);
1502
+ resolve();
1503
+ };
1504
+ signal.addEventListener("abort", finish);
1505
+ if (signal.aborted) {
1506
+ finish();
1507
+ return;
1508
+ }
1509
+ void running.then(finish, finish);
1510
+ });
1511
+ };
1512
+ const runWork = async (signal, task) => {
1513
+ const onAbort = () => abortCurrent();
1514
+ signal.addEventListener("abort", onAbort);
1515
+ if (signal.aborted) abortCurrent();
1516
+ try {
1517
+ while (work) {
1518
+ const previous = work;
1519
+ await raceUntilAborted(previous, signal);
1520
+ if (signal.aborted || halted) return;
1521
+ if (work === previous) return;
1522
+ }
1523
+ if (halted) return;
1524
+ const inner = new AbortController();
1525
+ workAbort = inner;
1526
+ if (signal.aborted) {
1527
+ workAbort = void 0;
1528
+ return;
1529
+ }
1530
+ const running = task(inner.signal).finally(() => {
1531
+ if (workAbort === inner) workAbort = void 0;
1532
+ if (work === running) work = void 0;
1533
+ });
1534
+ work = running;
1535
+ await raceUntilAborted(running, signal);
1536
+ } finally {
1537
+ signal.removeEventListener("abort", onAbort);
1538
+ }
1539
+ };
1540
+ const tick = async () => {
1541
+ if (closed || halted) return;
1542
+ try {
1543
+ await runWork(new AbortController().signal, async (signal) => {
1544
+ if (closed || halted) return;
1545
+ await drainAndEnqueue(false);
1546
+ await pump(signal);
1547
+ });
1548
+ } catch {
1549
+ }
1550
+ if (!closed && !halted) arm();
1551
+ };
1552
+ const arm = () => {
1553
+ if (closed || halted) return;
1554
+ const delay = Math.max(1e3, Math.floor(scheduleMs * (0.85 + random() * 0.3)));
1555
+ timer = setTimeout(() => {
1556
+ void tick();
1557
+ }, delay);
1558
+ timer.unref?.();
1559
+ };
1560
+ arm();
1561
+ const flush = async (timeoutMs) => {
1562
+ if (closed || halted) return;
1563
+ const abort = new AbortController();
1564
+ const budget = timeoutMs ?? FLUSH_MS;
1565
+ const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
1566
+ try {
1567
+ await runWork(abort.signal, async (signal) => {
1568
+ if (closed || halted) return;
1569
+ await drainAndEnqueue(true);
1570
+ await pump(signal);
1571
+ });
1572
+ } catch {
1573
+ } finally {
1574
+ clearTimeout(timeout);
1575
+ }
1576
+ };
1577
+ return {
1578
+ flush,
1579
+ close: async () => {
1580
+ if (closed) return;
1581
+ closed = true;
1582
+ if (timer) clearTimeout(timer);
1583
+ timer = void 0;
1584
+ const abort = new AbortController();
1585
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
1586
+ abortCurrent();
1587
+ try {
1588
+ await runWork(abort.signal, async (signal) => {
1589
+ input.collector.seal();
1590
+ await drainAndEnqueue(false);
1591
+ await pump(signal);
1592
+ });
1593
+ } catch {
1594
+ } finally {
1595
+ clearTimeout(timeout);
1596
+ stopped = true;
1597
+ input.collector.seal();
1598
+ queue.length = 0;
1599
+ queueBytes = 0;
1600
+ }
1601
+ },
1602
+ getStats: () => ({ sent, dropped, halted })
1603
+ };
1604
+ };
1605
+
1606
+ // src/execution-metrics/bind-execution-metrics.ts
1607
+ var SLOT = Symbol.for("rasputin.executionMetrics.runtime.v1");
1608
+ var releasedHandles = /* @__PURE__ */ new WeakSet();
1609
+ var isRuntime = (value) => {
1610
+ if (typeof value !== "object" || value === null) return false;
1611
+ return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
1612
+ };
1613
+ var bindingIdentity = (input) => `${input.ingestToken}
1614
+ ${input.url}
1615
+ ${input.environment}
1616
+ ${input.release}
1617
+ ${input.sampledMeasurementFormat ? "1" : "0"}`;
1618
+ var warnIncompatible = (runtime) => {
1619
+ if (runtime.warnedMismatch) return;
1620
+ runtime.warnedMismatch = true;
1621
+ console.warn(
1622
+ "[rasputin] execution metrics already running with a different configuration; this client will not collect execution metrics"
1623
+ );
1624
+ };
1625
+ var createBindings = (input) => {
1626
+ const collector = createExecutionMetricsCollector({
1627
+ environment: input.environment,
1628
+ producerId: randomUUID2(),
1629
+ release: input.release,
1630
+ sampledMeasurementFormat: input.sampledMeasurementFormat
1631
+ });
1632
+ return {
1633
+ collector,
1634
+ exporter: createExecutionMetricsExporter({
1635
+ collector,
1636
+ url: input.url,
1637
+ ingestToken: input.ingestToken,
1638
+ fetch: input.fetch ?? defaultIngestFetch()
1639
+ })
1640
+ };
1641
+ };
1642
+ var bindExecutionMetrics = (input) => {
1643
+ if (!input.clientEnabled) return void 0;
1644
+ if (input.options?.enabled === false) return void 0;
1645
+ const release = input.release.trim().toLowerCase();
1646
+ if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
1647
+ const url = resolveEndpointUrls2(input.apiUrl).executionMetricsUrl;
1648
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
1649
+ const key = bindingIdentity({
1650
+ ingestToken: input.ingestToken,
1651
+ url,
1652
+ environment: input.environment,
1653
+ release,
1654
+ sampledMeasurementFormat
1655
+ });
1656
+ const existing = Reflect.get(globalThis, SLOT);
1657
+ if (isRuntime(existing)) {
1658
+ if (existing.identity !== key) {
1659
+ warnIncompatible(existing);
1660
+ return void 0;
1661
+ }
1662
+ existing.refs += 1;
1663
+ return { collector: existing.collector, exporter: existing.exporter };
1664
+ }
1665
+ const bindings2 = createBindings({
1666
+ release,
1667
+ ingestToken: input.ingestToken,
1668
+ url,
1669
+ environment: input.environment,
1670
+ fetch: input.fetch,
1671
+ sampledMeasurementFormat
1672
+ });
1673
+ Reflect.set(globalThis, SLOT, {
1674
+ ...bindings2,
1675
+ refs: 1,
1676
+ identity: key,
1677
+ warnedMismatch: false
1678
+ });
1679
+ return bindings2;
1680
+ };
1681
+ var releaseExecutionMetricsBindings = async (bindings2) => {
1682
+ if (!bindings2 || releasedHandles.has(bindings2)) return;
1683
+ releasedHandles.add(bindings2);
1684
+ const existing = Reflect.get(globalThis, SLOT);
1685
+ if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
1686
+ existing.refs -= 1;
1687
+ if (existing.refs > 0) return;
1688
+ Reflect.deleteProperty(globalThis, SLOT);
1689
+ }
1690
+ await bindings2.exporter.close();
1691
+ };
1692
+
681
1693
  // src/execution-recorder/execution-recorder.ts
682
1694
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
683
1695
  import {
@@ -732,11 +1744,30 @@ var executionTypeKey = (metadata) => {
732
1744
  var isHttpClientErrorStatus = (status) => {
733
1745
  return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
734
1746
  };
1747
+ var isHttpServerErrorStatus = (status) => {
1748
+ return typeof status === "number" && Number.isFinite(status) && status >= 500;
1749
+ };
1750
+ var executionOutcomeFailed = (input) => input.hasError || input.runFailed || isHttpServerErrorStatus(input.status);
735
1751
 
736
1752
  // src/execution-recorder/function-plan.ts
737
1753
  var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
738
1754
  var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
739
1755
 
1756
+ // src/runtime-timing/call-duration.ts
1757
+ var planCallDuration = (sampler, input) => {
1758
+ if (!sampler) return { selected: true, measure: true };
1759
+ if (!input.executionType) return { selected: false, measure: input.forceMeasure };
1760
+ const selected = sampler.take(input.executionType, input.callerFunctionId, input.functionId);
1761
+ return { selected, measure: selected || input.forceMeasure };
1762
+ };
1763
+
1764
+ // src/runtime-timing/execution-duration.ts
1765
+ var planExecutionDuration = (sampler, executionType) => {
1766
+ if (!sampler) return { selected: true };
1767
+ if (!executionType) return { selected: false };
1768
+ return { selected: sampler.takeExecution(executionType) };
1769
+ };
1770
+
740
1771
  // src/function-metrics/function-metric-declaration-registry.ts
741
1772
  var REGISTRY_SYMBOL = Symbol.for("rasputin.functionMetrics.declarations.v1");
742
1773
  var getRegistry2 = () => {
@@ -761,58 +1792,93 @@ var registerFunctionMetricDeclarations = (declarations) => {
761
1792
  var functionMetricDeclarationFor = (runtimeId) => getRegistry2().byRuntimeId.get(runtimeId);
762
1793
 
763
1794
  // src/function-metrics/intern-prepared-metrics.ts
764
- import { functionMetricsTraceDeclaration } from "@rasputin-ai/core";
765
- var internPreparedMetrics = (collector, plan) => {
1795
+ import {
1796
+ functionMetricsTraceDeclaration
1797
+ } from "@rasputin-ai/core";
1798
+ var declarationForPreparedPlan = (plan) => {
766
1799
  if (plan.excluded) return void 0;
767
- if (plan.metricsHandle !== void 0) return plan.metricsHandle;
768
1800
  const declaration = plan.metricsDeclaration ?? functionMetricDeclarationFor(plan.functionId) ?? functionMetricsTraceDeclaration({
769
1801
  runtimeId: plan.functionId
770
1802
  });
771
1803
  plan.metricsDeclaration = declaration;
1804
+ return declaration;
1805
+ };
1806
+ var internPreparedMetrics = (collector, plan) => {
1807
+ if (plan.excluded) return void 0;
1808
+ if (plan.metricsHandle !== void 0) return plan.metricsHandle;
1809
+ const declaration = declarationForPreparedPlan(plan);
772
1810
  const handle = collector.internDeclaration(declaration);
773
1811
  if (handle !== void 0) plan.metricsHandle = handle;
774
1812
  return handle;
775
1813
  };
776
1814
 
777
1815
  // src/function-metrics/settle-function-metrics.ts
778
- var finishMetricsCall = (collector, functionHandle, executionHandle, startedNs, failed, endedNs) => {
1816
+ var finishMetricsCall = (collector, functionHandle, executionHandle, failed, timing) => {
779
1817
  try {
780
- collector.finishCall(functionHandle, executionHandle, startedNs, failed, endedNs);
1818
+ collector.finishCall(functionHandle, executionHandle, failed, timing);
781
1819
  } catch {
782
1820
  }
783
1821
  };
784
1822
  var thenOf = (value) => {
785
- if (typeof value !== "object" && typeof value !== "function" || value === null) {
1823
+ try {
1824
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
1825
+ return void 0;
1826
+ }
1827
+ if (!("then" in value)) return void 0;
1828
+ const then = value.then;
1829
+ if (typeof then !== "function") return void 0;
1830
+ return (onFulfilled, onRejected) => {
1831
+ Reflect.apply(then, value, [onFulfilled, onRejected]);
1832
+ };
1833
+ } catch {
1834
+ return void 0;
1835
+ }
1836
+ };
1837
+ var tryCallClock = () => {
1838
+ try {
1839
+ return process.hrtime.bigint();
1840
+ } catch {
786
1841
  return void 0;
787
1842
  }
788
- if (!("then" in value)) return void 0;
789
- const then = value.then;
790
- if (typeof then !== "function") return void 0;
791
- return (onFulfilled, onRejected) => {
792
- Reflect.apply(then, value, [onFulfilled, onRejected]);
793
- };
794
1843
  };
795
- var startMetricsCall = (collector, functionHandle, executionHandle, startedNs) => {
1844
+ var startMetricsCall = (collector, functionHandle, executionHandle, options) => {
796
1845
  if (!collector || functionHandle === void 0) return void 0;
797
1846
  try {
798
- return collector.startCall(functionHandle, executionHandle, startedNs);
1847
+ return collector.startCall(functionHandle, executionHandle, options);
799
1848
  } catch {
800
1849
  return void 0;
801
1850
  }
802
1851
  };
803
- var completeMetricsResult = (collector, functionHandle, executionHandle, startedNs, value) => {
1852
+ var completeMetricsResult = (collector, functionHandle, executionHandle, value, timing, onSettled) => {
804
1853
  const then = thenOf(value);
805
1854
  if (!then) {
806
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false);
1855
+ finishMetricsCall(collector, functionHandle, executionHandle, false, timing);
807
1856
  return;
808
1857
  }
1858
+ let completed = false;
1859
+ const complete = (failed) => {
1860
+ if (completed) return;
1861
+ completed = true;
1862
+ const endedNs = timing !== void 0 ? tryCallClock() : void 0;
1863
+ finishMetricsCall(
1864
+ collector,
1865
+ functionHandle,
1866
+ executionHandle,
1867
+ failed,
1868
+ timing === void 0 ? void 0 : { startedNs: timing.startedNs, endedNs }
1869
+ );
1870
+ try {
1871
+ onSettled?.(endedNs);
1872
+ } catch {
1873
+ }
1874
+ };
809
1875
  try {
810
1876
  then(
811
- () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false),
812
- () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true)
1877
+ () => complete(false),
1878
+ () => complete(true)
813
1879
  );
814
1880
  } catch {
815
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
1881
+ complete(true);
816
1882
  }
817
1883
  };
818
1884
 
@@ -852,6 +1918,14 @@ var emptyStats = () => ({
852
1918
  adaptiveRefreshFailures: 0,
853
1919
  lastAdaptiveFailureKind: null
854
1920
  });
1921
+ var metricsStorage = new AsyncLocalStorage();
1922
+ var tryCallClock2 = () => {
1923
+ try {
1924
+ return process.hrtime.bigint();
1925
+ } catch {
1926
+ return void 0;
1927
+ }
1928
+ };
855
1929
  var mergeMetadata = (store, metadata) => {
856
1930
  if (metadata.kind) store.execution.kind = metadata.kind;
857
1931
  if (metadata.name !== void 0) store.execution.name = metadata.name;
@@ -865,32 +1939,100 @@ var definitionOf = (input) => {
865
1939
  return input;
866
1940
  };
867
1941
  var bindExecutionHandle = (collector, store) => {
1942
+ if (!collector) return;
868
1943
  store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
869
1944
  };
870
- var runWithMetrics = (collector, plan, executionHandle, callback) => {
1945
+ var bindExecutionMetricsIdentity = (collector, store) => {
1946
+ if (!collector || !store.executionMetrics) return;
1947
+ collector.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
1948
+ };
1949
+ var settleStarted = (collector, functionHandle, executionHandle, started, value, failed, endedNs) => {
1950
+ if (!started || functionHandle === void 0 || executionHandle === void 0) return;
1951
+ const timing = started.measure ? { startedNs: started.startedNs, endedNs } : void 0;
1952
+ if (failed) {
1953
+ finishMetricsCall(collector, functionHandle, executionHandle, true, timing);
1954
+ return;
1955
+ }
1956
+ completeMetricsResult(collector, functionHandle, executionHandle, value, timing);
1957
+ };
1958
+ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1959
+ if (!collector) return callback();
1960
+ const duration = planCallDuration(durationSampler, {
1961
+ forceMeasure: false,
1962
+ executionType: store ? executionTypeKey(store.execution) : void 0,
1963
+ callerFunctionId: store?.currentFunctionId ?? "",
1964
+ functionId: plan.functionId
1965
+ });
1966
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
871
1967
  const functionHandle = internPreparedMetrics(collector, plan);
872
- const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
873
- try {
874
- const result = callback();
875
- if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
876
- completeMetricsResult(collector, functionHandle, executionHandle, startedNs, result);
877
- }
878
- return result;
879
- } catch (error) {
880
- if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
881
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
1968
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
1969
+ measure: duration.selected,
1970
+ ...duration.selected ? { startedNs } : {}
1971
+ });
1972
+ const invoke = () => {
1973
+ try {
1974
+ const result = callback();
1975
+ settleStarted(
1976
+ collector,
1977
+ functionHandle,
1978
+ store?.executionHandle,
1979
+ started,
1980
+ result,
1981
+ false,
1982
+ started?.measure && !(result instanceof Promise) ? tryCallClock2() : void 0
1983
+ );
1984
+ return result;
1985
+ } catch (error) {
1986
+ settleStarted(
1987
+ collector,
1988
+ functionHandle,
1989
+ store?.executionHandle,
1990
+ started,
1991
+ error,
1992
+ true,
1993
+ started?.measure ? tryCallClock2() : void 0
1994
+ );
1995
+ throw error;
882
1996
  }
883
- throw error;
884
- }
1997
+ };
1998
+ if (!store || !durationSampler) return invoke();
1999
+ return metricsStorage.run({ ...store, currentFunctionId: plan.functionId }, invoke);
885
2000
  };
886
- var metricsHandle = (collector, plan, executionHandle) => {
2001
+ var metricsHandle = (collector, durationSampler, plan, store) => {
2002
+ if (!collector) return passthroughHandle();
2003
+ const duration = planCallDuration(durationSampler, {
2004
+ forceMeasure: false,
2005
+ executionType: store ? executionTypeKey(store.execution) : void 0,
2006
+ callerFunctionId: store?.currentFunctionId ?? "",
2007
+ functionId: plan.functionId
2008
+ });
2009
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
887
2010
  const functionHandle = internPreparedMetrics(collector, plan);
888
- const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
889
- if (startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
2011
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
2012
+ measure: duration.selected,
2013
+ ...duration.selected ? { startedNs } : {}
2014
+ });
2015
+ if (!started || functionHandle === void 0 || store?.executionHandle === void 0) {
890
2016
  return passthroughHandle();
891
2017
  }
2018
+ const executionHandle = store.executionHandle;
892
2019
  let failed = false;
893
2020
  let settled = false;
2021
+ let previousFunctionId = store.currentFunctionId;
2022
+ let callerClaimed = false;
2023
+ const claimCaller = () => {
2024
+ if (callerClaimed || !durationSampler) return;
2025
+ previousFunctionId = store.currentFunctionId;
2026
+ store.currentFunctionId = plan.functionId;
2027
+ callerClaimed = true;
2028
+ };
2029
+ const releaseCaller = () => {
2030
+ if (!callerClaimed) return;
2031
+ callerClaimed = false;
2032
+ if (previousFunctionId === void 0) delete store.currentFunctionId;
2033
+ else store.currentFunctionId = previousFunctionId;
2034
+ };
2035
+ claimCaller();
894
2036
  return {
895
2037
  leave: (value) => value,
896
2038
  fail: () => {
@@ -899,20 +2041,36 @@ var metricsHandle = (collector, plan, executionHandle) => {
899
2041
  end: () => {
900
2042
  if (settled) return;
901
2043
  settled = true;
902
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, failed);
2044
+ releaseCaller();
2045
+ const endedNs = started.measure ? tryCallClock2() : void 0;
2046
+ finishMetricsCall(
2047
+ collector,
2048
+ functionHandle,
2049
+ executionHandle,
2050
+ failed,
2051
+ started.measure ? { startedNs: started.startedNs, endedNs } : void 0
2052
+ );
903
2053
  },
904
2054
  run: function __rasputinHandleRun__4(callback) {
905
2055
  return runExactlyOnce((invoke) => invoke(), callback);
906
2056
  },
907
- suspend: (value) => value,
908
- resume: (value) => value
2057
+ suspend: (value) => {
2058
+ releaseCaller();
2059
+ return value;
2060
+ },
2061
+ resume: (value) => {
2062
+ claimCaller();
2063
+ return value;
2064
+ }
909
2065
  };
910
2066
  };
911
- var createMetricsOnlyRuntime = (collector) => {
912
- const storage = new AsyncLocalStorage();
2067
+ var createMetricsOnlyRuntime = (input) => {
2068
+ const collector = input.functionMetrics;
2069
+ const executionMetrics = input.executionMetrics;
2070
+ const durationSampler = input.durationSampler;
913
2071
  const preparedModules = /* @__PURE__ */ new WeakMap();
914
2072
  let nextRuntimePlanId = 1;
915
- const currentHandle = () => storage.getStore()?.executionHandle;
2073
+ const currentStore = () => metricsStorage.getStore();
916
2074
  const planFor = (definition) => ({
917
2075
  runtimePlanId: nextRuntimePlanId++,
918
2076
  definition,
@@ -938,9 +2096,9 @@ var createMetricsOnlyRuntime = (collector) => {
938
2096
  preparedModules.set(plans, prepared);
939
2097
  return prepared;
940
2098
  };
941
- const runPrepared = (plan, _args, callback) => runWithMetrics(collector, plan, currentHandle(), callback);
942
- function trace(input, fn) {
943
- const definition = typeof input === "string" ? definitionOf(input) : { ...input, functionId: runtimeFunctionId2(input) };
2099
+ const runPrepared = (plan, _args, callback) => runWithMetrics(collector, durationSampler, plan, currentStore(), callback);
2100
+ function trace(input2, fn) {
2101
+ const definition = typeof input2 === "string" ? definitionOf(input2) : { ...input2, functionId: runtimeFunctionId2(input2) };
944
2102
  const plan = planFor(definition);
945
2103
  return function __rasputinHandleRun__4(...args) {
946
2104
  if (new.target) {
@@ -949,6 +2107,28 @@ var createMetricsOnlyRuntime = (collector) => {
949
2107
  return runPrepared(plan, args, () => fn.apply(this, args));
950
2108
  };
951
2109
  }
2110
+ const finishScope = (store, next) => {
2111
+ if (next) {
2112
+ mergeMetadata(store, next);
2113
+ bindExecutionHandle(collector, store);
2114
+ bindExecutionMetricsIdentity(executionMetrics, store);
2115
+ }
2116
+ if (!executionMetrics || !store.executionMetrics) return;
2117
+ if (store.executionMetrics.finished) return;
2118
+ const endedNs = tryCallClock2();
2119
+ const executionKey = executionTypeKey(store.execution);
2120
+ bindExecutionMetricsIdentity(executionMetrics, store);
2121
+ executionMetrics.finishExecution(store.executionMetrics, {
2122
+ failed: executionOutcomeFailed({
2123
+ hasError: store.hasError,
2124
+ runFailed: store.runFailed,
2125
+ status: store.execution.request?.status
2126
+ }),
2127
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
2128
+ startedNs: store.startedAtNs,
2129
+ ...endedNs === void 0 ? {} : { endedNs }
2130
+ });
2131
+ };
952
2132
  return {
953
2133
  createScope: (metadata) => {
954
2134
  const store = {
@@ -956,22 +2136,35 @@ var createMetricsOnlyRuntime = (collector) => {
956
2136
  ...metadata,
957
2137
  ...metadata.request ? { request: { ...metadata.request } } : {}
958
2138
  },
959
- executionHandle: void 0
2139
+ executionHandle: void 0,
2140
+ startedAtNs: tryCallClock2() ?? 0n,
2141
+ hasError: false,
2142
+ runFailed: false
960
2143
  };
961
2144
  bindExecutionHandle(collector, store);
2145
+ if (executionMetrics) {
2146
+ store.executionMetrics = executionMetrics.createState();
2147
+ bindExecutionMetricsIdentity(executionMetrics, store);
2148
+ }
962
2149
  return {
963
- run: (callback) => storage.run(store, callback),
964
- getErrorState: () => void 0,
965
- observeError: () => inertErrorObservation(),
966
- finish: (next) => {
967
- if (next) {
968
- mergeMetadata(store, next);
969
- bindExecutionHandle(collector, store);
2150
+ run: (callback) => metricsStorage.run(store, () => {
2151
+ try {
2152
+ return callback();
2153
+ } catch (error) {
2154
+ store.runFailed = true;
2155
+ throw error;
970
2156
  }
2157
+ }),
2158
+ getErrorState: () => void 0,
2159
+ observeError: () => {
2160
+ store.hasError = true;
2161
+ return inertErrorObservation();
971
2162
  },
2163
+ finish: (next) => finishScope(store, next),
972
2164
  mergeMetadata: (next) => {
973
2165
  mergeMetadata(store, next);
974
2166
  bindExecutionHandle(collector, store);
2167
+ bindExecutionMetricsIdentity(executionMetrics, store);
975
2168
  }
976
2169
  };
977
2170
  },
@@ -983,10 +2176,11 @@ var createMetricsOnlyRuntime = (collector) => {
983
2176
  },
984
2177
  prepareFunctionPlans: (plans) => prepareEncoded(plans),
985
2178
  runPreparedFunction: runPrepared,
986
- enterPreparedFunction: (plan) => metricsHandle(collector, plan, currentHandle()),
2179
+ enterPreparedFunction: (plan) => metricsHandle(collector, durationSampler, plan, currentStore()),
987
2180
  trace,
988
2181
  getStats: () => emptyStats(),
989
2182
  close: () => {
2183
+ durationSampler?.stop();
990
2184
  }
991
2185
  };
992
2186
  };
@@ -1004,68 +2198,6 @@ var sanitizeFullCaptureDurationMs = (value) => {
1004
2198
  Math.max(MIN_FULL_CAPTURE_DURATION_MS, Math.floor(value))
1005
2199
  );
1006
2200
  };
1007
- var sanitizeDynamicDurationSampling = (value) => value === true;
1008
-
1009
- // src/execution-recorder/dynamic-duration-sampling.ts
1010
- var DYNAMIC_DURATION_SAMPLE_STAGES = [
1011
- { below: 10, divisor: 1 },
1012
- { below: 30, divisor: 2 },
1013
- { below: 100, divisor: 3 },
1014
- { below: 500, divisor: 11 },
1015
- { below: 1e3, divisor: 23 },
1016
- { below: 5e3, divisor: 53 }
1017
- ];
1018
- var DYNAMIC_DURATION_SAMPLE_TAIL_AFTER = 5e3;
1019
- var DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR = 100;
1020
- var DYNAMIC_DURATION_SAMPLE_RESET_MS = 60 * 60 * 1e3;
1021
- var MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS = 4096;
1022
- var dynamicDurationSampleDivisor = (index) => {
1023
- for (const stage of DYNAMIC_DURATION_SAMPLE_STAGES) {
1024
- if (index < stage.below) return stage.divisor;
1025
- }
1026
- return DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
1027
- };
1028
- var shouldSampleDynamicDuration = (index) => {
1029
- return index % dynamicDurationSampleDivisor(index) === 0;
1030
- };
1031
- var nextDurationSampleIndex = (index) => {
1032
- if (index < Number.MAX_SAFE_INTEGER) return index + 1;
1033
- return DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + (index - DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + 1) % DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
1034
- };
1035
- var createDynamicDurationSampleBuckets = (options) => {
1036
- const buckets = /* @__PURE__ */ new Map();
1037
- const maxBuckets = options.maxBuckets ?? MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS;
1038
- const resetMs = options.resetMs ?? DYNAMIC_DURATION_SAMPLE_RESET_MS;
1039
- let lastResetAtMs = options.nowMs();
1040
- const reset = () => {
1041
- buckets.clear();
1042
- lastResetAtMs = options.nowMs();
1043
- };
1044
- const resetTimer = setInterval(reset, resetMs);
1045
- resetTimer.unref?.();
1046
- return {
1047
- take: (executionType, callerFunctionId, functionId) => {
1048
- if (options.nowMs() - lastResetAtMs >= resetMs) reset();
1049
- const key = `${executionType}\0${callerFunctionId}\0${functionId}`;
1050
- const existing = buckets.get(key);
1051
- if (existing !== void 0) {
1052
- buckets.delete(key);
1053
- buckets.set(key, nextDurationSampleIndex(existing));
1054
- return shouldSampleDynamicDuration(existing);
1055
- }
1056
- while (buckets.size >= maxBuckets) {
1057
- const oldest = buckets.keys().next().value;
1058
- if (oldest === void 0) break;
1059
- buckets.delete(oldest);
1060
- }
1061
- buckets.set(key, nextDurationSampleIndex(0));
1062
- return shouldSampleDynamicDuration(0);
1063
- },
1064
- stop: () => {
1065
- clearInterval(resetTimer);
1066
- }
1067
- };
1068
- };
1069
2201
 
1070
2202
  // src/execution-recorder/execution-journal.ts
1071
2203
  var KIND_ENTER = 1;
@@ -1164,6 +2296,15 @@ var ExecutionJournal = class {
1164
2296
  }
1165
2297
  this.openCallIds.delete(callId);
1166
2298
  }
2299
+ setCallTiming(callId, timestampNs, durationNs) {
2300
+ for (let index = this.length - 1; index >= 0; index--) {
2301
+ if (this.callId[index] !== callId) continue;
2302
+ if (this.kind[index] !== KIND_EXIT && this.kind[index] !== KIND_THROW) continue;
2303
+ this.timestampNs[index] = timestampNs;
2304
+ this.durationNs[index] = durationNs;
2305
+ return;
2306
+ }
2307
+ }
1167
2308
  dropCall() {
1168
2309
  this.dropped += 2;
1169
2310
  }
@@ -3101,24 +4242,49 @@ var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
3101
4242
  var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
3102
4243
  var createExecutionRecorder = (options, hooks = {}) => {
3103
4244
  if (!options?.enabled) {
3104
- return hooks.functionMetrics ? createMetricsOnlyRuntime(hooks.functionMetrics) : noOpExecution;
4245
+ return hooks.functionMetrics || hooks.executionMetrics ? createMetricsOnlyRuntime({
4246
+ functionMetrics: hooks.functionMetrics,
4247
+ executionMetrics: hooks.executionMetrics,
4248
+ durationSampler: hooks.durationSampler
4249
+ }) : noOpExecution;
3105
4250
  }
3106
4251
  const functionMetrics = hooks.functionMetrics;
4252
+ const executionMetrics = hooks.executionMetrics;
4253
+ const durationSampler = hooks.durationSampler;
3107
4254
  const bindMetricsExecution = (recording) => {
3108
4255
  if (!functionMetrics) return;
3109
4256
  recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
3110
4257
  executionTypeKey(recording.execution)
3111
4258
  );
3112
4259
  };
4260
+ const bindExecutionMetricsIdentity2 = (recording) => {
4261
+ if (!executionMetrics || !recording.executionMetrics) return;
4262
+ executionMetrics.bindIdentity(
4263
+ recording.executionMetrics,
4264
+ executionTypeKey(recording.execution)
4265
+ );
4266
+ };
3113
4267
  warnIfMissingAsyncContextFrame();
3114
4268
  const adaptiveEnabled = options.adaptive?.enabled === true;
3115
4269
  const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
3116
4270
  options.adaptive?.fullCaptureDurationMs
3117
4271
  );
3118
- const durationSamplingEnabled = adaptiveEnabled && sanitizeDynamicDurationSampling(options.adaptive?.dynamicDurationSampling);
4272
+ const trackCallers = durationSampler !== void 0;
3119
4273
  const readCallClock = () => process.hrtime.bigint();
4274
+ const tryCallClock3 = () => {
4275
+ try {
4276
+ return readCallClock();
4277
+ } catch {
4278
+ return void 0;
4279
+ }
4280
+ };
4281
+ const invocationStart = (measure) => {
4282
+ if (!measure) return { timed: false, startedAtNs: 0n };
4283
+ const startedAtNs = tryCallClock3();
4284
+ if (startedAtNs === void 0) return { timed: false, startedAtNs: 0n };
4285
+ return { timed: true, startedAtNs };
4286
+ };
3120
4287
  const nowMs = () => hooks.nowMs?.() ?? Date.now();
3121
- const durationSamples = durationSamplingEnabled ? createDynamicDurationSampleBuckets({ nowMs }) : void 0;
3122
4288
  const localActivations = /* @__PURE__ */ new Map();
3123
4289
  const policySnapshotFor = () => hooks.policySnapshot?.() ?? localActivations;
3124
4290
  const keyIsActive = (snapshot, key, atMs) => {
@@ -3303,21 +4469,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
3303
4469
  }
3304
4470
  };
3305
4471
  const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
3306
- const durationSamplingApplies = (recording) => durationSamplingEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess;
3307
4472
  const callStoreFor = (store, functionId, callId) => {
3308
4473
  const next = { ...store, currentCallId: callId };
3309
- if (durationSamplingEnabled) next.currentFunctionId = functionId;
4474
+ if (trackCallers) next.currentFunctionId = functionId;
3310
4475
  return next;
3311
4476
  };
3312
4477
  const samplingStore = (store, functionId) => {
3313
- return durationSamplingEnabled ? { ...store, currentFunctionId: functionId } : store;
3314
- };
3315
- const decideCallTiming = (recording, plan, callerFunctionId) => {
3316
- if (!durationSamplingApplies(recording) || !durationSamples) return true;
3317
- const typeKey = executionTypeKey(recording.execution);
3318
- if (!typeKey) return true;
3319
- return durationSamples.take(typeKey, callerFunctionId ?? "", plan.functionId);
3320
- };
4478
+ return trackCallers ? { ...store, currentFunctionId: functionId } : store;
4479
+ };
4480
+ const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess);
4481
+ const planInvocationDuration = (recording, plan, callerFunctionId) => planCallDuration(durationSampler, {
4482
+ forceMeasure: recorderForceMeasure(recording),
4483
+ executionType: executionTypeKey(recording.execution),
4484
+ callerFunctionId: callerFunctionId ?? "",
4485
+ functionId: plan.functionId
4486
+ });
3321
4487
  const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
3322
4488
  const tryAdmitLiveSession = (recording) => {
3323
4489
  if (recording.retainSuccess || recording.finished) return;
@@ -3530,7 +4696,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3530
4696
  },
3531
4697
  functions: functions.slice(),
3532
4698
  events: fullyTimed ? asFullyTimedEvents(events) : events.slice(),
3533
- ...fullyTimed || !durationSamplingEnabled ? {} : { durationSampling: { policy: "progressive" } },
4699
+ ...fullyTimed || !durationSampler ? {} : { durationSampling: { policy: "progressive" } },
3534
4700
  ...truncated ? { truncated: { ...truncated } } : {},
3535
4701
  ...capture ? { capture: { ...capture } } : {}
3536
4702
  };
@@ -3800,7 +4966,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3800
4966
  }
3801
4967
  };
3802
4968
  };
3803
- const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs) => {
4969
+ const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
3804
4970
  if (!recording.journal) {
3805
4971
  return;
3806
4972
  }
@@ -3810,17 +4976,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
3810
4976
  const callId = ++recording.nextCallId;
3811
4977
  const capturedError = serializedError(recording, error, callId);
3812
4978
  const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3813
- const endedAtNs = readCallClock();
4979
+ const endedAtNs = timed ? completedAtNs : void 0;
3814
4980
  const droppedBefore = recording.journal.dropped;
3815
4981
  const retained = recording.journal.forceCompletedCall(
3816
4982
  plan.runtimePlanId,
3817
4983
  callId,
3818
4984
  parentCallId,
3819
- timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4985
+ timed && endedAtNs !== void 0 ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
3820
4986
  recordedArgs,
3821
4987
  KIND_THROW,
3822
- endedAtNs - recording.startedAtNs,
3823
- timed ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
4988
+ timed && endedAtNs !== void 0 ? endedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4989
+ timed && endedAtNs !== void 0 ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
3824
4990
  capturedError.value
3825
4991
  );
3826
4992
  if (retained) {
@@ -3852,6 +5018,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
3852
5018
  appendSuppressedPlaceholder(recording, suppressed);
3853
5019
  }
3854
5020
  };
5021
+ const addSuppressedDuration = (suppressed, startedAtNs, endedAtNs) => {
5022
+ if (!suppressed.firstTimed) {
5023
+ suppressed.firstTimestampNs = startedAtNs;
5024
+ suppressed.firstTimed = true;
5025
+ }
5026
+ suppressed.lastTimestampNs = endedAtNs;
5027
+ suppressed.lastTimed = true;
5028
+ suppressed.sampledDurationCount++;
5029
+ suppressed.sampledDurationNs += endedAtNs - startedAtNs;
5030
+ };
3855
5031
  const releaseJournalIfIdle = (recording) => {
3856
5032
  if (!recording.finished || recording.hasError || recording.inFlightCalls > 0) return;
3857
5033
  if (!recording.journal) return;
@@ -3924,6 +5100,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
3924
5100
  if (metadata) {
3925
5101
  mergeExecutionMetadata(recording.execution, metadata);
3926
5102
  bindMetricsExecution(recording);
5103
+ bindExecutionMetricsIdentity2(recording);
5104
+ }
5105
+ if (executionMetrics && recording.executionMetrics) {
5106
+ const executionKey = executionTypeKey(recording.execution);
5107
+ bindExecutionMetricsIdentity2(recording);
5108
+ executionMetrics.finishExecution(recording.executionMetrics, {
5109
+ failed: executionOutcomeFailed({
5110
+ hasError: recording.hasError,
5111
+ runFailed: recording.runFailed === true,
5112
+ status: recording.execution.request?.status
5113
+ }),
5114
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
5115
+ startedNs: recording.startedAtNs,
5116
+ endedNs: recorderStartedAtNs
5117
+ });
3927
5118
  }
3928
5119
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3929
5120
  if (recording.runFailed && !recording.hasError) {
@@ -3994,6 +5185,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
3994
5185
  };
3995
5186
  if (identityComplete) tryAdmitLiveSession(recording);
3996
5187
  bindMetricsExecution(recording);
5188
+ if (executionMetrics) {
5189
+ recording.executionMetrics = executionMetrics.createState();
5190
+ bindExecutionMetricsIdentity2(recording);
5191
+ }
3997
5192
  stats.activeExecutions++;
3998
5193
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3999
5194
  liveRecordings.push(recording);
@@ -4046,6 +5241,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4046
5241
  mergeExecutionMetadata(recording.execution, nextMetadata);
4047
5242
  completeIdentityFromSnapshot(recording);
4048
5243
  bindMetricsExecution(recording);
5244
+ bindExecutionMetricsIdentity2(recording);
4049
5245
  } catch {
4050
5246
  }
4051
5247
  }
@@ -4062,18 +5258,53 @@ var createExecutionRecorder = (options, hooks = {}) => {
4062
5258
  }
4063
5259
  };
4064
5260
  const runPreparedFunctionFromStore = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5261
+ const duration = plan.excluded ? { selected: false, measure: false } : store ? planInvocationDuration(store.recording, plan, store.currentFunctionId) : { selected: false, measure: false };
5262
+ const startedNs = duration.measure ? tryCallClock3() : void 0;
4065
5263
  const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
4066
5264
  const executionHandle = store?.recording.metricsExecutionHandle;
4067
- const startedNs = startMetricsCall(functionMetrics, functionHandle, executionHandle);
5265
+ const metricsStart = startMetricsCall(functionMetrics, functionHandle, executionHandle, {
5266
+ measure: duration.selected,
5267
+ ...duration.selected ? { startedNs } : {}
5268
+ });
5269
+ const sharedClock = {
5270
+ start: startedNs,
5271
+ timed: startedNs !== void 0,
5272
+ selected: duration.selected
5273
+ };
5274
+ const applyRecorderEnd = (endedNs) => {
5275
+ if (endedNs === void 0) return;
5276
+ sharedClock.end = endedNs;
5277
+ sharedClock.applyEnd?.(endedNs);
5278
+ };
4068
5279
  const settle = (value, failed) => {
4069
- if (!functionMetrics || startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
5280
+ const pending = !failed && value instanceof Promise;
5281
+ if (!pending && sharedClock.timed && sharedClock.end === void 0) {
5282
+ sharedClock.end = tryCallClock3();
5283
+ }
5284
+ if (!functionMetrics || !metricsStart || functionHandle === void 0 || executionHandle === void 0) {
4070
5285
  return;
4071
5286
  }
5287
+ const timing = sharedClock.selected ? { startedNs: sharedClock.start, endedNs: sharedClock.end } : void 0;
4072
5288
  if (failed) {
4073
- finishMetricsCall(functionMetrics, functionHandle, executionHandle, startedNs, true);
5289
+ finishMetricsCall(functionMetrics, functionHandle, executionHandle, true, timing);
4074
5290
  return;
4075
5291
  }
4076
- completeMetricsResult(functionMetrics, functionHandle, executionHandle, startedNs, value);
5292
+ completeMetricsResult(
5293
+ functionMetrics,
5294
+ functionHandle,
5295
+ executionHandle,
5296
+ value,
5297
+ timing,
5298
+ (endedNs) => {
5299
+ if (endedNs !== void 0) {
5300
+ applyRecorderEnd(endedNs);
5301
+ return;
5302
+ }
5303
+ if (!sharedClock.selected && sharedClock.timed) {
5304
+ applyRecorderEnd(tryCallClock3());
5305
+ }
5306
+ }
5307
+ );
4077
5308
  };
4078
5309
  let startedCallback = false;
4079
5310
  try {
@@ -4085,7 +5316,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4085
5316
  startedCallback = true;
4086
5317
  return callback();
4087
5318
  },
4088
- omitValues
5319
+ omitValues,
5320
+ sharedClock
4089
5321
  );
4090
5322
  settle(result, false);
4091
5323
  return result;
@@ -4099,7 +5331,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4099
5331
  return result;
4100
5332
  }
4101
5333
  };
4102
- const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5334
+ const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues, sharedClock) {
4103
5335
  const omitCallValues = omitValues === true || plan.omitCallValues;
4104
5336
  if (!store) return callback();
4105
5337
  if (plan.disabled) {
@@ -4135,9 +5367,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4135
5367
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
4136
5368
  } catch {
4137
5369
  }
4138
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
5370
+ const timed = sharedClock.timed;
5371
+ const startedAtNs = sharedClock.start ?? 0n;
4139
5372
  if (group.observedCalls > capturedCallLimitFor(recording)) {
4140
- const startedAtNs2 = timed ? readCallClock() : 0n;
4141
5373
  try {
4142
5374
  const result = runStore(
4143
5375
  samplingStore(store, plan.functionId),
@@ -4145,23 +5377,48 @@ var createExecutionRecorder = (options, hooks = {}) => {
4145
5377
  return callback();
4146
5378
  }
4147
5379
  );
4148
- recordSuppressedCall(
4149
- recording,
4150
- group,
4151
- parentCallId,
4152
- startedAtNs2,
4153
- timed ? readCallClock() : 0n,
4154
- timed
4155
- );
5380
+ if (result instanceof Promise) {
5381
+ recordSuppressedCall(recording, group, parentCallId, startedAtNs, 0n, false);
5382
+ if (timed) {
5383
+ const suppressed = group.suppressed;
5384
+ sharedClock.applyEnd = (endedNs) => {
5385
+ if (endedNs === void 0 || recording.finished || !suppressed || group.suppressed !== suppressed) {
5386
+ return;
5387
+ }
5388
+ addSuppressedDuration(suppressed, startedAtNs, endedNs);
5389
+ };
5390
+ }
5391
+ } else {
5392
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5393
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5394
+ recordSuppressedCall(
5395
+ recording,
5396
+ group,
5397
+ parentCallId,
5398
+ startedAtNs,
5399
+ endedAtNs ?? 0n,
5400
+ endedAtNs !== void 0
5401
+ );
5402
+ }
4156
5403
  settleInFlight(recording);
4157
5404
  return result;
4158
5405
  } catch (error) {
4159
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs2, error, timed);
5406
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5407
+ captureCompletedThrow(
5408
+ recording,
5409
+ plan,
5410
+ args,
5411
+ parentCallId,
5412
+ startedAtNs,
5413
+ error,
5414
+ timed,
5415
+ void 0,
5416
+ sharedClock.end
5417
+ );
4160
5418
  settleInFlight(recording);
4161
5419
  throw error;
4162
5420
  }
4163
5421
  }
4164
- const startedAtNs = timed ? readCallClock() : 0n;
4165
5422
  if (!journal) {
4166
5423
  memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes);
4167
5424
  return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
@@ -4190,7 +5447,18 @@ var createExecutionRecorder = (options, hooks = {}) => {
4190
5447
  callback,
4191
5448
  captureSuccess,
4192
5449
  (error) => {
4193
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs, error, timed);
5450
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5451
+ captureCompletedThrow(
5452
+ recording,
5453
+ plan,
5454
+ args,
5455
+ parentCallId,
5456
+ startedAtNs,
5457
+ error,
5458
+ timed,
5459
+ void 0,
5460
+ sharedClock.end
5461
+ );
4194
5462
  settleInFlight(recording);
4195
5463
  }
4196
5464
  );
@@ -4210,7 +5478,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4210
5478
  });
4211
5479
  }
4212
5480
  const callId = ++recording.nextCallId;
4213
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
5481
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
4214
5482
  const capturedArgs = enterPayload(recording, omitCallValues, args);
4215
5483
  try {
4216
5484
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -4236,7 +5504,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4236
5504
  callback,
4237
5505
  (value) => {
4238
5506
  if (recording.journal) {
4239
- const endedAtNs = timed ? readCallClock() : void 0;
5507
+ const pending = value instanceof Promise;
5508
+ const endedAtNs = timed && !pending ? tryCallClock3() : void 0;
5509
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
4240
5510
  const returnValue = exitPayload(recording, omitCallValues, value);
4241
5511
  if (endedAtNs !== void 0) {
4242
5512
  recording.journal.finishCall(
@@ -4255,6 +5525,19 @@ var createExecutionRecorder = (options, hooks = {}) => {
4255
5525
  returnValue
4256
5526
  );
4257
5527
  }
5528
+ if (pending && timed) {
5529
+ const journal2 = recording.journal;
5530
+ sharedClock.applyEnd = (endedNs) => {
5531
+ if (endedNs === void 0 || recording.finished || recording.journal !== journal2) {
5532
+ return;
5533
+ }
5534
+ journal2.setCallTiming(
5535
+ callId,
5536
+ endedNs - recording.startedAtNs,
5537
+ endedNs - startedAtNs
5538
+ );
5539
+ };
5540
+ }
4258
5541
  stats.functionCallsCaptured++;
4259
5542
  }
4260
5543
  settleInFlight(recording);
@@ -4265,14 +5548,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
4265
5548
  return;
4266
5549
  }
4267
5550
  const capturedError = serializedError(recording, error, callId);
4268
- const endedAtNs = readCallClock();
4269
- recording.journal.finishCall(
4270
- KIND_THROW,
4271
- callId,
4272
- endedAtNs - recording.startedAtNs,
4273
- timed ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
4274
- capturedError.value
4275
- );
5551
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5552
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5553
+ if (endedAtNs !== void 0) {
5554
+ recording.journal.finishCall(
5555
+ KIND_THROW,
5556
+ callId,
5557
+ endedAtNs - recording.startedAtNs,
5558
+ endedAtNs - startedAtNs,
5559
+ capturedError.value
5560
+ );
5561
+ } else {
5562
+ recording.journal.finishCall(
5563
+ KIND_THROW,
5564
+ callId,
5565
+ TIMING_UNAVAILABLE,
5566
+ TIMING_UNAVAILABLE,
5567
+ capturedError.value
5568
+ );
5569
+ }
4276
5570
  stats.functionCallsCaptured++;
4277
5571
  capturedError.commit();
4278
5572
  settleInFlight(recording);
@@ -4301,21 +5595,24 @@ var createExecutionRecorder = (options, hooks = {}) => {
4301
5595
  this.group = group;
4302
5596
  this.captureDroppedThrow = captureDroppedThrow;
4303
5597
  this.callerClaimed = false;
5598
+ this.completedAtNs = void 0;
5599
+ this.metricsSelected = false;
4304
5600
  this.metricsOpen = false;
5601
+ this.metricsMeasure = false;
4305
5602
  this.metricsFailed = false;
4306
5603
  this.metricsFunctionHandle = 0;
4307
5604
  this.metricsExecutionHandle = 0;
4308
- this.metricsStartedNs = 0n;
5605
+ this.metricsStartedNs = void 0;
4309
5606
  }
4310
5607
  claimCaller() {
4311
- if (this.callerClaimed || !durationSamplingEnabled || !this.plan) return;
5608
+ if (this.callerClaimed || !trackCallers || !this.plan) return;
4312
5609
  if (this.activeStore !== this.parentStore) return;
4313
5610
  this.previousFunctionId = this.parentStore.currentFunctionId;
4314
5611
  this.parentStore.currentFunctionId = this.plan.functionId;
4315
5612
  this.callerClaimed = true;
4316
5613
  }
4317
5614
  reclaimCaller() {
4318
- if (!durationSamplingEnabled || !this.plan || this.activeStore !== this.parentStore) return;
5615
+ if (!trackCallers || !this.plan || this.activeStore !== this.parentStore) return;
4319
5616
  this.parentStore.currentFunctionId = this.plan.functionId;
4320
5617
  this.callerClaimed = true;
4321
5618
  }
@@ -4341,6 +5638,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4341
5638
  if (this.status === "failed") return;
4342
5639
  this.status = "failed";
4343
5640
  this.metricsFailed = true;
5641
+ if (this.timed && this.completedAtNs === void 0) {
5642
+ this.completedAtNs = tryCallClock3();
5643
+ }
4344
5644
  if (this.mode === "captured") writeCapturedThrow(this, error);
4345
5645
  else if (this.mode === "suppressed" && this.plan) {
4346
5646
  captureCompletedThrow(
@@ -4351,7 +5651,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4351
5651
  this.startedAtNs,
4352
5652
  error,
4353
5653
  this.timed,
4354
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5654
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5655
+ this.completedAtNs
4355
5656
  );
4356
5657
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
4357
5658
  captureCompletedThrow(
@@ -4362,25 +5663,28 @@ var createExecutionRecorder = (options, hooks = {}) => {
4362
5663
  this.startedAtNs,
4363
5664
  error,
4364
5665
  this.timed,
4365
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5666
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5667
+ this.completedAtNs
4366
5668
  );
4367
5669
  }
4368
5670
  } catch {
4369
5671
  }
4370
5672
  }
4371
5673
  end() {
4372
- let endedAtNs;
5674
+ let endedAtNs = this.completedAtNs;
5675
+ if (endedAtNs === void 0 && this.timed) {
5676
+ endedAtNs = tryCallClock3();
5677
+ this.completedAtNs = endedAtNs;
5678
+ }
4373
5679
  if (this.metricsOpen && functionMetrics) {
4374
5680
  this.metricsOpen = false;
4375
5681
  try {
4376
- endedAtNs = readCallClock();
4377
5682
  finishMetricsCall(
4378
5683
  functionMetrics,
4379
5684
  this.metricsFunctionHandle,
4380
5685
  this.metricsExecutionHandle,
4381
- this.metricsStartedNs,
4382
5686
  this.metricsFailed,
4383
- endedAtNs
5687
+ this.metricsMeasure ? { startedNs: this.metricsStartedNs, endedNs: endedAtNs } : void 0
4384
5688
  );
4385
5689
  } catch {
4386
5690
  }
@@ -4400,8 +5704,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4400
5704
  this.group,
4401
5705
  this.parentCallId,
4402
5706
  this.startedAtNs,
4403
- this.timed ? endedAtNs ?? readCallClock() : 0n,
4404
- this.timed
5707
+ endedAtNs ?? 0n,
5708
+ this.timed && endedAtNs !== void 0
4405
5709
  );
4406
5710
  } else if (this.mode === "dropped") {
4407
5711
  const droppedBefore = this.recording.journal?.dropped ?? 0;
@@ -4475,7 +5779,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4475
5779
  };
4476
5780
  const writeCapturedExit = (frame, value, completedAtNs) => {
4477
5781
  if (!frame.recording.journal) return;
4478
- const endedAtNs = frame.timed ? completedAtNs ?? readCallClock() : void 0;
5782
+ const endedAtNs = frame.timed ? completedAtNs : void 0;
4479
5783
  const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
4480
5784
  if (endedAtNs !== void 0) {
4481
5785
  frame.recording.journal.finishCall(
@@ -4498,37 +5802,47 @@ var createExecutionRecorder = (options, hooks = {}) => {
4498
5802
  };
4499
5803
  const writeCapturedThrow = (frame, error) => {
4500
5804
  if (!frame.recording.journal) return;
4501
- const endedAtNs = readCallClock();
5805
+ const endedAtNs = frame.timed ? frame.completedAtNs : void 0;
4502
5806
  const capturedError = serializedError(frame.recording, error, frame.callId);
4503
- frame.recording.journal.finishCall(
4504
- KIND_THROW,
4505
- frame.callId,
4506
- endedAtNs - frame.recording.startedAtNs,
4507
- frame.timed ? endedAtNs - frame.startedAtNs : TIMING_UNAVAILABLE,
4508
- capturedError.value
4509
- );
5807
+ if (endedAtNs !== void 0) {
5808
+ frame.recording.journal.finishCall(
5809
+ KIND_THROW,
5810
+ frame.callId,
5811
+ endedAtNs - frame.recording.startedAtNs,
5812
+ endedAtNs - frame.startedAtNs,
5813
+ capturedError.value
5814
+ );
5815
+ } else {
5816
+ frame.recording.journal.finishCall(
5817
+ KIND_THROW,
5818
+ frame.callId,
5819
+ TIMING_UNAVAILABLE,
5820
+ TIMING_UNAVAILABLE,
5821
+ capturedError.value
5822
+ );
5823
+ }
4510
5824
  stats.functionCallsCaptured++;
4511
5825
  capturedError.commit();
4512
5826
  };
4513
5827
  const armCallFrameMetrics = (frame, plan) => {
4514
5828
  if (!functionMetrics || plan.excluded) return;
4515
5829
  const functionHandle = internPreparedMetrics(functionMetrics, plan);
4516
- const reuseStart = frame.timed && frame.startedAtNs !== 0n ? frame.startedAtNs : void 0;
4517
- const startedNs = startMetricsCall(
5830
+ const started = startMetricsCall(
4518
5831
  functionMetrics,
4519
5832
  functionHandle,
4520
5833
  frame.recording.metricsExecutionHandle,
4521
- reuseStart
5834
+ frame.metricsSelected ? { measure: true, startedNs: frame.timed ? frame.startedAtNs : void 0 } : { measure: false }
4522
5835
  );
4523
- if (startedNs === void 0 || functionHandle === void 0) return;
5836
+ if (!started || functionHandle === void 0) return;
4524
5837
  const executionHandle = frame.recording.metricsExecutionHandle;
4525
5838
  if (executionHandle === void 0) return;
4526
5839
  frame.metricsOpen = true;
5840
+ frame.metricsMeasure = started.measure;
4527
5841
  frame.metricsFunctionHandle = functionHandle;
4528
5842
  frame.metricsExecutionHandle = executionHandle;
4529
- frame.metricsStartedNs = startedNs;
5843
+ frame.metricsStartedNs = started.startedNs;
4530
5844
  };
4531
- const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow) => {
5845
+ const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected) => {
4532
5846
  const frame = new CallFrame(
4533
5847
  mode,
4534
5848
  recording,
@@ -4544,6 +5858,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4544
5858
  group,
4545
5859
  captureDroppedThrow
4546
5860
  );
5861
+ frame.metricsSelected = selected;
4547
5862
  frame.claimCaller();
4548
5863
  enterStore(frame, parentStore);
4549
5864
  armCallFrameMetrics(frame, plan);
@@ -4557,6 +5872,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4557
5872
  }
4558
5873
  if (store.recording.finished) {
4559
5874
  if (!store.recording.budgetExpired && !store.recording.evicted) return noopHandle2;
5875
+ const duration2 = planInvocationDuration(store.recording, plan, store.currentFunctionId);
5876
+ const start2 = invocationStart(duration2.measure);
4560
5877
  const expiredStore = { recording: store.recording };
4561
5878
  const expired = new CallFrame(
4562
5879
  "expired",
@@ -4567,12 +5884,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
4567
5884
  EMPTY_ARGS,
4568
5885
  false,
4569
5886
  void 0,
4570
- 0n,
4571
- true,
5887
+ start2.startedAtNs,
5888
+ start2.timed,
4572
5889
  0,
4573
5890
  void 0,
4574
5891
  false
4575
5892
  );
5893
+ expired.metricsSelected = duration2.selected;
4576
5894
  armCallFrameMetrics(expired, plan);
4577
5895
  return expired;
4578
5896
  }
@@ -4582,6 +5900,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4582
5900
  const parentCallId = store.currentCallId;
4583
5901
  if (skipCapture(store, plan)) {
4584
5902
  stats.functionCallsExcluded++;
5903
+ const excludedDuration = plan.excluded ? { selected: false, measure: false } : planInvocationDuration(recording, plan, store.currentFunctionId);
5904
+ const start2 = invocationStart(excludedDuration.measure);
4585
5905
  const excludedStore = { ...store, suppressCapture: true };
4586
5906
  const frame = new CallFrame(
4587
5907
  "excluded",
@@ -4592,12 +5912,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
4592
5912
  EMPTY_ARGS,
4593
5913
  false,
4594
5914
  void 0,
4595
- 0n,
4596
- true,
5915
+ start2.startedAtNs,
5916
+ start2.timed,
4597
5917
  0,
4598
5918
  void 0,
4599
5919
  false
4600
5920
  );
5921
+ frame.metricsSelected = excludedDuration.selected;
4601
5922
  enterStore(frame, excludedStore);
4602
5923
  armCallFrameMetrics(frame, plan);
4603
5924
  return frame;
@@ -4610,8 +5931,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
4610
5931
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
4611
5932
  } catch {
4612
5933
  }
4613
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
4614
- const startedAtNs = timed ? readCallClock() : 0n;
5934
+ const duration = planInvocationDuration(recording, plan, store.currentFunctionId);
5935
+ const start = invocationStart(duration.measure);
5936
+ const timed = start.timed;
5937
+ const startedAtNs = start.startedAtNs;
4615
5938
  const parentStore = store;
4616
5939
  const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
4617
5940
  if (group.observedCalls > capturedCallLimitFor(recording)) {
@@ -4626,7 +5949,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4626
5949
  startedAtNs,
4627
5950
  timed,
4628
5951
  group,
4629
- false
5952
+ false,
5953
+ duration.selected
4630
5954
  );
4631
5955
  }
4632
5956
  if (!journal) {
@@ -4642,7 +5966,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4642
5966
  startedAtNs,
4643
5967
  timed,
4644
5968
  group,
4645
- false
5969
+ false,
5970
+ duration.selected
4646
5971
  );
4647
5972
  }
4648
5973
  if (!journal.canStartCall()) {
@@ -4657,7 +5982,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4657
5982
  startedAtNs,
4658
5983
  timed,
4659
5984
  group,
4660
- true
5985
+ true,
5986
+ duration.selected
4661
5987
  );
4662
5988
  }
4663
5989
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
@@ -4672,11 +5998,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
4672
5998
  startedAtNs,
4673
5999
  timed,
4674
6000
  group,
4675
- false
6001
+ false,
6002
+ duration.selected
4676
6003
  );
4677
6004
  }
4678
6005
  const callId = ++recording.nextCallId;
4679
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
6006
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
4680
6007
  const capturedArgs = enterPayload(recording, omitCallValues, args);
4681
6008
  try {
4682
6009
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -4693,7 +6020,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4693
6020
  startedAtNs,
4694
6021
  timed,
4695
6022
  group,
4696
- false
6023
+ false,
6024
+ duration.selected
4697
6025
  );
4698
6026
  }
4699
6027
  const callStore = callStoreFor(store, plan.functionId, callId);
@@ -4712,6 +6040,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4712
6040
  group,
4713
6041
  false
4714
6042
  );
6043
+ captured.metricsSelected = duration.selected;
4715
6044
  enterStore(captured, callStore);
4716
6045
  armCallFrameMetrics(captured, plan);
4717
6046
  return captured;
@@ -4781,7 +6110,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4781
6110
  enterPreparedFunction,
4782
6111
  trace,
4783
6112
  close: () => {
4784
- durationSamples?.stop();
6113
+ durationSampler?.stop();
4785
6114
  },
4786
6115
  getStats: () => ({
4787
6116
  ...stats,
@@ -4838,14 +6167,14 @@ var installAutomaticExecutionRuntime = (execution) => {
4838
6167
  // src/execution-recorder/bind-adaptive-recorder.ts
4839
6168
  import {
4840
6169
  resolveClientActivation,
4841
- resolveEndpointUrls as resolveEndpointUrls2
6170
+ resolveEndpointUrls as resolveEndpointUrls3
4842
6171
  } from "@rasputin-ai/core";
4843
6172
 
4844
6173
  // src/execution-recorder/execution-recording-sync.ts
4845
6174
  import {
4846
6175
  copyRedactKeys,
4847
- defaultIngestFetch,
4848
- encodeJsonRequestBodyAsync,
6176
+ defaultIngestFetch as defaultIngestFetch2,
6177
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
4849
6178
  MAX_REDACT_KEYS
4850
6179
  } from "@rasputin-ai/core";
4851
6180
 
@@ -5028,7 +6357,7 @@ var MAX_CACHE_ENTRIES = 1024;
5028
6357
  var MAX_PENDING_NOTIFIES = 32;
5029
6358
  var MAX_PENDING_TYPES = 64;
5030
6359
  var DEFAULT_POLL_INTERVAL_MS = 1e4;
5031
- var REQUEST_TIMEOUT_MS = 5e3;
6360
+ var REQUEST_TIMEOUT_MS2 = 5e3;
5032
6361
  var MAX_RETRIES = 5;
5033
6362
  var MAX_POLL_JITTER_MS = 2e3;
5034
6363
  var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
@@ -5043,7 +6372,7 @@ var classifyHttpFailure = (status) => {
5043
6372
  if (status >= 500) return "server_error";
5044
6373
  return "non_retryable_http";
5045
6374
  };
5046
- var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
6375
+ var backoffMs2 = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
5047
6376
  var abortFrom = (parent, child) => {
5048
6377
  const onAbort = () => child.abort();
5049
6378
  parent.addEventListener("abort", onAbort, { once: true });
@@ -5053,7 +6382,7 @@ var abortFrom = (parent, child) => {
5053
6382
  var createExecutionRecordingCoordinator = (options) => {
5054
6383
  const environment = options.environment;
5055
6384
  const nowMs = () => options.nowMs?.() ?? Date.now();
5056
- const fetchFn = options.fetch ?? defaultIngestFetch();
6385
+ const fetchFn = options.fetch ?? defaultIngestFetch2();
5057
6386
  const instanceId = crypto.randomUUID();
5058
6387
  const startedAt = /* @__PURE__ */ new Date();
5059
6388
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
@@ -5190,7 +6519,7 @@ var createExecutionRecordingCoordinator = (options) => {
5190
6519
  };
5191
6520
  const withRequestTimeout = async (signal, run) => {
5192
6521
  const request = new AbortController();
5193
- const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS);
6522
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
5194
6523
  timer.unref?.();
5195
6524
  const stopParent = abortFrom(signal, request);
5196
6525
  const stopCancel = abortFrom(cancelWork.signal, request);
@@ -5250,7 +6579,7 @@ var createExecutionRecordingCoordinator = (options) => {
5250
6579
  notifyFailures++;
5251
6580
  return false;
5252
6581
  }
5253
- await wait(backoffMs(attempt), signal);
6582
+ await wait(backoffMs2(attempt), signal);
5254
6583
  } catch (error) {
5255
6584
  if (signal.aborted || error instanceof Error && error.name === "AbortError") {
5256
6585
  rememberFailure("aborted");
@@ -5261,7 +6590,7 @@ var createExecutionRecordingCoordinator = (options) => {
5261
6590
  notifyFailures++;
5262
6591
  return false;
5263
6592
  }
5264
- await wait(backoffMs(attempt), signal);
6593
+ await wait(backoffMs2(attempt), signal);
5265
6594
  }
5266
6595
  }
5267
6596
  return false;
@@ -5459,7 +6788,7 @@ var createExecutionRecordingCoordinator = (options) => {
5459
6788
  if (combined.aborted) return false;
5460
6789
  let encoded;
5461
6790
  try {
5462
- encoded = await encodeJsonRequestBodyAsync(
6791
+ encoded = await encodeJsonRequestBodyAsync2(
5463
6792
  {
5464
6793
  instance_id: instanceId,
5465
6794
  recordings: batch.map((item) => ({
@@ -5510,7 +6839,7 @@ var createExecutionRecordingCoordinator = (options) => {
5510
6839
  rememberFailure(kind);
5511
6840
  if (kind === "non_retryable_http") return true;
5512
6841
  if (attempt === MAX_RETRIES) return false;
5513
- await wait(backoffMs(attempt), combined);
6842
+ await wait(backoffMs2(attempt), combined);
5514
6843
  } catch (error) {
5515
6844
  if (combined.aborted || error instanceof Error && error.name === "AbortError") {
5516
6845
  rememberFailure("aborted");
@@ -5518,7 +6847,7 @@ var createExecutionRecordingCoordinator = (options) => {
5518
6847
  }
5519
6848
  rememberFailure("network_error");
5520
6849
  if (attempt === MAX_RETRIES) return false;
5521
- await wait(backoffMs(attempt), combined);
6850
+ await wait(backoffMs2(attempt), combined);
5522
6851
  }
5523
6852
  }
5524
6853
  return false;
@@ -5692,9 +7021,9 @@ var bindAdaptiveRecorder = (input) => {
5692
7021
  const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
5693
7022
  environment: activation.environment,
5694
7023
  ingestToken: activation.ingestToken,
5695
- activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5696
- syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5697
- recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
7024
+ activateUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingActivateUrl,
7025
+ syncUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingSyncUrl,
7026
+ recordingsUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingRecordingsUrl,
5698
7027
  sdkName: input.sdkName,
5699
7028
  sdkVersion: input.sdkVersion,
5700
7029
  release: activation.release,
@@ -5714,6 +7043,8 @@ var bindAdaptiveRecorder = (input) => {
5714
7043
  recorderHooks.onSessionRecording = coordinator.enqueueRecording;
5715
7044
  }
5716
7045
  if (input.functionMetrics) recorderHooks.functionMetrics = input.functionMetrics;
7046
+ if (input.executionMetrics) recorderHooks.executionMetrics = input.executionMetrics;
7047
+ if (input.durationSampler) recorderHooks.durationSampler = input.durationSampler;
5717
7048
  const runtime = createExecutionRecorder(
5718
7049
  { ...options, enabled: input.recorderEnabled },
5719
7050
  recorderHooks
@@ -5722,34 +7053,35 @@ var bindAdaptiveRecorder = (input) => {
5722
7053
  };
5723
7054
 
5724
7055
  // src/function-metrics/bind-function-metrics.ts
5725
- import { randomUUID as randomUUID2 } from "node:crypto";
7056
+ import { randomUUID as randomUUID4 } from "node:crypto";
5726
7057
  import {
5727
- defaultIngestFetch as defaultIngestFetch2,
5728
- resolveEndpointUrls as resolveEndpointUrls3
7058
+ defaultIngestFetch as defaultIngestFetch3,
7059
+ resolveEndpointUrls as resolveEndpointUrls4
5729
7060
  } from "@rasputin-ai/core";
5730
7061
 
5731
7062
  // src/function-metrics/function-metrics-collector.ts
5732
7063
  import {
5733
- durationHistogramBucket,
5734
- FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
5735
- FUNCTION_METRICS_MAX_ACTIVE_SERIES,
5736
- FUNCTION_METRICS_MAX_BUFFERED_MS,
5737
- FUNCTION_METRICS_MAX_EXECUTION_TYPES,
7064
+ durationHistogramBucket as durationHistogramBucket2,
7065
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT as FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2,
7066
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES as FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7067
+ FUNCTION_METRICS_MAX_BUFFERED_MS as FUNCTION_METRICS_MAX_BUFFERED_MS2,
7068
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES as FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
5738
7069
  FUNCTION_METRICS_MAX_FUNCTIONS,
5739
- FUNCTION_METRICS_MAX_MINUTE_ROWS,
5740
- FUNCTION_METRICS_MAX_STATE_BYTES,
5741
- FUNCTION_METRICS_MINUTE_MS,
7070
+ FUNCTION_METRICS_MAX_MINUTE_ROWS as FUNCTION_METRICS_MAX_MINUTE_ROWS2,
7071
+ FUNCTION_METRICS_MAX_STATE_BYTES as FUNCTION_METRICS_MAX_STATE_BYTES2,
7072
+ FUNCTION_METRICS_MEASUREMENT_FORMAT as FUNCTION_METRICS_MEASUREMENT_FORMAT2,
7073
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS3,
7074
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT as FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2,
5742
7075
  functionIdentityKey,
5743
- isCanonicalFunctionMetricsExecutionKey
7076
+ isCanonicalFunctionMetricsExecutionKey as isCanonicalFunctionMetricsExecutionKey2
5744
7077
  } from "@rasputin-ai/core";
5745
7078
 
5746
7079
  // src/function-metrics/function-metrics-batches.ts
5747
- import { randomUUID } from "node:crypto";
7080
+ import { randomUUID as randomUUID3 } from "node:crypto";
5748
7081
  import {
5749
- FUNCTION_METRICS_MEASUREMENT_FORMAT,
5750
7082
  FUNCTION_METRICS_SCHEMA_VERSION
5751
7083
  } from "@rasputin-ai/core";
5752
- var emptyCoverage = (buckets) => ({
7084
+ var emptyCoverage3 = (buckets) => ({
5753
7085
  covered_bucket_starts: buckets,
5754
7086
  skipped_unresolved_execution_type: 0,
5755
7087
  dropped_active_series: 0,
@@ -5758,8 +7090,8 @@ var emptyCoverage = (buckets) => ({
5758
7090
  dropped_late_completion: 0,
5759
7091
  dropped_unexportable: 0
5760
7092
  });
5761
- var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
5762
- var sparseHistogram = (histogram) => {
7093
+ var bucketStart2 = (minute) => new Date(minute * 6e4).toISOString();
7094
+ var sparseHistogram2 = (histogram) => {
5763
7095
  const cells = [];
5764
7096
  for (let index = 0; index < histogram.length; index += 1) {
5765
7097
  const count = histogram[index] ?? 0;
@@ -5767,10 +7099,10 @@ var sparseHistogram = (histogram) => {
5767
7099
  }
5768
7100
  return cells;
5769
7101
  };
5770
- var toMinute = (row, functionIndex, executionTypeIndex) => ({
7102
+ var toMinute2 = (row, functionIndex, executionTypeIndex) => ({
5771
7103
  function_index: functionIndex,
5772
7104
  execution_type_index: executionTypeIndex,
5773
- bucket_start: bucketStart(row.minute),
7105
+ bucket_start: bucketStart2(row.minute),
5774
7106
  started_calls: row.series.started,
5775
7107
  completed_calls: row.series.completed,
5776
7108
  failed_calls: row.series.failed,
@@ -5778,7 +7110,7 @@ var toMinute = (row, functionIndex, executionTypeIndex) => ({
5778
7110
  duration_sample_sum_us: row.series.sampleSumUs,
5779
7111
  duration_sample_min_us: row.series.sampleMinUs,
5780
7112
  duration_sample_max_us: row.series.sampleMaxUs,
5781
- duration_histogram: sparseHistogram(row.series.histogram),
7113
+ duration_histogram: sparseHistogram2(row.series.histogram),
5782
7114
  invalid_timing_count: row.series.invalidTiming
5783
7115
  });
5784
7116
  var rowsFromQueue = (queued) => {
@@ -5828,7 +7160,7 @@ var chunkRows = (rows, maxFunctions, maxExecutionTypes, maxMinuteRows) => {
5828
7160
  flush();
5829
7161
  return chunks;
5830
7162
  };
5831
- var batchForChunk = (draft, rows, coverage) => {
7163
+ var batchForChunk2 = (draft, rows, coverage) => {
5832
7164
  const functionIndexes = /* @__PURE__ */ new Map();
5833
7165
  const executionIndexes = /* @__PURE__ */ new Map();
5834
7166
  const functions = [];
@@ -5851,12 +7183,12 @@ var batchForChunk = (draft, rows, coverage) => {
5851
7183
  executionIndexes.set(row.executionHandle, executionTypeIndex);
5852
7184
  executionTypes.push({ execution_key: executionKey });
5853
7185
  }
5854
- minutes.push(toMinute(row, functionIndex, executionTypeIndex));
7186
+ minutes.push(toMinute2(row, functionIndex, executionTypeIndex));
5855
7187
  }
5856
7188
  const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
5857
7189
  return {
5858
7190
  schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5859
- measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
7191
+ measurement_format: draft.measurementFormat,
5860
7192
  producer_id: draft.producerId,
5861
7193
  batch_id: draft.batchId(),
5862
7194
  environment: draft.environment,
@@ -5877,7 +7209,7 @@ var functionMetricsBatchesFromQueue = (draft) => {
5877
7209
  return [
5878
7210
  {
5879
7211
  schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5880
- measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
7212
+ measurement_format: draft.measurementFormat,
5881
7213
  producer_id: draft.producerId,
5882
7214
  batch_id: draft.batchId(),
5883
7215
  environment: draft.environment,
@@ -5891,29 +7223,29 @@ var functionMetricsBatchesFromQueue = (draft) => {
5891
7223
  }
5892
7224
  const chunks = chunkRows(rows, draft.maxFunctions, draft.maxExecutionTypes, draft.maxMinuteRows);
5893
7225
  return chunks.map(
5894
- (chunk, index) => batchForChunk(draft, chunk, index === 0 ? draft.coverage : emptyCoverage([]))
7226
+ (chunk, index) => batchForChunk2(draft, chunk, index === 0 ? draft.coverage : emptyCoverage3([]))
5895
7227
  );
5896
7228
  };
5897
- var newFunctionMetricsBatchId = () => randomUUID();
7229
+ var newFunctionMetricsBatchId = () => randomUUID3();
5898
7230
 
5899
7231
  // src/function-metrics/function-metrics-collector.ts
5900
- var SERIES_BYTES = 256;
5901
- var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
7232
+ var SERIES_BYTES2 = 256;
7233
+ var HISTOGRAM_BYTES2 = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2 * 4;
5902
7234
  var DECLARATION_BYTES = 1024;
5903
- var MAX_ELAPSED_NS = BigInt(Number.MAX_SAFE_INTEGER);
5904
- var defaultLimits = () => ({
5905
- maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES,
5906
- maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES,
5907
- maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS / FUNCTION_METRICS_MINUTE_MS,
7235
+ var MAX_ELAPSED_NS2 = BigInt(Number.MAX_SAFE_INTEGER);
7236
+ var defaultLimits2 = () => ({
7237
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7238
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES2,
7239
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS2 / FUNCTION_METRICS_MINUTE_MS3,
5908
7240
  maxFunctions: FUNCTION_METRICS_MAX_FUNCTIONS,
5909
- maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
5910
- maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
7241
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
7242
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS2
5911
7243
  });
5912
- var defaultClock = () => ({
7244
+ var defaultClock2 = () => ({
5913
7245
  monotonicNs: () => process.hrtime.bigint(),
5914
7246
  wallTimeMs: () => Date.now()
5915
7247
  });
5916
- var emptyCoverage2 = () => ({
7248
+ var emptyCoverage4 = () => ({
5917
7249
  covered_bucket_starts: [],
5918
7250
  skipped_unresolved_execution_type: 0,
5919
7251
  dropped_active_series: 0,
@@ -5922,23 +7254,23 @@ var emptyCoverage2 = () => ({
5922
7254
  dropped_late_completion: 0,
5923
7255
  dropped_unexportable: 0
5924
7256
  });
5925
- var note = (coverage, counter, amount = 1) => {
7257
+ var note2 = (coverage, counter, amount = 1) => {
5926
7258
  const next = coverage[counter] + amount;
5927
7259
  coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
5928
7260
  };
5929
- var countSeries = (table) => {
7261
+ var countSeries2 = (table) => {
5930
7262
  let count = 0;
5931
7263
  for (const byExecution of table.values()) count += byExecution.size;
5932
7264
  return count;
5933
7265
  };
5934
- var tableBytes = (table) => {
7266
+ var tableBytes2 = (table) => {
5935
7267
  let bytes = 0;
5936
7268
  for (const byExecution of table.values()) {
5937
7269
  for (const series of byExecution.values()) bytes += series.bytes;
5938
7270
  }
5939
7271
  return bytes;
5940
7272
  };
5941
- var discardedMarks = (table) => {
7273
+ var discardedMarks2 = (table) => {
5942
7274
  let marks = 0;
5943
7275
  for (const byExecution of table.values()) {
5944
7276
  for (const series of byExecution.values()) {
@@ -5948,12 +7280,12 @@ var discardedMarks = (table) => {
5948
7280
  }
5949
7281
  return marks;
5950
7282
  };
5951
- var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
5952
- var copySeries = (series) => ({
7283
+ var seriesHasMarks2 = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
7284
+ var copySeries2 = (series) => ({
5953
7285
  ...series,
5954
7286
  histogram: series.histogram.slice()
5955
7287
  });
5956
- var resetSeries = (series) => {
7288
+ var resetSeries2 = (series) => {
5957
7289
  series.started = 0;
5958
7290
  series.completed = 0;
5959
7291
  series.failed = 0;
@@ -5964,13 +7296,13 @@ var resetSeries = (series) => {
5964
7296
  series.invalidTiming = 0;
5965
7297
  series.histogram.fill(0);
5966
7298
  };
5967
- var snapshotAndReset = (table) => {
7299
+ var snapshotAndReset2 = (table) => {
5968
7300
  const snapshot = /* @__PURE__ */ new Map();
5969
7301
  for (const [functionHandle, byExecution] of table) {
5970
7302
  const copied = /* @__PURE__ */ new Map();
5971
7303
  for (const [executionHandle, series] of byExecution) {
5972
- if (seriesHasMarks(series)) copied.set(executionHandle, copySeries(series));
5973
- resetSeries(series);
7304
+ if (seriesHasMarks2(series)) copied.set(executionHandle, copySeries2(series));
7305
+ resetSeries2(series);
5974
7306
  }
5975
7307
  if (copied.size > 0) snapshot.set(functionHandle, copied);
5976
7308
  }
@@ -5985,10 +7317,11 @@ var declarationAccepted = (declaration) => {
5985
7317
  return true;
5986
7318
  };
5987
7319
  var createFunctionMetricsCollector = (options) => {
5988
- const limits = { ...defaultLimits(), ...options.limits };
5989
- const clock = options.clock ?? defaultClock();
7320
+ const limits = { ...defaultLimits2(), ...options.limits };
7321
+ const clock = options.clock ?? defaultClock2();
5990
7322
  const batchId = options.batchId ?? newFunctionMetricsBatchId;
5991
- const coverage = emptyCoverage2();
7323
+ const measurementFormat = options.sampledMeasurementFormat ? FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2 : FUNCTION_METRICS_MEASUREMENT_FORMAT2;
7324
+ const coverage = emptyCoverage4();
5992
7325
  const functions = [];
5993
7326
  const functionHandleByRuntimeId = /* @__PURE__ */ new Map();
5994
7327
  const executionKeys = [];
@@ -6002,7 +7335,7 @@ var createFunctionMetricsCollector = (options) => {
6002
7335
  let sealed = false;
6003
7336
  const reserve = (bytes) => {
6004
7337
  if (stateBytes > limits.maxStateBytes - bytes) {
6005
- note(coverage, "dropped_byte_budget");
7338
+ note2(coverage, "dropped_byte_budget");
6006
7339
  return false;
6007
7340
  }
6008
7341
  stateBytes += bytes;
@@ -6010,17 +7343,17 @@ var createFunctionMetricsCollector = (options) => {
6010
7343
  };
6011
7344
  const internDeclaration = (declaration) => {
6012
7345
  if (!declaration) {
6013
- note(coverage, "dropped_unexportable");
7346
+ note2(coverage, "dropped_unexportable");
6014
7347
  return void 0;
6015
7348
  }
6016
7349
  const existing = functionHandleByRuntimeId.get(declaration.runtime_id);
6017
7350
  if (existing !== void 0) return existing;
6018
7351
  if (!declarationAccepted(declaration)) {
6019
- note(coverage, "dropped_unexportable");
7352
+ note2(coverage, "dropped_unexportable");
6020
7353
  return void 0;
6021
7354
  }
6022
7355
  if (functions.length >= limits.maxFunctions) {
6023
- note(coverage, "dropped_unexportable");
7356
+ note2(coverage, "dropped_unexportable");
6024
7357
  return void 0;
6025
7358
  }
6026
7359
  if (!reserve(DECLARATION_BYTES + declaration.runtime_id.length)) return void 0;
@@ -6030,11 +7363,11 @@ var createFunctionMetricsCollector = (options) => {
6030
7363
  return handle;
6031
7364
  };
6032
7365
  const internExecutionKey = (key) => {
6033
- if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
7366
+ if (!key || !isCanonicalFunctionMetricsExecutionKey2(key)) return void 0;
6034
7367
  const existing = executionHandleByKey.get(key);
6035
7368
  if (existing !== void 0) return existing;
6036
7369
  if (executionKeys.length >= limits.maxExecutionTypes) {
6037
- note(coverage, "dropped_unexportable");
7370
+ note2(coverage, "dropped_unexportable");
6038
7371
  return void 0;
6039
7372
  }
6040
7373
  if (!reserve(key.length)) return void 0;
@@ -6057,10 +7390,10 @@ var createFunctionMetricsCollector = (options) => {
6057
7390
  const existing = byExecution.get(executionHandle);
6058
7391
  if (existing) return existing;
6059
7392
  if (activeSeries >= limits.maxActiveSeries) {
6060
- note(coverage, "dropped_active_series");
7393
+ note2(coverage, "dropped_active_series");
6061
7394
  return void 0;
6062
7395
  }
6063
- if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
7396
+ if (!reserve(SERIES_BYTES2 + HISTOGRAM_BYTES2)) return void 0;
6064
7397
  const series = {
6065
7398
  started: 0,
6066
7399
  completed: 0,
@@ -6070,15 +7403,15 @@ var createFunctionMetricsCollector = (options) => {
6070
7403
  sampleMinUs: null,
6071
7404
  sampleMaxUs: null,
6072
7405
  invalidTiming: 0,
6073
- histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
6074
- bytes: SERIES_BYTES + HISTOGRAM_BYTES
7406
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2),
7407
+ bytes: SERIES_BYTES2 + HISTOGRAM_BYTES2
6075
7408
  };
6076
7409
  byExecution.set(executionHandle, series);
6077
7410
  activeSeries += 1;
6078
7411
  return series;
6079
7412
  };
6080
7413
  const appendQueue = (entry) => {
6081
- if (discardedMarks(entry.series) === 0) {
7414
+ if (discardedMarks2(entry.series) === 0) {
6082
7415
  stateBytes -= entry.bytes;
6083
7416
  if (stateBytes < 0) stateBytes = 0;
6084
7417
  return;
@@ -6090,14 +7423,14 @@ var createFunctionMetricsCollector = (options) => {
6090
7423
  if (!dropped) break;
6091
7424
  stateBytes -= dropped.bytes;
6092
7425
  if (stateBytes < 0) stateBytes = 0;
6093
- note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
7426
+ note2(coverage, "dropped_queue_budget", discardedMarks2(dropped.series));
6094
7427
  }
6095
7428
  };
6096
7429
  const closeMinute = (minute, table) => {
6097
7430
  active.delete(minute);
6098
- activeSeries -= countSeries(table);
7431
+ activeSeries -= countSeries2(table);
6099
7432
  if (minute > lastClosedMinute) lastClosedMinute = minute;
6100
- appendQueue({ minute, series: table, bytes: tableBytes(table) });
7433
+ appendQueue({ minute, series: table, bytes: tableBytes2(table) });
6101
7434
  };
6102
7435
  const rotate = (currentMinute) => {
6103
7436
  for (const minute of [...active.keys()]) {
@@ -6115,7 +7448,7 @@ var createFunctionMetricsCollector = (options) => {
6115
7448
  };
6116
7449
  const snapshotActive = () => {
6117
7450
  for (const [minute, table] of active) {
6118
- appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
7451
+ appendQueue({ minute, series: snapshotAndReset2(table), bytes: 0 });
6119
7452
  }
6120
7453
  };
6121
7454
  const moveAllActive = () => {
@@ -6139,14 +7472,34 @@ var createFunctionMetricsCollector = (options) => {
6139
7472
  series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
6140
7473
  return true;
6141
7474
  };
7475
+ const rememberOutcome = (series, failed) => {
7476
+ const completed = series.completed + 1;
7477
+ const failures = series.failed + (failed ? 1 : 0);
7478
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
7479
+ series.completed = completed;
7480
+ series.failed = failures;
7481
+ return true;
7482
+ };
7483
+ const rememberInvalidTiming = (series, failed) => {
7484
+ const completed = series.completed + 1;
7485
+ const failures = series.failed + (failed ? 1 : 0);
7486
+ const invalidTiming = series.invalidTiming + 1;
7487
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures) || !Number.isSafeInteger(invalidTiming)) {
7488
+ return false;
7489
+ }
7490
+ series.completed = completed;
7491
+ series.failed = failures;
7492
+ series.invalidTiming = invalidTiming;
7493
+ return true;
7494
+ };
6142
7495
  const rememberCompletion = (series, startedNs, failed, endedNs) => {
6143
7496
  const completed = series.completed + 1;
6144
7497
  const failures = series.failed + (failed ? 1 : 0);
6145
7498
  if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
6146
7499
  const elapsed = endedNs - startedNs;
6147
7500
  const durationUs = Number(elapsed) / 1e3;
6148
- const placed = durationHistogramBucket(durationUs);
6149
- const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
7501
+ const placed = durationHistogramBucket2(durationUs);
7502
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS2;
6150
7503
  const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
6151
7504
  if (!sampled) {
6152
7505
  const invalidTiming = series.invalidTiming + 1;
@@ -6157,73 +7510,99 @@ var createFunctionMetricsCollector = (options) => {
6157
7510
  series.failed = failures;
6158
7511
  return true;
6159
7512
  };
6160
- const startCall = (functionHandle, executionHandle, startedNs) => {
7513
+ const startCall = (functionHandle, executionHandle, callOptions) => {
6161
7514
  if (sealed) {
6162
- note(coverage, "dropped_unexportable");
7515
+ note2(coverage, "dropped_unexportable");
6163
7516
  return void 0;
6164
7517
  }
6165
7518
  if (executionHandle === void 0) {
6166
- note(coverage, "skipped_unresolved_execution_type");
7519
+ note2(coverage, "skipped_unresolved_execution_type");
6167
7520
  return void 0;
6168
7521
  }
6169
- const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
7522
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
6170
7523
  rotateIfNeeded(minute);
6171
7524
  if (minute <= lastClosedMinute) {
6172
- note(coverage, "dropped_late_completion");
7525
+ note2(coverage, "dropped_late_completion");
6173
7526
  return void 0;
6174
7527
  }
6175
7528
  const series = ensureSeries(minute, functionHandle, executionHandle);
6176
7529
  if (!series) return void 0;
6177
7530
  const started = series.started + 1;
6178
7531
  if (!Number.isSafeInteger(started)) {
6179
- note(coverage, "dropped_unexportable");
7532
+ note2(coverage, "dropped_unexportable");
6180
7533
  return void 0;
6181
7534
  }
6182
7535
  series.started = started;
6183
- return startedNs ?? clock.monotonicNs();
7536
+ const measure = callOptions?.measure !== false;
7537
+ if (!measure) return { measure: false };
7538
+ if (callOptions && "startedNs" in callOptions) {
7539
+ return { measure: true, startedNs: callOptions.startedNs };
7540
+ }
7541
+ try {
7542
+ return { measure: true, startedNs: clock.monotonicNs() };
7543
+ } catch {
7544
+ return { measure: true };
7545
+ }
6184
7546
  };
6185
- const finishCall = (functionHandle, executionHandle, startedNs, failed, endedNs) => {
7547
+ const finishCall = (functionHandle, executionHandle, failed, timing) => {
6186
7548
  if (sealed) {
6187
- note(coverage, "dropped_late_completion");
7549
+ note2(coverage, "dropped_late_completion");
6188
7550
  return;
6189
7551
  }
6190
- const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
7552
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
6191
7553
  rotateIfNeeded(minute);
6192
7554
  if (minute <= lastClosedMinute && !active.has(minute)) {
6193
- note(coverage, "dropped_late_completion");
7555
+ note2(coverage, "dropped_late_completion");
6194
7556
  return;
6195
7557
  }
6196
7558
  const series = ensureSeries(minute, functionHandle, executionHandle);
6197
7559
  if (!series) return;
6198
- const remembered = rememberCompletion(
6199
- series,
6200
- startedNs,
6201
- failed,
6202
- endedNs ?? clock.monotonicNs()
6203
- );
6204
- if (!remembered) note(coverage, "dropped_unexportable");
7560
+ const remembered = timing === void 0 ? rememberOutcome(series, failed) : timing.startedNs !== void 0 && timing.endedNs !== void 0 ? rememberCompletion(series, timing.startedNs, failed, timing.endedNs) : rememberInvalidTiming(series, failed);
7561
+ if (!remembered) note2(coverage, "dropped_unexportable");
6205
7562
  };
6206
7563
  const beginCall = (input) => {
6207
7564
  const functionHandle = internDeclaration(input.declaration);
6208
7565
  if (functionHandle === void 0) return void 0;
6209
- if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey(input.executionKey)) {
7566
+ if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey2(input.executionKey)) {
6210
7567
  startCall(functionHandle, void 0);
6211
7568
  return void 0;
6212
7569
  }
6213
7570
  const executionHandle = internExecutionKey(input.executionKey);
6214
7571
  if (executionHandle === void 0) return void 0;
6215
- const startedNs = startCall(functionHandle, executionHandle);
6216
- if (startedNs === void 0) return void 0;
6217
- return { settled: false, functionHandle, executionHandle, startedNs };
7572
+ const started = startCall(functionHandle, executionHandle, {
7573
+ measure: input.measure,
7574
+ ..."startedNs" in input ? { startedNs: input.startedNs } : {}
7575
+ });
7576
+ if (!started) return void 0;
7577
+ return {
7578
+ settled: false,
7579
+ functionHandle,
7580
+ executionHandle,
7581
+ startedNs: started.startedNs,
7582
+ measure: started.measure
7583
+ };
6218
7584
  };
6219
7585
  const completeCall = (call, failed) => {
6220
7586
  if (!call || call.settled) return;
6221
7587
  call.settled = true;
6222
- finishCall(call.functionHandle, call.executionHandle, call.startedNs, failed);
7588
+ if (!call.measure) {
7589
+ finishCall(call.functionHandle, call.executionHandle, failed);
7590
+ return;
7591
+ }
7592
+ let endedNs;
7593
+ try {
7594
+ endedNs = clock.monotonicNs();
7595
+ } catch {
7596
+ endedNs = void 0;
7597
+ }
7598
+ finishCall(call.functionHandle, call.executionHandle, failed, {
7599
+ startedNs: call.startedNs,
7600
+ endedNs
7601
+ });
6223
7602
  };
6224
7603
  const drain = (drainOptions) => {
6225
7604
  if (!sealed) {
6226
- rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
7605
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3));
6227
7606
  if (drainOptions?.flushAll) snapshotActive();
6228
7607
  }
6229
7608
  const batches = functionMetricsBatchesFromQueue({
@@ -6237,7 +7616,8 @@ var createFunctionMetricsCollector = (options) => {
6237
7616
  functions,
6238
7617
  executionKeys,
6239
7618
  queued: queue,
6240
- coverage: { ...coverage, covered_bucket_starts: [] }
7619
+ coverage: { ...coverage, covered_bucket_starts: [] },
7620
+ measurementFormat
6241
7621
  });
6242
7622
  if (batches.length === 0) return [];
6243
7623
  for (const queued of queue) stateBytes -= queued.bytes;
@@ -6270,27 +7650,27 @@ var createFunctionMetricsCollector = (options) => {
6270
7650
  // src/function-metrics/encode-function-metrics-upload.ts
6271
7651
  import {
6272
7652
  encodeFunctionMetricsBatch,
6273
- encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
6274
- FUNCTION_METRICS_BUCKET_LATENESS_MS,
6275
- FUNCTION_METRICS_MAX_DECODED_BYTES,
6276
- FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS2,
6277
- parseFunctionMetricsBucketStart
7653
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync3,
7654
+ FUNCTION_METRICS_BUCKET_LATENESS_MS as FUNCTION_METRICS_BUCKET_LATENESS_MS2,
7655
+ FUNCTION_METRICS_MAX_DECODED_BYTES as FUNCTION_METRICS_MAX_DECODED_BYTES2,
7656
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS4,
7657
+ parseFunctionMetricsBucketStart as parseFunctionMetricsBucketStart2
6278
7658
  } from "@rasputin-ai/core";
6279
- var minuteMarks = (minute) => {
7659
+ var minuteMarks2 = (minute) => {
6280
7660
  const next = minute.started_calls + minute.completed_calls;
6281
7661
  return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
6282
7662
  };
6283
- var expiresAtMsFor = (batch, nowMs) => {
7663
+ var expiresAtMsFor2 = (batch, nowMs) => {
6284
7664
  let oldest;
6285
7665
  for (const start of batch.coverage.covered_bucket_starts) {
6286
- const bucket = parseFunctionMetricsBucketStart(start);
7666
+ const bucket = parseFunctionMetricsBucketStart2(start);
6287
7667
  if (bucket === void 0) continue;
6288
7668
  if (oldest === void 0 || bucket < oldest) oldest = bucket;
6289
7669
  }
6290
- if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
6291
- return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
7670
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
7671
+ return oldest + FUNCTION_METRICS_MINUTE_MS4 + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
6292
7672
  };
6293
- var zeroLossCoverage = (coverage) => ({
7673
+ var zeroLossCoverage2 = (coverage) => ({
6294
7674
  ...coverage,
6295
7675
  skipped_unresolved_execution_type: 0,
6296
7676
  dropped_active_series: 0,
@@ -6299,7 +7679,7 @@ var zeroLossCoverage = (coverage) => ({
6299
7679
  dropped_late_completion: 0,
6300
7680
  dropped_unexportable: 0
6301
7681
  });
6302
- var projectMinutes = (source, minutes, coverage, batchId) => {
7682
+ var projectMinutes2 = (source, minutes, coverage, batchId) => {
6303
7683
  const functionIndexes = /* @__PURE__ */ new Map();
6304
7684
  const typeIndexes = /* @__PURE__ */ new Map();
6305
7685
  const functions = [];
@@ -6338,7 +7718,7 @@ var projectMinutes = (source, minutes, coverage, batchId) => {
6338
7718
  coverage: { ...coverage, covered_bucket_starts: covered }
6339
7719
  };
6340
7720
  };
6341
- var withLoss = (batch, loss) => ({
7721
+ var withLoss2 = (batch, loss) => ({
6342
7722
  ...batch,
6343
7723
  coverage: {
6344
7724
  ...batch.coverage,
@@ -6346,37 +7726,37 @@ var withLoss = (batch, loss) => ({
6346
7726
  dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
6347
7727
  }
6348
7728
  });
6349
- var encodeOne = async (batch, nowMs, signal) => {
7729
+ var encodeOne2 = async (batch, nowMs, signal) => {
6350
7730
  const decodedBytes = encodeFunctionMetricsBatch(batch);
6351
- if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES) return void 0;
6352
- const encoded = await encodeJsonRequestBodyAsync2(decodedBytes, void 0, signal);
7731
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES2) return void 0;
7732
+ const encoded = await encodeJsonRequestBodyAsync3(decodedBytes, void 0, signal);
6353
7733
  return {
6354
7734
  decodedBytes,
6355
7735
  body: encoded.body,
6356
7736
  gzip: encoded.gzip,
6357
7737
  batchId: batch.batch_id,
6358
- expiresAtMs: expiresAtMsFor(batch, nowMs)
7738
+ expiresAtMs: expiresAtMsFor2(batch, nowMs)
6359
7739
  };
6360
7740
  };
6361
- var encodeFitting = async (batch, nowMs, signal) => {
6362
- const encoded = await encodeOne(batch, nowMs, signal);
7741
+ var encodeFitting2 = async (batch, nowMs, signal) => {
7742
+ const encoded = await encodeOne2(batch, nowMs, signal);
6363
7743
  if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
6364
7744
  if (batch.minutes.length <= 1) {
6365
7745
  return {
6366
7746
  uploads: [],
6367
- droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
7747
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks2(minute), 0)
6368
7748
  };
6369
7749
  }
6370
7750
  const mid = Math.ceil(batch.minutes.length / 2);
6371
- const first = projectMinutes(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
6372
- const rest = projectMinutes(
7751
+ const first = projectMinutes2(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
7752
+ const rest = projectMinutes2(
6373
7753
  batch,
6374
7754
  batch.minutes.slice(mid),
6375
- zeroLossCoverage(batch.coverage),
7755
+ zeroLossCoverage2(batch.coverage),
6376
7756
  newFunctionMetricsBatchId()
6377
7757
  );
6378
- const left = await encodeFitting(first, nowMs, signal);
6379
- const right = await encodeFitting(rest, nowMs, signal);
7758
+ const left = await encodeFitting2(first, nowMs, signal);
7759
+ const right = await encodeFitting2(rest, nowMs, signal);
6380
7760
  return {
6381
7761
  uploads: [...left.uploads, ...right.uploads],
6382
7762
  droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
@@ -6389,105 +7769,21 @@ var encodeFunctionMetricsUploads = async (batches, input) => {
6389
7769
  dropped_queue_budget: input.queueDrops ?? 0
6390
7770
  };
6391
7771
  for (const batch of batches) {
6392
- const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
7772
+ const fitted = await encodeFitting2(withLoss2(batch, extra), input.nowMs, input.signal);
6393
7773
  extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
6394
7774
  uploads.push(...fitted.uploads);
6395
7775
  }
6396
7776
  return uploads;
6397
7777
  };
6398
7778
 
6399
- // src/function-metrics/send-function-metrics-batch.ts
6400
- var REQUEST_TIMEOUT_MS2 = 2e4;
6401
- var abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
6402
- var retryAfterMs = (response) => {
6403
- const header = response.headers.get("retry-after");
6404
- if (!header) return null;
6405
- const seconds = Number(header);
6406
- if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
6407
- const date = Date.parse(header);
6408
- return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
6409
- };
6410
- var backoffMs2 = (attempt, random) => {
6411
- const base = Math.min(3e4, 500 * 2 ** attempt);
6412
- return Math.floor(base * (0.5 + random()));
6413
- };
6414
- var fetchUntilAborted = (fetchFn, url, init) => new Promise((resolve, reject) => {
6415
- const onAbort = () => reject(abortError());
6416
- init.signal.addEventListener("abort", onAbort, { once: true });
6417
- if (init.signal.aborted) {
6418
- init.signal.removeEventListener("abort", onAbort);
6419
- reject(abortError());
6420
- return;
6421
- }
6422
- void fetchFn(url, init).then(
6423
- (value) => {
6424
- init.signal.removeEventListener("abort", onAbort);
6425
- resolve(value);
6426
- },
6427
- (error) => {
6428
- init.signal.removeEventListener("abort", onAbort);
6429
- reject(error);
6430
- }
6431
- );
6432
- });
6433
- var sendFunctionMetricsBatch = async (input) => {
6434
- if (input.signal.aborted) return { outcome: "aborted" };
6435
- const nowMs = input.nowMs ?? Date.now;
6436
- if (input.upload.expiresAtMs <= nowMs())
6437
- return { outcome: "terminal", status: null, halt: false };
6438
- const request = new AbortController();
6439
- const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
6440
- timer.unref?.();
6441
- const onParentAbort = () => request.abort();
6442
- input.signal.addEventListener("abort", onParentAbort, { once: true });
6443
- if (input.signal.aborted) request.abort();
6444
- const headers = {
6445
- Authorization: `Bearer ${input.ingestToken}`,
6446
- "Content-Type": "application/json",
6447
- Accept: "application/json"
6448
- };
6449
- if (input.upload.gzip) headers["Content-Encoding"] = "gzip";
6450
- try {
6451
- const response = await fetchUntilAborted(input.fetch, input.url, {
6452
- method: "POST",
6453
- headers,
6454
- body: input.upload.body,
6455
- signal: request.signal
6456
- });
6457
- if (response.ok) return { outcome: "ok" };
6458
- if (response.status === 429) {
6459
- return {
6460
- outcome: "retry",
6461
- waitMs: retryAfterMs(response) ?? backoffMs2(input.attempt, input.random ?? Math.random)
6462
- };
6463
- }
6464
- if (response.status === 401 || response.status === 403 || response.status === 404) {
6465
- return { outcome: "terminal", status: response.status, halt: true };
6466
- }
6467
- if (response.status >= 400 && response.status < 500) {
6468
- return { outcome: "terminal", status: response.status, halt: false };
6469
- }
6470
- return {
6471
- outcome: "retry",
6472
- waitMs: backoffMs2(input.attempt, input.random ?? Math.random)
6473
- };
6474
- } catch {
6475
- if (input.signal.aborted) return { outcome: "aborted" };
6476
- return { outcome: "retry", waitMs: backoffMs2(input.attempt, input.random ?? Math.random) };
6477
- } finally {
6478
- clearTimeout(timer);
6479
- input.signal.removeEventListener("abort", onParentAbort);
6480
- }
6481
- };
6482
-
6483
7779
  // src/function-metrics/function-metrics-exporter.ts
6484
- var MAX_QUEUE_ITEMS = 32;
6485
- var MAX_QUEUE_BYTES = 4 * 1024 * 1024;
6486
- var DEFAULT_SCHEDULE_MS = 6e4;
6487
- var FLUSH_MS = 1e4;
6488
- var SHUTDOWN_FLUSH_MS = 2e3;
6489
- var MAX_ATTEMPTS = 8;
6490
- var sleep = (ms, signal) => new Promise((resolve) => {
7780
+ var MAX_QUEUE_ITEMS2 = 32;
7781
+ var MAX_QUEUE_BYTES2 = 4 * 1024 * 1024;
7782
+ var DEFAULT_SCHEDULE_MS2 = 6e4;
7783
+ var FLUSH_MS2 = 1e4;
7784
+ var SHUTDOWN_FLUSH_MS2 = 2e3;
7785
+ var MAX_ATTEMPTS2 = 8;
7786
+ var sleep2 = (ms, signal) => new Promise((resolve) => {
6491
7787
  if (ms <= 0 || signal.aborted) {
6492
7788
  resolve();
6493
7789
  return;
@@ -6508,7 +7804,7 @@ var sleep = (ms, signal) => new Promise((resolve) => {
6508
7804
  var createFunctionMetricsExporter = (input) => {
6509
7805
  const nowMs = input.nowMs ?? Date.now;
6510
7806
  const random = input.random ?? Math.random;
6511
- const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
7807
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS2;
6512
7808
  const queue = [];
6513
7809
  let queueBytes = 0;
6514
7810
  let queueDrops = 0;
@@ -6532,7 +7828,7 @@ var createFunctionMetricsExporter = (input) => {
6532
7828
  const enqueue = (upload) => {
6533
7829
  queue.push({ upload, attempt: 0 });
6534
7830
  queueBytes += upload.decodedBytes.byteLength;
6535
- while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
7831
+ while (queue.length > MAX_QUEUE_ITEMS2 || queueBytes > MAX_QUEUE_BYTES2) dropOldest();
6536
7832
  };
6537
7833
  const drainAndEnqueue = async (flushAll2) => {
6538
7834
  if (halted || stopped) return;
@@ -6567,7 +7863,7 @@ var createFunctionMetricsExporter = (input) => {
6567
7863
  dropped += 1;
6568
7864
  continue;
6569
7865
  }
6570
- if (item.attempt >= MAX_ATTEMPTS) {
7866
+ if (item.attempt >= MAX_ATTEMPTS2) {
6571
7867
  queue.shift();
6572
7868
  queueBytes -= item.upload.decodedBytes.byteLength;
6573
7869
  dropped += 1;
@@ -6601,7 +7897,7 @@ var createFunctionMetricsExporter = (input) => {
6601
7897
  continue;
6602
7898
  }
6603
7899
  item.attempt += 1;
6604
- await sleep(result.waitMs, signal);
7900
+ await sleep2(result.waitMs, signal);
6605
7901
  }
6606
7902
  };
6607
7903
  const abortCurrent = () => {
@@ -6677,7 +7973,7 @@ var createFunctionMetricsExporter = (input) => {
6677
7973
  const flush = async (timeoutMs) => {
6678
7974
  if (closed || halted) return;
6679
7975
  const abort = new AbortController();
6680
- const budget = timeoutMs ?? FLUSH_MS;
7976
+ const budget = timeoutMs ?? FLUSH_MS2;
6681
7977
  const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
6682
7978
  try {
6683
7979
  await runWork(abort.signal, async (signal) => {
@@ -6698,7 +7994,7 @@ var createFunctionMetricsExporter = (input) => {
6698
7994
  if (timer) clearTimeout(timer);
6699
7995
  timer = void 0;
6700
7996
  const abort = new AbortController();
6701
- const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
7997
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS2);
6702
7998
  abortCurrent();
6703
7999
  try {
6704
8000
  await runWork(abort.signal, async (signal) => {
@@ -6731,29 +8027,31 @@ var installFunctionMetricDeclarationSink = () => {
6731
8027
  };
6732
8028
 
6733
8029
  // src/function-metrics/bind-function-metrics.ts
6734
- var SLOT = Symbol.for("rasputin.functionMetrics.runtime.v1");
6735
- var releasedHandles = /* @__PURE__ */ new WeakSet();
6736
- var isRuntime = (value) => {
8030
+ var SLOT2 = Symbol.for("rasputin.functionMetrics.runtime.v1");
8031
+ var releasedHandles2 = /* @__PURE__ */ new WeakSet();
8032
+ var isRuntime2 = (value) => {
6737
8033
  if (typeof value !== "object" || value === null) return false;
6738
8034
  return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
6739
8035
  };
6740
- var bindingIdentity = (input) => `${input.ingestToken}
8036
+ var bindingIdentity2 = (input) => `${input.ingestToken}
6741
8037
  ${input.url}
6742
8038
  ${input.environment}
6743
- ${input.release}`;
6744
- var warnIncompatible = (runtime) => {
8039
+ ${input.release}
8040
+ ${input.sampledMeasurementFormat ? "1" : "0"}`;
8041
+ var warnIncompatible2 = (runtime) => {
6745
8042
  if (runtime.warnedMismatch) return;
6746
8043
  runtime.warnedMismatch = true;
6747
8044
  console.warn(
6748
8045
  "[rasputin] function metrics already running with a different configuration; this client will not collect function metrics"
6749
8046
  );
6750
8047
  };
6751
- var createBindings = (input) => {
8048
+ var createBindings2 = (input) => {
6752
8049
  installFunctionMetricDeclarationSink();
6753
8050
  const collector = createFunctionMetricsCollector({
6754
8051
  environment: input.environment,
6755
- producerId: randomUUID2(),
6756
- release: input.release
8052
+ producerId: randomUUID4(),
8053
+ release: input.release,
8054
+ sampledMeasurementFormat: input.sampledMeasurementFormat
6757
8055
  });
6758
8056
  return {
6759
8057
  collector,
@@ -6761,7 +8059,7 @@ var createBindings = (input) => {
6761
8059
  collector,
6762
8060
  url: input.url,
6763
8061
  ingestToken: input.ingestToken,
6764
- fetch: input.fetch ?? defaultIngestFetch2()
8062
+ fetch: input.fetch ?? defaultIngestFetch3()
6765
8063
  })
6766
8064
  };
6767
8065
  };
@@ -6770,30 +8068,33 @@ var bindFunctionMetrics = (input) => {
6770
8068
  if (input.options?.enabled === false) return void 0;
6771
8069
  const release = input.release.trim().toLowerCase();
6772
8070
  if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
6773
- const url = resolveEndpointUrls3(input.apiUrl).functionMetricsUrl;
6774
- const key = bindingIdentity({
8071
+ const url = resolveEndpointUrls4(input.apiUrl).functionMetricsUrl;
8072
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
8073
+ const key = bindingIdentity2({
6775
8074
  ingestToken: input.ingestToken,
6776
8075
  url,
6777
8076
  environment: input.environment,
6778
- release
8077
+ release,
8078
+ sampledMeasurementFormat
6779
8079
  });
6780
- const existing = Reflect.get(globalThis, SLOT);
6781
- if (isRuntime(existing)) {
8080
+ const existing = Reflect.get(globalThis, SLOT2);
8081
+ if (isRuntime2(existing)) {
6782
8082
  if (existing.identity !== key) {
6783
- warnIncompatible(existing);
8083
+ warnIncompatible2(existing);
6784
8084
  return void 0;
6785
8085
  }
6786
8086
  existing.refs += 1;
6787
8087
  return { collector: existing.collector, exporter: existing.exporter };
6788
8088
  }
6789
- const bindings2 = createBindings({
8089
+ const bindings2 = createBindings2({
6790
8090
  release,
6791
8091
  ingestToken: input.ingestToken,
6792
8092
  url,
6793
8093
  environment: input.environment,
6794
- fetch: input.fetch
8094
+ fetch: input.fetch,
8095
+ sampledMeasurementFormat
6795
8096
  });
6796
- Reflect.set(globalThis, SLOT, {
8097
+ Reflect.set(globalThis, SLOT2, {
6797
8098
  ...bindings2,
6798
8099
  refs: 1,
6799
8100
  identity: key,
@@ -6802,13 +8103,13 @@ var bindFunctionMetrics = (input) => {
6802
8103
  return bindings2;
6803
8104
  };
6804
8105
  var releaseFunctionMetricsBindings = async (bindings2) => {
6805
- if (!bindings2 || releasedHandles.has(bindings2)) return;
6806
- releasedHandles.add(bindings2);
6807
- const existing = Reflect.get(globalThis, SLOT);
6808
- if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
8106
+ if (!bindings2 || releasedHandles2.has(bindings2)) return;
8107
+ releasedHandles2.add(bindings2);
8108
+ const existing = Reflect.get(globalThis, SLOT2);
8109
+ if (isRuntime2(existing) && existing.exporter === bindings2.exporter) {
6809
8110
  existing.refs -= 1;
6810
8111
  if (existing.refs > 0) return;
6811
- Reflect.deleteProperty(globalThis, SLOT);
8112
+ Reflect.deleteProperty(globalThis, SLOT2);
6812
8113
  }
6813
8114
  await bindings2.exporter.close();
6814
8115
  };
@@ -6949,9 +8250,77 @@ var installGlobalHandlers = (client, options = {}) => {
6949
8250
  };
6950
8251
  };
6951
8252
 
8253
+ // src/runtime-timing/dynamic-duration-sampling.ts
8254
+ var DYNAMIC_DURATION_SAMPLE_STAGES = [
8255
+ { below: 10, divisor: 1 },
8256
+ { below: 30, divisor: 2 },
8257
+ { below: 100, divisor: 3 },
8258
+ { below: 500, divisor: 11 },
8259
+ { below: 1e3, divisor: 23 },
8260
+ { below: 5e3, divisor: 53 }
8261
+ ];
8262
+ var MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS = 4096;
8263
+ var DYNAMIC_DURATION_SAMPLE_TAIL_AFTER = 5e3;
8264
+ var DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR = 100;
8265
+ var DYNAMIC_DURATION_SAMPLE_RESET_MS = 60 * 60 * 1e3;
8266
+ var EXECUTION_DURATION_SAMPLE_PREFIX = "\0execution-metrics\0";
8267
+ var dynamicDurationSampleDivisor = (index) => {
8268
+ for (const stage of DYNAMIC_DURATION_SAMPLE_STAGES) {
8269
+ if (index < stage.below) return stage.divisor;
8270
+ }
8271
+ return DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8272
+ };
8273
+ var shouldSampleDynamicDuration = (index) => {
8274
+ return index % dynamicDurationSampleDivisor(index) === 0;
8275
+ };
8276
+ var nextDurationSampleIndex = (index) => {
8277
+ if (index < Number.MAX_SAFE_INTEGER) return index + 1;
8278
+ return DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + (index - DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + 1) % DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8279
+ };
8280
+ var createDynamicDurationSampleBuckets = (options) => {
8281
+ const functionBuckets = /* @__PURE__ */ new Map();
8282
+ const executionBuckets = /* @__PURE__ */ new Map();
8283
+ const maxBuckets = options.maxBuckets ?? MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS;
8284
+ const resetMs = options.resetMs ?? DYNAMIC_DURATION_SAMPLE_RESET_MS;
8285
+ let lastResetAtMs = options.nowMs();
8286
+ let stopped = false;
8287
+ const reset = () => {
8288
+ functionBuckets.clear();
8289
+ executionBuckets.clear();
8290
+ lastResetAtMs = options.nowMs();
8291
+ };
8292
+ const resetTimer = setInterval(reset, resetMs);
8293
+ resetTimer.unref?.();
8294
+ const takeKey = (buckets, key) => {
8295
+ if (options.nowMs() - lastResetAtMs >= resetMs) reset();
8296
+ const existing = buckets.get(key);
8297
+ if (existing !== void 0) {
8298
+ buckets.delete(key);
8299
+ buckets.set(key, nextDurationSampleIndex(existing));
8300
+ return shouldSampleDynamicDuration(existing);
8301
+ }
8302
+ while (buckets.size >= maxBuckets) {
8303
+ const oldest = buckets.keys().next().value;
8304
+ if (oldest === void 0) break;
8305
+ buckets.delete(oldest);
8306
+ }
8307
+ buckets.set(key, nextDurationSampleIndex(0));
8308
+ return shouldSampleDynamicDuration(0);
8309
+ };
8310
+ return {
8311
+ take: (executionType, callerFunctionId, functionId) => takeKey(functionBuckets, `${executionType}\0${callerFunctionId}\0${functionId}`),
8312
+ takeExecution: (executionType) => takeKey(executionBuckets, `${EXECUTION_DURATION_SAMPLE_PREFIX}${executionType}`),
8313
+ stop: () => {
8314
+ if (stopped) return;
8315
+ stopped = true;
8316
+ clearInterval(resetTimer);
8317
+ }
8318
+ };
8319
+ };
8320
+
6952
8321
  // src/sdk-meta.ts
6953
8322
  var SDK_NAME = "@rasputin-ai/node";
6954
- var SDK_VERSION = "0.13.1";
8323
+ var SDK_VERSION = "0.14.0";
6955
8324
 
6956
8325
  // src/rasputin-init.ts
6957
8326
  var publicExecution = (runtime) => ({
@@ -6967,7 +8336,7 @@ var publicExecution = (runtime) => ({
6967
8336
  getStats: runtime.getStats
6968
8337
  });
6969
8338
  var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
6970
- }, policy, metrics) => {
8339
+ }, policy, metrics, executionMetrics) => {
6971
8340
  const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
6972
8341
  };
6973
8342
  const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
@@ -6988,11 +8357,13 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
6988
8357
  if (timeoutMs === void 0) {
6989
8358
  await policy?.flush();
6990
8359
  await metrics?.exporter.flush();
8360
+ await executionMetrics?.exporter.flush();
6991
8361
  await manifestUpload.wait();
6992
8362
  return;
6993
8363
  }
6994
8364
  await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
6995
8365
  await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8366
+ await executionMetrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
6996
8367
  await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
6997
8368
  },
6998
8369
  close: async () => {
@@ -7003,6 +8374,7 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
7003
8374
  const startedAt = Date.now();
7004
8375
  await policy?.close();
7005
8376
  await releaseFunctionMetricsBindings(metrics);
8377
+ await releaseExecutionMetricsBindings(executionMetrics);
7006
8378
  await client.close();
7007
8379
  await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
7008
8380
  }
@@ -7013,6 +8385,7 @@ function RasputinInit(options, hooks = {}) {
7013
8385
  const enabled = isClientEnabled(options);
7014
8386
  const activation = resolveClientActivation2(options);
7015
8387
  const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
8388
+ const durationSampling = options.dynamicDurationSampling === true;
7016
8389
  const metrics = activation.enabled ? bindFunctionMetrics({
7017
8390
  options: options.functionMetrics,
7018
8391
  clientEnabled: true,
@@ -7020,8 +8393,20 @@ function RasputinInit(options, hooks = {}) {
7020
8393
  release: activation.release,
7021
8394
  ingestToken: activation.ingestToken,
7022
8395
  apiUrl: activation.apiUrl,
7023
- fetch: hooks.fetch
8396
+ fetch: hooks.fetch,
8397
+ sampledMeasurementFormat: durationSampling
8398
+ }) : void 0;
8399
+ const executionMetrics = activation.enabled ? bindExecutionMetrics({
8400
+ options: options.executionMetrics,
8401
+ clientEnabled: true,
8402
+ environment: activation.environment,
8403
+ release: activation.release,
8404
+ ingestToken: activation.ingestToken,
8405
+ apiUrl: activation.apiUrl,
8406
+ fetch: hooks.fetch,
8407
+ sampledMeasurementFormat: durationSampling
7024
8408
  }) : void 0;
8409
+ const durationSampler = durationSampling && (recorderEnabled || Boolean(metrics) || Boolean(executionMetrics)) ? createDynamicDurationSampleBuckets({ nowMs: () => Date.now() }) : void 0;
7025
8410
  const { runtime, policy } = bindAdaptiveRecorder({
7026
8411
  executionRecorder: options.executionRecorder,
7027
8412
  recorderEnabled,
@@ -7035,7 +8420,9 @@ function RasputinInit(options, hooks = {}) {
7035
8420
  sdkVersion: SDK_VERSION,
7036
8421
  scrubPII: options.scrubPII,
7037
8422
  fetch: hooks.fetch,
7038
- functionMetrics: metrics?.collector
8423
+ functionMetrics: metrics?.collector,
8424
+ executionMetrics: executionMetrics?.collector,
8425
+ durationSampler
7039
8426
  });
7040
8427
  const client = createClient(options, {
7041
8428
  sdkVersion: SDK_VERSION,
@@ -7067,7 +8454,8 @@ function RasputinInit(options, hooks = {}) {
7067
8454
  },
7068
8455
  () => uninstallHandlers(),
7069
8456
  policy,
7070
- metrics
8457
+ metrics,
8458
+ executionMetrics
7071
8459
  );
7072
8460
  if (enabled && options.installGlobalHandlers !== false) {
7073
8461
  uninstallHandlers = installGlobalHandlers(wrappedClient);