@rasputin-ai/node 0.13.1 → 0.15.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 (54) hide show
  1. package/dist/execution-metrics/bind-execution-metrics.d.ts +19 -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 -1
  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/execution-recorder/execution-recording-sync.d.ts +0 -1
  25. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -1
  26. package/dist/function-metrics/bind-function-metrics.d.ts +2 -2
  27. package/dist/function-metrics/bind-function-metrics.d.ts.map +1 -1
  28. package/dist/function-metrics/create-metrics-only-runtime.d.ts +7 -1
  29. package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -1
  30. package/dist/function-metrics/function-metrics-batches.d.ts +2 -1
  31. package/dist/function-metrics/function-metrics-batches.d.ts.map +1 -1
  32. package/dist/function-metrics/function-metrics-collector.d.ts +18 -3
  33. package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -1
  34. package/dist/function-metrics/intern-prepared-metrics.d.ts +2 -0
  35. package/dist/function-metrics/intern-prepared-metrics.d.ts.map +1 -1
  36. package/dist/function-metrics/settle-function-metrics.d.ts +7 -4
  37. package/dist/function-metrics/settle-function-metrics.d.ts.map +1 -1
  38. package/dist/index.js +1852 -505
  39. package/dist/instrument/bun.js +1 -1
  40. package/dist/instrument/node.js +1 -1
  41. package/dist/internal.d.ts +3 -0
  42. package/dist/internal.d.ts.map +1 -1
  43. package/dist/internal.js +1830 -498
  44. package/dist/rasputin-init.d.ts +13 -6
  45. package/dist/rasputin-init.d.ts.map +1 -1
  46. package/dist/runtime-timing/call-duration.d.ts +13 -0
  47. package/dist/runtime-timing/call-duration.d.ts.map +1 -0
  48. package/dist/{execution-recorder → runtime-timing}/dynamic-duration-sampling.d.ts +6 -4
  49. package/dist/runtime-timing/dynamic-duration-sampling.d.ts.map +1 -0
  50. package/dist/runtime-timing/execution-duration.d.ts +5 -0
  51. package/dist/runtime-timing/execution-duration.d.ts.map +1 -0
  52. package/dist/sdk-meta.d.ts +1 -1
  53. package/package.json +2 -2
  54. package/dist/execution-recorder/dynamic-duration-sampling.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -678,6 +678,1017 @@ 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
+ const release = input.release.trim().toLowerCase();
1645
+ if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
1646
+ const url = resolveEndpointUrls2(input.apiUrl).executionMetricsUrl;
1647
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
1648
+ const key = bindingIdentity({
1649
+ ingestToken: input.ingestToken,
1650
+ url,
1651
+ environment: input.environment,
1652
+ release,
1653
+ sampledMeasurementFormat
1654
+ });
1655
+ const existing = Reflect.get(globalThis, SLOT);
1656
+ if (isRuntime(existing)) {
1657
+ if (existing.identity !== key) {
1658
+ warnIncompatible(existing);
1659
+ return void 0;
1660
+ }
1661
+ existing.refs += 1;
1662
+ return { collector: existing.collector, exporter: existing.exporter };
1663
+ }
1664
+ const bindings2 = createBindings({
1665
+ release,
1666
+ ingestToken: input.ingestToken,
1667
+ url,
1668
+ environment: input.environment,
1669
+ fetch: input.fetch,
1670
+ sampledMeasurementFormat
1671
+ });
1672
+ Reflect.set(globalThis, SLOT, {
1673
+ ...bindings2,
1674
+ refs: 1,
1675
+ identity: key,
1676
+ warnedMismatch: false
1677
+ });
1678
+ return bindings2;
1679
+ };
1680
+ var releaseExecutionMetricsBindings = async (bindings2) => {
1681
+ if (!bindings2 || releasedHandles.has(bindings2)) return;
1682
+ releasedHandles.add(bindings2);
1683
+ const existing = Reflect.get(globalThis, SLOT);
1684
+ if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
1685
+ existing.refs -= 1;
1686
+ if (existing.refs > 0) return;
1687
+ Reflect.deleteProperty(globalThis, SLOT);
1688
+ }
1689
+ await bindings2.exporter.close();
1690
+ };
1691
+
681
1692
  // src/execution-recorder/execution-recorder.ts
682
1693
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
683
1694
  import {
@@ -732,11 +1743,30 @@ var executionTypeKey = (metadata) => {
732
1743
  var isHttpClientErrorStatus = (status) => {
733
1744
  return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
734
1745
  };
1746
+ var isHttpServerErrorStatus = (status) => {
1747
+ return typeof status === "number" && Number.isFinite(status) && status >= 500;
1748
+ };
1749
+ var executionOutcomeFailed = (input) => input.hasError || input.runFailed || isHttpServerErrorStatus(input.status);
735
1750
 
736
1751
  // src/execution-recorder/function-plan.ts
737
1752
  var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
738
1753
  var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
739
1754
 
1755
+ // src/runtime-timing/call-duration.ts
1756
+ var planCallDuration = (sampler, input) => {
1757
+ if (!sampler) return { selected: true, measure: true };
1758
+ if (!input.executionType) return { selected: false, measure: input.forceMeasure };
1759
+ const selected = sampler.take(input.executionType, input.callerFunctionId, input.functionId);
1760
+ return { selected, measure: selected || input.forceMeasure };
1761
+ };
1762
+
1763
+ // src/runtime-timing/execution-duration.ts
1764
+ var planExecutionDuration = (sampler, executionType) => {
1765
+ if (!sampler) return { selected: true };
1766
+ if (!executionType) return { selected: false };
1767
+ return { selected: sampler.takeExecution(executionType) };
1768
+ };
1769
+
740
1770
  // src/function-metrics/function-metric-declaration-registry.ts
741
1771
  var REGISTRY_SYMBOL = Symbol.for("rasputin.functionMetrics.declarations.v1");
742
1772
  var getRegistry2 = () => {
@@ -761,58 +1791,93 @@ var registerFunctionMetricDeclarations = (declarations) => {
761
1791
  var functionMetricDeclarationFor = (runtimeId) => getRegistry2().byRuntimeId.get(runtimeId);
762
1792
 
763
1793
  // src/function-metrics/intern-prepared-metrics.ts
764
- import { functionMetricsTraceDeclaration } from "@rasputin-ai/core";
765
- var internPreparedMetrics = (collector, plan) => {
1794
+ import {
1795
+ functionMetricsTraceDeclaration
1796
+ } from "@rasputin-ai/core";
1797
+ var declarationForPreparedPlan = (plan) => {
766
1798
  if (plan.excluded) return void 0;
767
- if (plan.metricsHandle !== void 0) return plan.metricsHandle;
768
1799
  const declaration = plan.metricsDeclaration ?? functionMetricDeclarationFor(plan.functionId) ?? functionMetricsTraceDeclaration({
769
1800
  runtimeId: plan.functionId
770
1801
  });
771
1802
  plan.metricsDeclaration = declaration;
1803
+ return declaration;
1804
+ };
1805
+ var internPreparedMetrics = (collector, plan) => {
1806
+ if (plan.excluded) return void 0;
1807
+ if (plan.metricsHandle !== void 0) return plan.metricsHandle;
1808
+ const declaration = declarationForPreparedPlan(plan);
772
1809
  const handle = collector.internDeclaration(declaration);
773
1810
  if (handle !== void 0) plan.metricsHandle = handle;
774
1811
  return handle;
775
1812
  };
776
1813
 
777
1814
  // src/function-metrics/settle-function-metrics.ts
778
- var finishMetricsCall = (collector, functionHandle, executionHandle, startedNs, failed, endedNs) => {
1815
+ var finishMetricsCall = (collector, functionHandle, executionHandle, failed, timing) => {
779
1816
  try {
780
- collector.finishCall(functionHandle, executionHandle, startedNs, failed, endedNs);
1817
+ collector.finishCall(functionHandle, executionHandle, failed, timing);
781
1818
  } catch {
782
1819
  }
783
1820
  };
784
1821
  var thenOf = (value) => {
785
- if (typeof value !== "object" && typeof value !== "function" || value === null) {
1822
+ try {
1823
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
1824
+ return void 0;
1825
+ }
1826
+ if (!("then" in value)) return void 0;
1827
+ const then = value.then;
1828
+ if (typeof then !== "function") return void 0;
1829
+ return (onFulfilled, onRejected) => {
1830
+ Reflect.apply(then, value, [onFulfilled, onRejected]);
1831
+ };
1832
+ } catch {
1833
+ return void 0;
1834
+ }
1835
+ };
1836
+ var tryCallClock = () => {
1837
+ try {
1838
+ return process.hrtime.bigint();
1839
+ } catch {
786
1840
  return void 0;
787
1841
  }
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
1842
  };
795
- var startMetricsCall = (collector, functionHandle, executionHandle, startedNs) => {
1843
+ var startMetricsCall = (collector, functionHandle, executionHandle, options) => {
796
1844
  if (!collector || functionHandle === void 0) return void 0;
797
1845
  try {
798
- return collector.startCall(functionHandle, executionHandle, startedNs);
1846
+ return collector.startCall(functionHandle, executionHandle, options);
799
1847
  } catch {
800
1848
  return void 0;
801
1849
  }
802
1850
  };
803
- var completeMetricsResult = (collector, functionHandle, executionHandle, startedNs, value) => {
1851
+ var completeMetricsResult = (collector, functionHandle, executionHandle, value, timing, onSettled) => {
804
1852
  const then = thenOf(value);
805
1853
  if (!then) {
806
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false);
1854
+ finishMetricsCall(collector, functionHandle, executionHandle, false, timing);
807
1855
  return;
808
1856
  }
1857
+ let completed = false;
1858
+ const complete = (failed) => {
1859
+ if (completed) return;
1860
+ completed = true;
1861
+ const endedNs = timing !== void 0 ? tryCallClock() : void 0;
1862
+ finishMetricsCall(
1863
+ collector,
1864
+ functionHandle,
1865
+ executionHandle,
1866
+ failed,
1867
+ timing === void 0 ? void 0 : { startedNs: timing.startedNs, endedNs }
1868
+ );
1869
+ try {
1870
+ onSettled?.(endedNs);
1871
+ } catch {
1872
+ }
1873
+ };
809
1874
  try {
810
1875
  then(
811
- () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false),
812
- () => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true)
1876
+ () => complete(false),
1877
+ () => complete(true)
813
1878
  );
814
1879
  } catch {
815
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
1880
+ complete(true);
816
1881
  }
817
1882
  };
818
1883
 
@@ -852,6 +1917,14 @@ var emptyStats = () => ({
852
1917
  adaptiveRefreshFailures: 0,
853
1918
  lastAdaptiveFailureKind: null
854
1919
  });
1920
+ var metricsStorage = new AsyncLocalStorage();
1921
+ var tryCallClock2 = () => {
1922
+ try {
1923
+ return process.hrtime.bigint();
1924
+ } catch {
1925
+ return void 0;
1926
+ }
1927
+ };
855
1928
  var mergeMetadata = (store, metadata) => {
856
1929
  if (metadata.kind) store.execution.kind = metadata.kind;
857
1930
  if (metadata.name !== void 0) store.execution.name = metadata.name;
@@ -865,32 +1938,100 @@ var definitionOf = (input) => {
865
1938
  return input;
866
1939
  };
867
1940
  var bindExecutionHandle = (collector, store) => {
1941
+ if (!collector) return;
868
1942
  store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
869
1943
  };
870
- var runWithMetrics = (collector, plan, executionHandle, callback) => {
1944
+ var bindExecutionMetricsIdentity = (collector, store) => {
1945
+ if (!collector || !store.executionMetrics) return;
1946
+ collector.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
1947
+ };
1948
+ var settleStarted = (collector, functionHandle, executionHandle, started, value, failed, endedNs) => {
1949
+ if (!started || functionHandle === void 0 || executionHandle === void 0) return;
1950
+ const timing = started.measure ? { startedNs: started.startedNs, endedNs } : void 0;
1951
+ if (failed) {
1952
+ finishMetricsCall(collector, functionHandle, executionHandle, true, timing);
1953
+ return;
1954
+ }
1955
+ completeMetricsResult(collector, functionHandle, executionHandle, value, timing);
1956
+ };
1957
+ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1958
+ if (!collector) return callback();
1959
+ const duration = planCallDuration(durationSampler, {
1960
+ forceMeasure: false,
1961
+ executionType: store ? executionTypeKey(store.execution) : void 0,
1962
+ callerFunctionId: store?.currentFunctionId ?? "",
1963
+ functionId: plan.functionId
1964
+ });
1965
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
871
1966
  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);
1967
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
1968
+ measure: duration.selected,
1969
+ ...duration.selected ? { startedNs } : {}
1970
+ });
1971
+ const invoke = () => {
1972
+ try {
1973
+ const result = callback();
1974
+ settleStarted(
1975
+ collector,
1976
+ functionHandle,
1977
+ store?.executionHandle,
1978
+ started,
1979
+ result,
1980
+ false,
1981
+ started?.measure && !(result instanceof Promise) ? tryCallClock2() : void 0
1982
+ );
1983
+ return result;
1984
+ } catch (error) {
1985
+ settleStarted(
1986
+ collector,
1987
+ functionHandle,
1988
+ store?.executionHandle,
1989
+ started,
1990
+ error,
1991
+ true,
1992
+ started?.measure ? tryCallClock2() : void 0
1993
+ );
1994
+ throw error;
882
1995
  }
883
- throw error;
884
- }
1996
+ };
1997
+ if (!store || !durationSampler) return invoke();
1998
+ return metricsStorage.run({ ...store, currentFunctionId: plan.functionId }, invoke);
885
1999
  };
886
- var metricsHandle = (collector, plan, executionHandle) => {
2000
+ var metricsHandle = (collector, durationSampler, plan, store) => {
2001
+ if (!collector) return passthroughHandle();
2002
+ const duration = planCallDuration(durationSampler, {
2003
+ forceMeasure: false,
2004
+ executionType: store ? executionTypeKey(store.execution) : void 0,
2005
+ callerFunctionId: store?.currentFunctionId ?? "",
2006
+ functionId: plan.functionId
2007
+ });
2008
+ const startedNs = duration.measure ? tryCallClock2() : void 0;
887
2009
  const functionHandle = internPreparedMetrics(collector, plan);
888
- const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
889
- if (startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
2010
+ const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
2011
+ measure: duration.selected,
2012
+ ...duration.selected ? { startedNs } : {}
2013
+ });
2014
+ if (!started || functionHandle === void 0 || store?.executionHandle === void 0) {
890
2015
  return passthroughHandle();
891
2016
  }
2017
+ const executionHandle = store.executionHandle;
892
2018
  let failed = false;
893
2019
  let settled = false;
2020
+ let previousFunctionId = store.currentFunctionId;
2021
+ let callerClaimed = false;
2022
+ const claimCaller = () => {
2023
+ if (callerClaimed || !durationSampler) return;
2024
+ previousFunctionId = store.currentFunctionId;
2025
+ store.currentFunctionId = plan.functionId;
2026
+ callerClaimed = true;
2027
+ };
2028
+ const releaseCaller = () => {
2029
+ if (!callerClaimed) return;
2030
+ callerClaimed = false;
2031
+ if (previousFunctionId === void 0) delete store.currentFunctionId;
2032
+ else store.currentFunctionId = previousFunctionId;
2033
+ };
2034
+ claimCaller();
894
2035
  return {
895
2036
  leave: (value) => value,
896
2037
  fail: () => {
@@ -899,20 +2040,36 @@ var metricsHandle = (collector, plan, executionHandle) => {
899
2040
  end: () => {
900
2041
  if (settled) return;
901
2042
  settled = true;
902
- finishMetricsCall(collector, functionHandle, executionHandle, startedNs, failed);
2043
+ releaseCaller();
2044
+ const endedNs = started.measure ? tryCallClock2() : void 0;
2045
+ finishMetricsCall(
2046
+ collector,
2047
+ functionHandle,
2048
+ executionHandle,
2049
+ failed,
2050
+ started.measure ? { startedNs: started.startedNs, endedNs } : void 0
2051
+ );
903
2052
  },
904
2053
  run: function __rasputinHandleRun__4(callback) {
905
2054
  return runExactlyOnce((invoke) => invoke(), callback);
906
2055
  },
907
- suspend: (value) => value,
908
- resume: (value) => value
2056
+ suspend: (value) => {
2057
+ releaseCaller();
2058
+ return value;
2059
+ },
2060
+ resume: (value) => {
2061
+ claimCaller();
2062
+ return value;
2063
+ }
909
2064
  };
910
2065
  };
911
- var createMetricsOnlyRuntime = (collector) => {
912
- const storage = new AsyncLocalStorage();
2066
+ var createMetricsOnlyRuntime = (input) => {
2067
+ const collector = input.functionMetrics;
2068
+ const executionMetrics = input.executionMetrics;
2069
+ const durationSampler = input.durationSampler;
913
2070
  const preparedModules = /* @__PURE__ */ new WeakMap();
914
2071
  let nextRuntimePlanId = 1;
915
- const currentHandle = () => storage.getStore()?.executionHandle;
2072
+ const currentStore = () => metricsStorage.getStore();
916
2073
  const planFor = (definition) => ({
917
2074
  runtimePlanId: nextRuntimePlanId++,
918
2075
  definition,
@@ -938,9 +2095,9 @@ var createMetricsOnlyRuntime = (collector) => {
938
2095
  preparedModules.set(plans, prepared);
939
2096
  return prepared;
940
2097
  };
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) };
2098
+ const runPrepared = (plan, _args, callback) => runWithMetrics(collector, durationSampler, plan, currentStore(), callback);
2099
+ function trace(input2, fn) {
2100
+ const definition = typeof input2 === "string" ? definitionOf(input2) : { ...input2, functionId: runtimeFunctionId2(input2) };
944
2101
  const plan = planFor(definition);
945
2102
  return function __rasputinHandleRun__4(...args) {
946
2103
  if (new.target) {
@@ -949,6 +2106,28 @@ var createMetricsOnlyRuntime = (collector) => {
949
2106
  return runPrepared(plan, args, () => fn.apply(this, args));
950
2107
  };
951
2108
  }
2109
+ const finishScope = (store, next) => {
2110
+ if (next) {
2111
+ mergeMetadata(store, next);
2112
+ bindExecutionHandle(collector, store);
2113
+ bindExecutionMetricsIdentity(executionMetrics, store);
2114
+ }
2115
+ if (!executionMetrics || !store.executionMetrics) return;
2116
+ if (store.executionMetrics.finished) return;
2117
+ const endedNs = tryCallClock2();
2118
+ const executionKey = executionTypeKey(store.execution);
2119
+ bindExecutionMetricsIdentity(executionMetrics, store);
2120
+ executionMetrics.finishExecution(store.executionMetrics, {
2121
+ failed: executionOutcomeFailed({
2122
+ hasError: store.hasError,
2123
+ runFailed: store.runFailed,
2124
+ status: store.execution.request?.status
2125
+ }),
2126
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
2127
+ startedNs: store.startedAtNs,
2128
+ ...endedNs === void 0 ? {} : { endedNs }
2129
+ });
2130
+ };
952
2131
  return {
953
2132
  createScope: (metadata) => {
954
2133
  const store = {
@@ -956,22 +2135,35 @@ var createMetricsOnlyRuntime = (collector) => {
956
2135
  ...metadata,
957
2136
  ...metadata.request ? { request: { ...metadata.request } } : {}
958
2137
  },
959
- executionHandle: void 0
2138
+ executionHandle: void 0,
2139
+ startedAtNs: tryCallClock2() ?? 0n,
2140
+ hasError: false,
2141
+ runFailed: false
960
2142
  };
961
2143
  bindExecutionHandle(collector, store);
2144
+ if (executionMetrics) {
2145
+ store.executionMetrics = executionMetrics.createState();
2146
+ bindExecutionMetricsIdentity(executionMetrics, store);
2147
+ }
962
2148
  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);
2149
+ run: (callback) => metricsStorage.run(store, () => {
2150
+ try {
2151
+ return callback();
2152
+ } catch (error) {
2153
+ store.runFailed = true;
2154
+ throw error;
970
2155
  }
2156
+ }),
2157
+ getErrorState: () => void 0,
2158
+ observeError: () => {
2159
+ store.hasError = true;
2160
+ return inertErrorObservation();
971
2161
  },
2162
+ finish: (next) => finishScope(store, next),
972
2163
  mergeMetadata: (next) => {
973
2164
  mergeMetadata(store, next);
974
2165
  bindExecutionHandle(collector, store);
2166
+ bindExecutionMetricsIdentity(executionMetrics, store);
975
2167
  }
976
2168
  };
977
2169
  },
@@ -983,10 +2175,11 @@ var createMetricsOnlyRuntime = (collector) => {
983
2175
  },
984
2176
  prepareFunctionPlans: (plans) => prepareEncoded(plans),
985
2177
  runPreparedFunction: runPrepared,
986
- enterPreparedFunction: (plan) => metricsHandle(collector, plan, currentHandle()),
2178
+ enterPreparedFunction: (plan) => metricsHandle(collector, durationSampler, plan, currentStore()),
987
2179
  trace,
988
2180
  getStats: () => emptyStats(),
989
2181
  close: () => {
2182
+ durationSampler?.stop();
990
2183
  }
991
2184
  };
992
2185
  };
@@ -1004,68 +2197,6 @@ var sanitizeFullCaptureDurationMs = (value) => {
1004
2197
  Math.max(MIN_FULL_CAPTURE_DURATION_MS, Math.floor(value))
1005
2198
  );
1006
2199
  };
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
2200
 
1070
2201
  // src/execution-recorder/execution-journal.ts
1071
2202
  var KIND_ENTER = 1;
@@ -1164,6 +2295,15 @@ var ExecutionJournal = class {
1164
2295
  }
1165
2296
  this.openCallIds.delete(callId);
1166
2297
  }
2298
+ setCallTiming(callId, timestampNs, durationNs) {
2299
+ for (let index = this.length - 1; index >= 0; index--) {
2300
+ if (this.callId[index] !== callId) continue;
2301
+ if (this.kind[index] !== KIND_EXIT && this.kind[index] !== KIND_THROW) continue;
2302
+ this.timestampNs[index] = timestampNs;
2303
+ this.durationNs[index] = durationNs;
2304
+ return;
2305
+ }
2306
+ }
1167
2307
  dropCall() {
1168
2308
  this.dropped += 2;
1169
2309
  }
@@ -3101,24 +4241,49 @@ var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
3101
4241
  var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
3102
4242
  var createExecutionRecorder = (options, hooks = {}) => {
3103
4243
  if (!options?.enabled) {
3104
- return hooks.functionMetrics ? createMetricsOnlyRuntime(hooks.functionMetrics) : noOpExecution;
4244
+ return hooks.functionMetrics || hooks.executionMetrics ? createMetricsOnlyRuntime({
4245
+ functionMetrics: hooks.functionMetrics,
4246
+ executionMetrics: hooks.executionMetrics,
4247
+ durationSampler: hooks.durationSampler
4248
+ }) : noOpExecution;
3105
4249
  }
3106
4250
  const functionMetrics = hooks.functionMetrics;
4251
+ const executionMetrics = hooks.executionMetrics;
4252
+ const durationSampler = hooks.durationSampler;
3107
4253
  const bindMetricsExecution = (recording) => {
3108
4254
  if (!functionMetrics) return;
3109
4255
  recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
3110
4256
  executionTypeKey(recording.execution)
3111
4257
  );
3112
4258
  };
4259
+ const bindExecutionMetricsIdentity2 = (recording) => {
4260
+ if (!executionMetrics || !recording.executionMetrics) return;
4261
+ executionMetrics.bindIdentity(
4262
+ recording.executionMetrics,
4263
+ executionTypeKey(recording.execution)
4264
+ );
4265
+ };
3113
4266
  warnIfMissingAsyncContextFrame();
3114
4267
  const adaptiveEnabled = options.adaptive?.enabled === true;
3115
4268
  const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
3116
4269
  options.adaptive?.fullCaptureDurationMs
3117
4270
  );
3118
- const durationSamplingEnabled = adaptiveEnabled && sanitizeDynamicDurationSampling(options.adaptive?.dynamicDurationSampling);
4271
+ const trackCallers = durationSampler !== void 0;
3119
4272
  const readCallClock = () => process.hrtime.bigint();
4273
+ const tryCallClock3 = () => {
4274
+ try {
4275
+ return readCallClock();
4276
+ } catch {
4277
+ return void 0;
4278
+ }
4279
+ };
4280
+ const invocationStart = (measure) => {
4281
+ if (!measure) return { timed: false, startedAtNs: 0n };
4282
+ const startedAtNs = tryCallClock3();
4283
+ if (startedAtNs === void 0) return { timed: false, startedAtNs: 0n };
4284
+ return { timed: true, startedAtNs };
4285
+ };
3120
4286
  const nowMs = () => hooks.nowMs?.() ?? Date.now();
3121
- const durationSamples = durationSamplingEnabled ? createDynamicDurationSampleBuckets({ nowMs }) : void 0;
3122
4287
  const localActivations = /* @__PURE__ */ new Map();
3123
4288
  const policySnapshotFor = () => hooks.policySnapshot?.() ?? localActivations;
3124
4289
  const keyIsActive = (snapshot, key, atMs) => {
@@ -3303,21 +4468,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
3303
4468
  }
3304
4469
  };
3305
4470
  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
4471
  const callStoreFor = (store, functionId, callId) => {
3308
4472
  const next = { ...store, currentCallId: callId };
3309
- if (durationSamplingEnabled) next.currentFunctionId = functionId;
4473
+ if (trackCallers) next.currentFunctionId = functionId;
3310
4474
  return next;
3311
4475
  };
3312
4476
  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
- };
4477
+ return trackCallers ? { ...store, currentFunctionId: functionId } : store;
4478
+ };
4479
+ const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess);
4480
+ const planInvocationDuration = (recording, plan, callerFunctionId) => planCallDuration(durationSampler, {
4481
+ forceMeasure: recorderForceMeasure(recording),
4482
+ executionType: executionTypeKey(recording.execution),
4483
+ callerFunctionId: callerFunctionId ?? "",
4484
+ functionId: plan.functionId
4485
+ });
3321
4486
  const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
3322
4487
  const tryAdmitLiveSession = (recording) => {
3323
4488
  if (recording.retainSuccess || recording.finished) return;
@@ -3530,7 +4695,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3530
4695
  },
3531
4696
  functions: functions.slice(),
3532
4697
  events: fullyTimed ? asFullyTimedEvents(events) : events.slice(),
3533
- ...fullyTimed || !durationSamplingEnabled ? {} : { durationSampling: { policy: "progressive" } },
4698
+ ...fullyTimed || !durationSampler ? {} : { durationSampling: { policy: "progressive" } },
3534
4699
  ...truncated ? { truncated: { ...truncated } } : {},
3535
4700
  ...capture ? { capture: { ...capture } } : {}
3536
4701
  };
@@ -3800,7 +4965,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3800
4965
  }
3801
4966
  };
3802
4967
  };
3803
- const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs) => {
4968
+ const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
3804
4969
  if (!recording.journal) {
3805
4970
  return;
3806
4971
  }
@@ -3810,17 +4975,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
3810
4975
  const callId = ++recording.nextCallId;
3811
4976
  const capturedError = serializedError(recording, error, callId);
3812
4977
  const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3813
- const endedAtNs = readCallClock();
4978
+ const endedAtNs = timed ? completedAtNs : void 0;
3814
4979
  const droppedBefore = recording.journal.dropped;
3815
4980
  const retained = recording.journal.forceCompletedCall(
3816
4981
  plan.runtimePlanId,
3817
4982
  callId,
3818
4983
  parentCallId,
3819
- timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4984
+ timed && endedAtNs !== void 0 ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
3820
4985
  recordedArgs,
3821
4986
  KIND_THROW,
3822
- endedAtNs - recording.startedAtNs,
3823
- timed ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
4987
+ timed && endedAtNs !== void 0 ? endedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE,
4988
+ timed && endedAtNs !== void 0 ? endedAtNs - startedAtNs : TIMING_UNAVAILABLE,
3824
4989
  capturedError.value
3825
4990
  );
3826
4991
  if (retained) {
@@ -3852,6 +5017,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
3852
5017
  appendSuppressedPlaceholder(recording, suppressed);
3853
5018
  }
3854
5019
  };
5020
+ const addSuppressedDuration = (suppressed, startedAtNs, endedAtNs) => {
5021
+ if (!suppressed.firstTimed) {
5022
+ suppressed.firstTimestampNs = startedAtNs;
5023
+ suppressed.firstTimed = true;
5024
+ }
5025
+ suppressed.lastTimestampNs = endedAtNs;
5026
+ suppressed.lastTimed = true;
5027
+ suppressed.sampledDurationCount++;
5028
+ suppressed.sampledDurationNs += endedAtNs - startedAtNs;
5029
+ };
3855
5030
  const releaseJournalIfIdle = (recording) => {
3856
5031
  if (!recording.finished || recording.hasError || recording.inFlightCalls > 0) return;
3857
5032
  if (!recording.journal) return;
@@ -3924,6 +5099,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
3924
5099
  if (metadata) {
3925
5100
  mergeExecutionMetadata(recording.execution, metadata);
3926
5101
  bindMetricsExecution(recording);
5102
+ bindExecutionMetricsIdentity2(recording);
5103
+ }
5104
+ if (executionMetrics && recording.executionMetrics) {
5105
+ const executionKey = executionTypeKey(recording.execution);
5106
+ bindExecutionMetricsIdentity2(recording);
5107
+ executionMetrics.finishExecution(recording.executionMetrics, {
5108
+ failed: executionOutcomeFailed({
5109
+ hasError: recording.hasError,
5110
+ runFailed: recording.runFailed === true,
5111
+ status: recording.execution.request?.status
5112
+ }),
5113
+ measure: planExecutionDuration(durationSampler, executionKey).selected,
5114
+ startedNs: recording.startedAtNs,
5115
+ endedNs: recorderStartedAtNs
5116
+ });
3927
5117
  }
3928
5118
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3929
5119
  if (recording.runFailed && !recording.hasError) {
@@ -3933,8 +5123,6 @@ var createExecutionRecorder = (options, hooks = {}) => {
3933
5123
  if (!recording.hasError && !recording.retainSuccess) {
3934
5124
  stats.successfulExecutionsDiscarded++;
3935
5125
  }
3936
- const finishedKey = executionTypeKey(recording.execution);
3937
- if (finishedKey) hooks.observeExecutionType?.(finishedKey);
3938
5126
  recording.finishedAtNs = process.hrtime.bigint();
3939
5127
  addRecorderTime(recording, recording.finishedAtNs - recorderStartedAtNs);
3940
5128
  recordInlineTiming(recording);
@@ -3994,6 +5182,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
3994
5182
  };
3995
5183
  if (identityComplete) tryAdmitLiveSession(recording);
3996
5184
  bindMetricsExecution(recording);
5185
+ if (executionMetrics) {
5186
+ recording.executionMetrics = executionMetrics.createState();
5187
+ bindExecutionMetricsIdentity2(recording);
5188
+ }
3997
5189
  stats.activeExecutions++;
3998
5190
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3999
5191
  liveRecordings.push(recording);
@@ -4046,6 +5238,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4046
5238
  mergeExecutionMetadata(recording.execution, nextMetadata);
4047
5239
  completeIdentityFromSnapshot(recording);
4048
5240
  bindMetricsExecution(recording);
5241
+ bindExecutionMetricsIdentity2(recording);
4049
5242
  } catch {
4050
5243
  }
4051
5244
  }
@@ -4062,18 +5255,53 @@ var createExecutionRecorder = (options, hooks = {}) => {
4062
5255
  }
4063
5256
  };
4064
5257
  const runPreparedFunctionFromStore = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5258
+ const duration = plan.excluded ? { selected: false, measure: false } : store ? planInvocationDuration(store.recording, plan, store.currentFunctionId) : { selected: false, measure: false };
5259
+ const startedNs = duration.measure ? tryCallClock3() : void 0;
4065
5260
  const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
4066
5261
  const executionHandle = store?.recording.metricsExecutionHandle;
4067
- const startedNs = startMetricsCall(functionMetrics, functionHandle, executionHandle);
5262
+ const metricsStart = startMetricsCall(functionMetrics, functionHandle, executionHandle, {
5263
+ measure: duration.selected,
5264
+ ...duration.selected ? { startedNs } : {}
5265
+ });
5266
+ const sharedClock = {
5267
+ start: startedNs,
5268
+ timed: startedNs !== void 0,
5269
+ selected: duration.selected
5270
+ };
5271
+ const applyRecorderEnd = (endedNs) => {
5272
+ if (endedNs === void 0) return;
5273
+ sharedClock.end = endedNs;
5274
+ sharedClock.applyEnd?.(endedNs);
5275
+ };
4068
5276
  const settle = (value, failed) => {
4069
- if (!functionMetrics || startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
5277
+ const pending = !failed && value instanceof Promise;
5278
+ if (!pending && sharedClock.timed && sharedClock.end === void 0) {
5279
+ sharedClock.end = tryCallClock3();
5280
+ }
5281
+ if (!functionMetrics || !metricsStart || functionHandle === void 0 || executionHandle === void 0) {
4070
5282
  return;
4071
5283
  }
5284
+ const timing = sharedClock.selected ? { startedNs: sharedClock.start, endedNs: sharedClock.end } : void 0;
4072
5285
  if (failed) {
4073
- finishMetricsCall(functionMetrics, functionHandle, executionHandle, startedNs, true);
5286
+ finishMetricsCall(functionMetrics, functionHandle, executionHandle, true, timing);
4074
5287
  return;
4075
5288
  }
4076
- completeMetricsResult(functionMetrics, functionHandle, executionHandle, startedNs, value);
5289
+ completeMetricsResult(
5290
+ functionMetrics,
5291
+ functionHandle,
5292
+ executionHandle,
5293
+ value,
5294
+ timing,
5295
+ (endedNs) => {
5296
+ if (endedNs !== void 0) {
5297
+ applyRecorderEnd(endedNs);
5298
+ return;
5299
+ }
5300
+ if (!sharedClock.selected && sharedClock.timed) {
5301
+ applyRecorderEnd(tryCallClock3());
5302
+ }
5303
+ }
5304
+ );
4077
5305
  };
4078
5306
  let startedCallback = false;
4079
5307
  try {
@@ -4085,7 +5313,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4085
5313
  startedCallback = true;
4086
5314
  return callback();
4087
5315
  },
4088
- omitValues
5316
+ omitValues,
5317
+ sharedClock
4089
5318
  );
4090
5319
  settle(result, false);
4091
5320
  return result;
@@ -4099,7 +5328,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4099
5328
  return result;
4100
5329
  }
4101
5330
  };
4102
- const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
5331
+ const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues, sharedClock) {
4103
5332
  const omitCallValues = omitValues === true || plan.omitCallValues;
4104
5333
  if (!store) return callback();
4105
5334
  if (plan.disabled) {
@@ -4135,9 +5364,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4135
5364
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
4136
5365
  } catch {
4137
5366
  }
4138
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
5367
+ const timed = sharedClock.timed;
5368
+ const startedAtNs = sharedClock.start ?? 0n;
4139
5369
  if (group.observedCalls > capturedCallLimitFor(recording)) {
4140
- const startedAtNs2 = timed ? readCallClock() : 0n;
4141
5370
  try {
4142
5371
  const result = runStore(
4143
5372
  samplingStore(store, plan.functionId),
@@ -4145,23 +5374,48 @@ var createExecutionRecorder = (options, hooks = {}) => {
4145
5374
  return callback();
4146
5375
  }
4147
5376
  );
4148
- recordSuppressedCall(
4149
- recording,
4150
- group,
4151
- parentCallId,
4152
- startedAtNs2,
4153
- timed ? readCallClock() : 0n,
4154
- timed
4155
- );
5377
+ if (result instanceof Promise) {
5378
+ recordSuppressedCall(recording, group, parentCallId, startedAtNs, 0n, false);
5379
+ if (timed) {
5380
+ const suppressed = group.suppressed;
5381
+ sharedClock.applyEnd = (endedNs) => {
5382
+ if (endedNs === void 0 || recording.finished || !suppressed || group.suppressed !== suppressed) {
5383
+ return;
5384
+ }
5385
+ addSuppressedDuration(suppressed, startedAtNs, endedNs);
5386
+ };
5387
+ }
5388
+ } else {
5389
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5390
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5391
+ recordSuppressedCall(
5392
+ recording,
5393
+ group,
5394
+ parentCallId,
5395
+ startedAtNs,
5396
+ endedAtNs ?? 0n,
5397
+ endedAtNs !== void 0
5398
+ );
5399
+ }
4156
5400
  settleInFlight(recording);
4157
5401
  return result;
4158
5402
  } catch (error) {
4159
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs2, error, timed);
5403
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5404
+ captureCompletedThrow(
5405
+ recording,
5406
+ plan,
5407
+ args,
5408
+ parentCallId,
5409
+ startedAtNs,
5410
+ error,
5411
+ timed,
5412
+ void 0,
5413
+ sharedClock.end
5414
+ );
4160
5415
  settleInFlight(recording);
4161
5416
  throw error;
4162
5417
  }
4163
5418
  }
4164
- const startedAtNs = timed ? readCallClock() : 0n;
4165
5419
  if (!journal) {
4166
5420
  memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes);
4167
5421
  return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
@@ -4190,7 +5444,18 @@ var createExecutionRecorder = (options, hooks = {}) => {
4190
5444
  callback,
4191
5445
  captureSuccess,
4192
5446
  (error) => {
4193
- captureCompletedThrow(recording, plan, args, parentCallId, startedAtNs, error, timed);
5447
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5448
+ captureCompletedThrow(
5449
+ recording,
5450
+ plan,
5451
+ args,
5452
+ parentCallId,
5453
+ startedAtNs,
5454
+ error,
5455
+ timed,
5456
+ void 0,
5457
+ sharedClock.end
5458
+ );
4194
5459
  settleInFlight(recording);
4195
5460
  }
4196
5461
  );
@@ -4210,7 +5475,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4210
5475
  });
4211
5476
  }
4212
5477
  const callId = ++recording.nextCallId;
4213
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
5478
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
4214
5479
  const capturedArgs = enterPayload(recording, omitCallValues, args);
4215
5480
  try {
4216
5481
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -4236,7 +5501,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4236
5501
  callback,
4237
5502
  (value) => {
4238
5503
  if (recording.journal) {
4239
- const endedAtNs = timed ? readCallClock() : void 0;
5504
+ const pending = value instanceof Promise;
5505
+ const endedAtNs = timed && !pending ? tryCallClock3() : void 0;
5506
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
4240
5507
  const returnValue = exitPayload(recording, omitCallValues, value);
4241
5508
  if (endedAtNs !== void 0) {
4242
5509
  recording.journal.finishCall(
@@ -4255,6 +5522,19 @@ var createExecutionRecorder = (options, hooks = {}) => {
4255
5522
  returnValue
4256
5523
  );
4257
5524
  }
5525
+ if (pending && timed) {
5526
+ const journal2 = recording.journal;
5527
+ sharedClock.applyEnd = (endedNs) => {
5528
+ if (endedNs === void 0 || recording.finished || recording.journal !== journal2) {
5529
+ return;
5530
+ }
5531
+ journal2.setCallTiming(
5532
+ callId,
5533
+ endedNs - recording.startedAtNs,
5534
+ endedNs - startedAtNs
5535
+ );
5536
+ };
5537
+ }
4258
5538
  stats.functionCallsCaptured++;
4259
5539
  }
4260
5540
  settleInFlight(recording);
@@ -4265,14 +5545,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
4265
5545
  return;
4266
5546
  }
4267
5547
  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
- );
5548
+ const endedAtNs = timed ? tryCallClock3() : void 0;
5549
+ if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5550
+ if (endedAtNs !== void 0) {
5551
+ recording.journal.finishCall(
5552
+ KIND_THROW,
5553
+ callId,
5554
+ endedAtNs - recording.startedAtNs,
5555
+ endedAtNs - startedAtNs,
5556
+ capturedError.value
5557
+ );
5558
+ } else {
5559
+ recording.journal.finishCall(
5560
+ KIND_THROW,
5561
+ callId,
5562
+ TIMING_UNAVAILABLE,
5563
+ TIMING_UNAVAILABLE,
5564
+ capturedError.value
5565
+ );
5566
+ }
4276
5567
  stats.functionCallsCaptured++;
4277
5568
  capturedError.commit();
4278
5569
  settleInFlight(recording);
@@ -4301,21 +5592,24 @@ var createExecutionRecorder = (options, hooks = {}) => {
4301
5592
  this.group = group;
4302
5593
  this.captureDroppedThrow = captureDroppedThrow;
4303
5594
  this.callerClaimed = false;
5595
+ this.completedAtNs = void 0;
5596
+ this.metricsSelected = false;
4304
5597
  this.metricsOpen = false;
5598
+ this.metricsMeasure = false;
4305
5599
  this.metricsFailed = false;
4306
5600
  this.metricsFunctionHandle = 0;
4307
5601
  this.metricsExecutionHandle = 0;
4308
- this.metricsStartedNs = 0n;
5602
+ this.metricsStartedNs = void 0;
4309
5603
  }
4310
5604
  claimCaller() {
4311
- if (this.callerClaimed || !durationSamplingEnabled || !this.plan) return;
5605
+ if (this.callerClaimed || !trackCallers || !this.plan) return;
4312
5606
  if (this.activeStore !== this.parentStore) return;
4313
5607
  this.previousFunctionId = this.parentStore.currentFunctionId;
4314
5608
  this.parentStore.currentFunctionId = this.plan.functionId;
4315
5609
  this.callerClaimed = true;
4316
5610
  }
4317
5611
  reclaimCaller() {
4318
- if (!durationSamplingEnabled || !this.plan || this.activeStore !== this.parentStore) return;
5612
+ if (!trackCallers || !this.plan || this.activeStore !== this.parentStore) return;
4319
5613
  this.parentStore.currentFunctionId = this.plan.functionId;
4320
5614
  this.callerClaimed = true;
4321
5615
  }
@@ -4341,6 +5635,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4341
5635
  if (this.status === "failed") return;
4342
5636
  this.status = "failed";
4343
5637
  this.metricsFailed = true;
5638
+ if (this.timed && this.completedAtNs === void 0) {
5639
+ this.completedAtNs = tryCallClock3();
5640
+ }
4344
5641
  if (this.mode === "captured") writeCapturedThrow(this, error);
4345
5642
  else if (this.mode === "suppressed" && this.plan) {
4346
5643
  captureCompletedThrow(
@@ -4351,7 +5648,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4351
5648
  this.startedAtNs,
4352
5649
  error,
4353
5650
  this.timed,
4354
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5651
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5652
+ this.completedAtNs
4355
5653
  );
4356
5654
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
4357
5655
  captureCompletedThrow(
@@ -4362,25 +5660,28 @@ var createExecutionRecorder = (options, hooks = {}) => {
4362
5660
  this.startedAtNs,
4363
5661
  error,
4364
5662
  this.timed,
4365
- this.recording.captureValues ? void 0 : ARGS_OMITTED
5663
+ this.recording.captureValues ? void 0 : ARGS_OMITTED,
5664
+ this.completedAtNs
4366
5665
  );
4367
5666
  }
4368
5667
  } catch {
4369
5668
  }
4370
5669
  }
4371
5670
  end() {
4372
- let endedAtNs;
5671
+ let endedAtNs = this.completedAtNs;
5672
+ if (endedAtNs === void 0 && this.timed) {
5673
+ endedAtNs = tryCallClock3();
5674
+ this.completedAtNs = endedAtNs;
5675
+ }
4373
5676
  if (this.metricsOpen && functionMetrics) {
4374
5677
  this.metricsOpen = false;
4375
5678
  try {
4376
- endedAtNs = readCallClock();
4377
5679
  finishMetricsCall(
4378
5680
  functionMetrics,
4379
5681
  this.metricsFunctionHandle,
4380
5682
  this.metricsExecutionHandle,
4381
- this.metricsStartedNs,
4382
5683
  this.metricsFailed,
4383
- endedAtNs
5684
+ this.metricsMeasure ? { startedNs: this.metricsStartedNs, endedNs: endedAtNs } : void 0
4384
5685
  );
4385
5686
  } catch {
4386
5687
  }
@@ -4400,8 +5701,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4400
5701
  this.group,
4401
5702
  this.parentCallId,
4402
5703
  this.startedAtNs,
4403
- this.timed ? endedAtNs ?? readCallClock() : 0n,
4404
- this.timed
5704
+ endedAtNs ?? 0n,
5705
+ this.timed && endedAtNs !== void 0
4405
5706
  );
4406
5707
  } else if (this.mode === "dropped") {
4407
5708
  const droppedBefore = this.recording.journal?.dropped ?? 0;
@@ -4475,7 +5776,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4475
5776
  };
4476
5777
  const writeCapturedExit = (frame, value, completedAtNs) => {
4477
5778
  if (!frame.recording.journal) return;
4478
- const endedAtNs = frame.timed ? completedAtNs ?? readCallClock() : void 0;
5779
+ const endedAtNs = frame.timed ? completedAtNs : void 0;
4479
5780
  const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
4480
5781
  if (endedAtNs !== void 0) {
4481
5782
  frame.recording.journal.finishCall(
@@ -4498,37 +5799,47 @@ var createExecutionRecorder = (options, hooks = {}) => {
4498
5799
  };
4499
5800
  const writeCapturedThrow = (frame, error) => {
4500
5801
  if (!frame.recording.journal) return;
4501
- const endedAtNs = readCallClock();
5802
+ const endedAtNs = frame.timed ? frame.completedAtNs : void 0;
4502
5803
  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
- );
5804
+ if (endedAtNs !== void 0) {
5805
+ frame.recording.journal.finishCall(
5806
+ KIND_THROW,
5807
+ frame.callId,
5808
+ endedAtNs - frame.recording.startedAtNs,
5809
+ endedAtNs - frame.startedAtNs,
5810
+ capturedError.value
5811
+ );
5812
+ } else {
5813
+ frame.recording.journal.finishCall(
5814
+ KIND_THROW,
5815
+ frame.callId,
5816
+ TIMING_UNAVAILABLE,
5817
+ TIMING_UNAVAILABLE,
5818
+ capturedError.value
5819
+ );
5820
+ }
4510
5821
  stats.functionCallsCaptured++;
4511
5822
  capturedError.commit();
4512
5823
  };
4513
5824
  const armCallFrameMetrics = (frame, plan) => {
4514
5825
  if (!functionMetrics || plan.excluded) return;
4515
5826
  const functionHandle = internPreparedMetrics(functionMetrics, plan);
4516
- const reuseStart = frame.timed && frame.startedAtNs !== 0n ? frame.startedAtNs : void 0;
4517
- const startedNs = startMetricsCall(
5827
+ const started = startMetricsCall(
4518
5828
  functionMetrics,
4519
5829
  functionHandle,
4520
5830
  frame.recording.metricsExecutionHandle,
4521
- reuseStart
5831
+ frame.metricsSelected ? { measure: true, startedNs: frame.timed ? frame.startedAtNs : void 0 } : { measure: false }
4522
5832
  );
4523
- if (startedNs === void 0 || functionHandle === void 0) return;
5833
+ if (!started || functionHandle === void 0) return;
4524
5834
  const executionHandle = frame.recording.metricsExecutionHandle;
4525
5835
  if (executionHandle === void 0) return;
4526
5836
  frame.metricsOpen = true;
5837
+ frame.metricsMeasure = started.measure;
4527
5838
  frame.metricsFunctionHandle = functionHandle;
4528
5839
  frame.metricsExecutionHandle = executionHandle;
4529
- frame.metricsStartedNs = startedNs;
5840
+ frame.metricsStartedNs = started.startedNs;
4530
5841
  };
4531
- const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow) => {
5842
+ const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected) => {
4532
5843
  const frame = new CallFrame(
4533
5844
  mode,
4534
5845
  recording,
@@ -4544,6 +5855,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4544
5855
  group,
4545
5856
  captureDroppedThrow
4546
5857
  );
5858
+ frame.metricsSelected = selected;
4547
5859
  frame.claimCaller();
4548
5860
  enterStore(frame, parentStore);
4549
5861
  armCallFrameMetrics(frame, plan);
@@ -4557,6 +5869,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4557
5869
  }
4558
5870
  if (store.recording.finished) {
4559
5871
  if (!store.recording.budgetExpired && !store.recording.evicted) return noopHandle2;
5872
+ const duration2 = planInvocationDuration(store.recording, plan, store.currentFunctionId);
5873
+ const start2 = invocationStart(duration2.measure);
4560
5874
  const expiredStore = { recording: store.recording };
4561
5875
  const expired = new CallFrame(
4562
5876
  "expired",
@@ -4567,12 +5881,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
4567
5881
  EMPTY_ARGS,
4568
5882
  false,
4569
5883
  void 0,
4570
- 0n,
4571
- true,
5884
+ start2.startedAtNs,
5885
+ start2.timed,
4572
5886
  0,
4573
5887
  void 0,
4574
5888
  false
4575
5889
  );
5890
+ expired.metricsSelected = duration2.selected;
4576
5891
  armCallFrameMetrics(expired, plan);
4577
5892
  return expired;
4578
5893
  }
@@ -4582,6 +5897,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4582
5897
  const parentCallId = store.currentCallId;
4583
5898
  if (skipCapture(store, plan)) {
4584
5899
  stats.functionCallsExcluded++;
5900
+ const excludedDuration = plan.excluded ? { selected: false, measure: false } : planInvocationDuration(recording, plan, store.currentFunctionId);
5901
+ const start2 = invocationStart(excludedDuration.measure);
4585
5902
  const excludedStore = { ...store, suppressCapture: true };
4586
5903
  const frame = new CallFrame(
4587
5904
  "excluded",
@@ -4592,12 +5909,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
4592
5909
  EMPTY_ARGS,
4593
5910
  false,
4594
5911
  void 0,
4595
- 0n,
4596
- true,
5912
+ start2.startedAtNs,
5913
+ start2.timed,
4597
5914
  0,
4598
5915
  void 0,
4599
5916
  false
4600
5917
  );
5918
+ frame.metricsSelected = excludedDuration.selected;
4601
5919
  enterStore(frame, excludedStore);
4602
5920
  armCallFrameMetrics(frame, plan);
4603
5921
  return frame;
@@ -4610,8 +5928,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
4610
5928
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
4611
5929
  } catch {
4612
5930
  }
4613
- const timed = durationSamplingEnabled ? decideCallTiming(recording, plan, store.currentFunctionId) : true;
4614
- const startedAtNs = timed ? readCallClock() : 0n;
5931
+ const duration = planInvocationDuration(recording, plan, store.currentFunctionId);
5932
+ const start = invocationStart(duration.measure);
5933
+ const timed = start.timed;
5934
+ const startedAtNs = start.startedAtNs;
4615
5935
  const parentStore = store;
4616
5936
  const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
4617
5937
  if (group.observedCalls > capturedCallLimitFor(recording)) {
@@ -4626,7 +5946,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4626
5946
  startedAtNs,
4627
5947
  timed,
4628
5948
  group,
4629
- false
5949
+ false,
5950
+ duration.selected
4630
5951
  );
4631
5952
  }
4632
5953
  if (!journal) {
@@ -4642,7 +5963,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4642
5963
  startedAtNs,
4643
5964
  timed,
4644
5965
  group,
4645
- false
5966
+ false,
5967
+ duration.selected
4646
5968
  );
4647
5969
  }
4648
5970
  if (!journal.canStartCall()) {
@@ -4657,7 +5979,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4657
5979
  startedAtNs,
4658
5980
  timed,
4659
5981
  group,
4660
- true
5982
+ true,
5983
+ duration.selected
4661
5984
  );
4662
5985
  }
4663
5986
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
@@ -4672,11 +5995,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
4672
5995
  startedAtNs,
4673
5996
  timed,
4674
5997
  group,
4675
- false
5998
+ false,
5999
+ duration.selected
4676
6000
  );
4677
6001
  }
4678
6002
  const callId = ++recording.nextCallId;
4679
- const enterTimestampNs = timed ? readCallClock() - recording.startedAtNs : TIMING_UNAVAILABLE;
6003
+ const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
4680
6004
  const capturedArgs = enterPayload(recording, omitCallValues, args);
4681
6005
  try {
4682
6006
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
@@ -4693,7 +6017,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4693
6017
  startedAtNs,
4694
6018
  timed,
4695
6019
  group,
4696
- false
6020
+ false,
6021
+ duration.selected
4697
6022
  );
4698
6023
  }
4699
6024
  const callStore = callStoreFor(store, plan.functionId, callId);
@@ -4712,6 +6037,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4712
6037
  group,
4713
6038
  false
4714
6039
  );
6040
+ captured.metricsSelected = duration.selected;
4715
6041
  enterStore(captured, callStore);
4716
6042
  armCallFrameMetrics(captured, plan);
4717
6043
  return captured;
@@ -4781,7 +6107,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4781
6107
  enterPreparedFunction,
4782
6108
  trace,
4783
6109
  close: () => {
4784
- durationSamples?.stop();
6110
+ durationSampler?.stop();
4785
6111
  },
4786
6112
  getStats: () => ({
4787
6113
  ...stats,
@@ -4838,14 +6164,14 @@ var installAutomaticExecutionRuntime = (execution) => {
4838
6164
  // src/execution-recorder/bind-adaptive-recorder.ts
4839
6165
  import {
4840
6166
  resolveClientActivation,
4841
- resolveEndpointUrls as resolveEndpointUrls2
6167
+ resolveEndpointUrls as resolveEndpointUrls3
4842
6168
  } from "@rasputin-ai/core";
4843
6169
 
4844
6170
  // src/execution-recorder/execution-recording-sync.ts
4845
6171
  import {
4846
6172
  copyRedactKeys,
4847
- defaultIngestFetch,
4848
- encodeJsonRequestBodyAsync,
6173
+ defaultIngestFetch as defaultIngestFetch2,
6174
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
4849
6175
  MAX_REDACT_KEYS
4850
6176
  } from "@rasputin-ai/core";
4851
6177
 
@@ -5026,9 +6352,8 @@ var createSerializerCache = (options) => {
5026
6352
  // src/execution-recorder/execution-recording-sync.ts
5027
6353
  var MAX_CACHE_ENTRIES = 1024;
5028
6354
  var MAX_PENDING_NOTIFIES = 32;
5029
- var MAX_PENDING_TYPES = 64;
5030
- var DEFAULT_POLL_INTERVAL_MS = 1e4;
5031
- var REQUEST_TIMEOUT_MS = 5e3;
6355
+ var DEFAULT_POLL_INTERVAL_MS = 3e4;
6356
+ var REQUEST_TIMEOUT_MS2 = 5e3;
5032
6357
  var MAX_RETRIES = 5;
5033
6358
  var MAX_POLL_JITTER_MS = 2e3;
5034
6359
  var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
@@ -5043,7 +6368,7 @@ var classifyHttpFailure = (status) => {
5043
6368
  if (status >= 500) return "server_error";
5044
6369
  return "non_retryable_http";
5045
6370
  };
5046
- var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
6371
+ var backoffMs2 = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
5047
6372
  var abortFrom = (parent, child) => {
5048
6373
  const onAbort = () => child.abort();
5049
6374
  parent.addEventListener("abort", onAbort, { once: true });
@@ -5053,7 +6378,7 @@ var abortFrom = (parent, child) => {
5053
6378
  var createExecutionRecordingCoordinator = (options) => {
5054
6379
  const environment = options.environment;
5055
6380
  const nowMs = () => options.nowMs?.() ?? Date.now();
5056
- const fetchFn = options.fetch ?? defaultIngestFetch();
6381
+ const fetchFn = options.fetch ?? defaultIngestFetch2();
5057
6382
  const instanceId = crypto.randomUUID();
5058
6383
  const startedAt = /* @__PURE__ */ new Date();
5059
6384
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
@@ -5061,11 +6386,10 @@ var createExecutionRecordingCoordinator = (options) => {
5061
6386
  const serializers = createSerializerCache(options.recorderOptions);
5062
6387
  const cache = /* @__PURE__ */ new Map();
5063
6388
  const pending = /* @__PURE__ */ new Map();
5064
- const catalog = /* @__PURE__ */ new Map();
5065
6389
  const sessionsById = /* @__PURE__ */ new Map();
5066
6390
  const completedSessionIds = /* @__PURE__ */ new Set();
5067
6391
  const recordings = [];
5068
- const capabilities = ["catalog", "manual_sessions", "settings_overrides"];
6392
+ const capabilities = ["manual_sessions", "settings_overrides"];
5069
6393
  let closed = false;
5070
6394
  let closing = false;
5071
6395
  let sessionsDirty = true;
@@ -5190,7 +6514,7 @@ var createExecutionRecordingCoordinator = (options) => {
5190
6514
  };
5191
6515
  const withRequestTimeout = async (signal, run) => {
5192
6516
  const request = new AbortController();
5193
- const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS);
6517
+ const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
5194
6518
  timer.unref?.();
5195
6519
  const stopParent = abortFrom(signal, request);
5196
6520
  const stopCancel = abortFrom(cancelWork.signal, request);
@@ -5250,7 +6574,7 @@ var createExecutionRecordingCoordinator = (options) => {
5250
6574
  notifyFailures++;
5251
6575
  return false;
5252
6576
  }
5253
- await wait(backoffMs(attempt), signal);
6577
+ await wait(backoffMs2(attempt), signal);
5254
6578
  } catch (error) {
5255
6579
  if (signal.aborted || error instanceof Error && error.name === "AbortError") {
5256
6580
  rememberFailure("aborted");
@@ -5261,7 +6585,7 @@ var createExecutionRecordingCoordinator = (options) => {
5261
6585
  notifyFailures++;
5262
6586
  return false;
5263
6587
  }
5264
- await wait(backoffMs(attempt), signal);
6588
+ await wait(backoffMs2(attempt), signal);
5265
6589
  }
5266
6590
  }
5267
6591
  return false;
@@ -5309,14 +6633,6 @@ var createExecutionRecordingCoordinator = (options) => {
5309
6633
  if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
5310
6634
  void drainNotifies(notifySignal());
5311
6635
  };
5312
- const rememberCatalog = (key, atMs) => {
5313
- if (key.length === 0 || key.length > MAX_EXECUTION_TYPE_KEY_LENGTH) return;
5314
- if (catalog.size >= MAX_CACHE_ENTRIES && !catalog.has(key)) {
5315
- const oldest = catalog.keys().next().value;
5316
- if (oldest !== void 0) catalog.delete(oldest);
5317
- }
5318
- catalog.set(key, atMs);
5319
- };
5320
6636
  const applyCompletedSessionIds = (value) => {
5321
6637
  if (!Array.isArray(value)) return;
5322
6638
  for (const entry of value) {
@@ -5376,17 +6692,8 @@ var createExecutionRecordingCoordinator = (options) => {
5376
6692
  trimCache();
5377
6693
  for (const key of seen) pending.delete(key);
5378
6694
  };
5379
- const catalogTypes = () => {
5380
- const entries = [];
5381
- for (const [executionKey, lastSeenAtMs] of catalog) {
5382
- entries.push({ executionKey, lastSeenAtMs });
5383
- if (entries.length >= MAX_PENDING_TYPES) break;
5384
- }
5385
- return entries;
5386
- };
5387
6695
  const syncOnce = async (signal) => {
5388
6696
  if (closed) return;
5389
- const types2 = catalogTypes();
5390
6697
  try {
5391
6698
  const { response, body: payload } = await postJson(
5392
6699
  options.syncUrl,
@@ -5402,11 +6709,7 @@ var createExecutionRecordingCoordinator = (options) => {
5402
6709
  reported_mode: options.mode,
5403
6710
  reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
5404
6711
  capabilities
5405
- },
5406
- types: types2.map((entry) => ({
5407
- execution_key: entry.executionKey,
5408
- last_seen_at: new Date(entry.lastSeenAtMs).toISOString()
5409
- }))
6712
+ }
5410
6713
  },
5411
6714
  signal,
5412
6715
  async (syncResponse) => {
@@ -5421,14 +6724,6 @@ var createExecutionRecordingCoordinator = (options) => {
5421
6724
  }
5422
6725
  applyActivations(payload?.activations);
5423
6726
  applySessions(payload?.sessions);
5424
- for (const entry of types2) {
5425
- const current = catalog.get(entry.executionKey);
5426
- if (current === void 0) continue;
5427
- catalog.delete(entry.executionKey);
5428
- if (current !== entry.lastSeenAtMs) {
5429
- catalog.set(entry.executionKey, current);
5430
- }
5431
- }
5432
6727
  } catch (error) {
5433
6728
  if (signal.aborted || error instanceof Error && error.name === "AbortError") {
5434
6729
  rememberFailure("aborted");
@@ -5459,7 +6754,7 @@ var createExecutionRecordingCoordinator = (options) => {
5459
6754
  if (combined.aborted) return false;
5460
6755
  let encoded;
5461
6756
  try {
5462
- encoded = await encodeJsonRequestBodyAsync(
6757
+ encoded = await encodeJsonRequestBodyAsync2(
5463
6758
  {
5464
6759
  instance_id: instanceId,
5465
6760
  recordings: batch.map((item) => ({
@@ -5510,7 +6805,7 @@ var createExecutionRecordingCoordinator = (options) => {
5510
6805
  rememberFailure(kind);
5511
6806
  if (kind === "non_retryable_http") return true;
5512
6807
  if (attempt === MAX_RETRIES) return false;
5513
- await wait(backoffMs(attempt), combined);
6808
+ await wait(backoffMs2(attempt), combined);
5514
6809
  } catch (error) {
5515
6810
  if (combined.aborted || error instanceof Error && error.name === "AbortError") {
5516
6811
  rememberFailure("aborted");
@@ -5518,7 +6813,7 @@ var createExecutionRecordingCoordinator = (options) => {
5518
6813
  }
5519
6814
  rememberFailure("network_error");
5520
6815
  if (attempt === MAX_RETRIES) return false;
5521
- await wait(backoffMs(attempt), combined);
6816
+ await wait(backoffMs2(attempt), combined);
5522
6817
  }
5523
6818
  }
5524
6819
  return false;
@@ -5593,9 +6888,6 @@ var createExecutionRecordingCoordinator = (options) => {
5593
6888
  }
5594
6889
  return void 0;
5595
6890
  };
5596
- const observeType = (executionKeyValue) => {
5597
- rememberCatalog(executionKeyValue, nowMs());
5598
- };
5599
6891
  const enqueueRecording = (payload) => {
5600
6892
  if (closed || closing) return;
5601
6893
  recordings.push(payload);
@@ -5630,7 +6922,6 @@ var createExecutionRecordingCoordinator = (options) => {
5630
6922
  activate,
5631
6923
  peekSessions,
5632
6924
  consumeSession,
5633
- observeType,
5634
6925
  enqueueRecording,
5635
6926
  getStats: () => ({
5636
6927
  adaptiveNotifyFailures: notifyFailures,
@@ -5692,9 +6983,9 @@ var bindAdaptiveRecorder = (input) => {
5692
6983
  const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
5693
6984
  environment: activation.environment,
5694
6985
  ingestToken: activation.ingestToken,
5695
- activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5696
- syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5697
- recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
6986
+ activateUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingActivateUrl,
6987
+ syncUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingSyncUrl,
6988
+ recordingsUrl: resolveEndpointUrls3(activation.apiUrl).executionRecordingRecordingsUrl,
5698
6989
  sdkName: input.sdkName,
5699
6990
  sdkVersion: input.sdkVersion,
5700
6991
  release: activation.release,
@@ -5710,10 +7001,11 @@ var bindAdaptiveRecorder = (input) => {
5710
7001
  recorderHooks.getStats = coordinator.getStats;
5711
7002
  recorderHooks.sessionCaptureSnapshot = coordinator.peekSessions;
5712
7003
  recorderHooks.consumeSession = coordinator.consumeSession;
5713
- recorderHooks.observeExecutionType = coordinator.observeType;
5714
7004
  recorderHooks.onSessionRecording = coordinator.enqueueRecording;
5715
7005
  }
5716
7006
  if (input.functionMetrics) recorderHooks.functionMetrics = input.functionMetrics;
7007
+ if (input.executionMetrics) recorderHooks.executionMetrics = input.executionMetrics;
7008
+ if (input.durationSampler) recorderHooks.durationSampler = input.durationSampler;
5717
7009
  const runtime = createExecutionRecorder(
5718
7010
  { ...options, enabled: input.recorderEnabled },
5719
7011
  recorderHooks
@@ -5722,34 +7014,35 @@ var bindAdaptiveRecorder = (input) => {
5722
7014
  };
5723
7015
 
5724
7016
  // src/function-metrics/bind-function-metrics.ts
5725
- import { randomUUID as randomUUID2 } from "node:crypto";
7017
+ import { randomUUID as randomUUID4 } from "node:crypto";
5726
7018
  import {
5727
- defaultIngestFetch as defaultIngestFetch2,
5728
- resolveEndpointUrls as resolveEndpointUrls3
7019
+ defaultIngestFetch as defaultIngestFetch3,
7020
+ resolveEndpointUrls as resolveEndpointUrls4
5729
7021
  } from "@rasputin-ai/core";
5730
7022
 
5731
7023
  // src/function-metrics/function-metrics-collector.ts
5732
7024
  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,
7025
+ durationHistogramBucket as durationHistogramBucket2,
7026
+ FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT as FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2,
7027
+ FUNCTION_METRICS_MAX_ACTIVE_SERIES as FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7028
+ FUNCTION_METRICS_MAX_BUFFERED_MS as FUNCTION_METRICS_MAX_BUFFERED_MS2,
7029
+ FUNCTION_METRICS_MAX_EXECUTION_TYPES as FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
5738
7030
  FUNCTION_METRICS_MAX_FUNCTIONS,
5739
- FUNCTION_METRICS_MAX_MINUTE_ROWS,
5740
- FUNCTION_METRICS_MAX_STATE_BYTES,
5741
- FUNCTION_METRICS_MINUTE_MS,
7031
+ FUNCTION_METRICS_MAX_MINUTE_ROWS as FUNCTION_METRICS_MAX_MINUTE_ROWS2,
7032
+ FUNCTION_METRICS_MAX_STATE_BYTES as FUNCTION_METRICS_MAX_STATE_BYTES2,
7033
+ FUNCTION_METRICS_MEASUREMENT_FORMAT as FUNCTION_METRICS_MEASUREMENT_FORMAT2,
7034
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS3,
7035
+ FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT as FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2,
5742
7036
  functionIdentityKey,
5743
- isCanonicalFunctionMetricsExecutionKey
7037
+ isCanonicalFunctionMetricsExecutionKey as isCanonicalFunctionMetricsExecutionKey2
5744
7038
  } from "@rasputin-ai/core";
5745
7039
 
5746
7040
  // src/function-metrics/function-metrics-batches.ts
5747
- import { randomUUID } from "node:crypto";
7041
+ import { randomUUID as randomUUID3 } from "node:crypto";
5748
7042
  import {
5749
- FUNCTION_METRICS_MEASUREMENT_FORMAT,
5750
7043
  FUNCTION_METRICS_SCHEMA_VERSION
5751
7044
  } from "@rasputin-ai/core";
5752
- var emptyCoverage = (buckets) => ({
7045
+ var emptyCoverage3 = (buckets) => ({
5753
7046
  covered_bucket_starts: buckets,
5754
7047
  skipped_unresolved_execution_type: 0,
5755
7048
  dropped_active_series: 0,
@@ -5758,8 +7051,8 @@ var emptyCoverage = (buckets) => ({
5758
7051
  dropped_late_completion: 0,
5759
7052
  dropped_unexportable: 0
5760
7053
  });
5761
- var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
5762
- var sparseHistogram = (histogram) => {
7054
+ var bucketStart2 = (minute) => new Date(minute * 6e4).toISOString();
7055
+ var sparseHistogram2 = (histogram) => {
5763
7056
  const cells = [];
5764
7057
  for (let index = 0; index < histogram.length; index += 1) {
5765
7058
  const count = histogram[index] ?? 0;
@@ -5767,10 +7060,10 @@ var sparseHistogram = (histogram) => {
5767
7060
  }
5768
7061
  return cells;
5769
7062
  };
5770
- var toMinute = (row, functionIndex, executionTypeIndex) => ({
7063
+ var toMinute2 = (row, functionIndex, executionTypeIndex) => ({
5771
7064
  function_index: functionIndex,
5772
7065
  execution_type_index: executionTypeIndex,
5773
- bucket_start: bucketStart(row.minute),
7066
+ bucket_start: bucketStart2(row.minute),
5774
7067
  started_calls: row.series.started,
5775
7068
  completed_calls: row.series.completed,
5776
7069
  failed_calls: row.series.failed,
@@ -5778,7 +7071,7 @@ var toMinute = (row, functionIndex, executionTypeIndex) => ({
5778
7071
  duration_sample_sum_us: row.series.sampleSumUs,
5779
7072
  duration_sample_min_us: row.series.sampleMinUs,
5780
7073
  duration_sample_max_us: row.series.sampleMaxUs,
5781
- duration_histogram: sparseHistogram(row.series.histogram),
7074
+ duration_histogram: sparseHistogram2(row.series.histogram),
5782
7075
  invalid_timing_count: row.series.invalidTiming
5783
7076
  });
5784
7077
  var rowsFromQueue = (queued) => {
@@ -5828,7 +7121,7 @@ var chunkRows = (rows, maxFunctions, maxExecutionTypes, maxMinuteRows) => {
5828
7121
  flush();
5829
7122
  return chunks;
5830
7123
  };
5831
- var batchForChunk = (draft, rows, coverage) => {
7124
+ var batchForChunk2 = (draft, rows, coverage) => {
5832
7125
  const functionIndexes = /* @__PURE__ */ new Map();
5833
7126
  const executionIndexes = /* @__PURE__ */ new Map();
5834
7127
  const functions = [];
@@ -5851,12 +7144,12 @@ var batchForChunk = (draft, rows, coverage) => {
5851
7144
  executionIndexes.set(row.executionHandle, executionTypeIndex);
5852
7145
  executionTypes.push({ execution_key: executionKey });
5853
7146
  }
5854
- minutes.push(toMinute(row, functionIndex, executionTypeIndex));
7147
+ minutes.push(toMinute2(row, functionIndex, executionTypeIndex));
5855
7148
  }
5856
7149
  const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
5857
7150
  return {
5858
7151
  schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5859
- measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
7152
+ measurement_format: draft.measurementFormat,
5860
7153
  producer_id: draft.producerId,
5861
7154
  batch_id: draft.batchId(),
5862
7155
  environment: draft.environment,
@@ -5877,7 +7170,7 @@ var functionMetricsBatchesFromQueue = (draft) => {
5877
7170
  return [
5878
7171
  {
5879
7172
  schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
5880
- measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
7173
+ measurement_format: draft.measurementFormat,
5881
7174
  producer_id: draft.producerId,
5882
7175
  batch_id: draft.batchId(),
5883
7176
  environment: draft.environment,
@@ -5891,29 +7184,29 @@ var functionMetricsBatchesFromQueue = (draft) => {
5891
7184
  }
5892
7185
  const chunks = chunkRows(rows, draft.maxFunctions, draft.maxExecutionTypes, draft.maxMinuteRows);
5893
7186
  return chunks.map(
5894
- (chunk, index) => batchForChunk(draft, chunk, index === 0 ? draft.coverage : emptyCoverage([]))
7187
+ (chunk, index) => batchForChunk2(draft, chunk, index === 0 ? draft.coverage : emptyCoverage3([]))
5895
7188
  );
5896
7189
  };
5897
- var newFunctionMetricsBatchId = () => randomUUID();
7190
+ var newFunctionMetricsBatchId = () => randomUUID3();
5898
7191
 
5899
7192
  // src/function-metrics/function-metrics-collector.ts
5900
- var SERIES_BYTES = 256;
5901
- var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
7193
+ var SERIES_BYTES2 = 256;
7194
+ var HISTOGRAM_BYTES2 = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2 * 4;
5902
7195
  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,
7196
+ var MAX_ELAPSED_NS2 = BigInt(Number.MAX_SAFE_INTEGER);
7197
+ var defaultLimits2 = () => ({
7198
+ maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES2,
7199
+ maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES2,
7200
+ maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS2 / FUNCTION_METRICS_MINUTE_MS3,
5908
7201
  maxFunctions: FUNCTION_METRICS_MAX_FUNCTIONS,
5909
- maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
5910
- maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
7202
+ maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES2,
7203
+ maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS2
5911
7204
  });
5912
- var defaultClock = () => ({
7205
+ var defaultClock2 = () => ({
5913
7206
  monotonicNs: () => process.hrtime.bigint(),
5914
7207
  wallTimeMs: () => Date.now()
5915
7208
  });
5916
- var emptyCoverage2 = () => ({
7209
+ var emptyCoverage4 = () => ({
5917
7210
  covered_bucket_starts: [],
5918
7211
  skipped_unresolved_execution_type: 0,
5919
7212
  dropped_active_series: 0,
@@ -5922,23 +7215,23 @@ var emptyCoverage2 = () => ({
5922
7215
  dropped_late_completion: 0,
5923
7216
  dropped_unexportable: 0
5924
7217
  });
5925
- var note = (coverage, counter, amount = 1) => {
7218
+ var note2 = (coverage, counter, amount = 1) => {
5926
7219
  const next = coverage[counter] + amount;
5927
7220
  coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
5928
7221
  };
5929
- var countSeries = (table) => {
7222
+ var countSeries2 = (table) => {
5930
7223
  let count = 0;
5931
7224
  for (const byExecution of table.values()) count += byExecution.size;
5932
7225
  return count;
5933
7226
  };
5934
- var tableBytes = (table) => {
7227
+ var tableBytes2 = (table) => {
5935
7228
  let bytes = 0;
5936
7229
  for (const byExecution of table.values()) {
5937
7230
  for (const series of byExecution.values()) bytes += series.bytes;
5938
7231
  }
5939
7232
  return bytes;
5940
7233
  };
5941
- var discardedMarks = (table) => {
7234
+ var discardedMarks2 = (table) => {
5942
7235
  let marks = 0;
5943
7236
  for (const byExecution of table.values()) {
5944
7237
  for (const series of byExecution.values()) {
@@ -5948,12 +7241,12 @@ var discardedMarks = (table) => {
5948
7241
  }
5949
7242
  return marks;
5950
7243
  };
5951
- var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
5952
- var copySeries = (series) => ({
7244
+ var seriesHasMarks2 = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
7245
+ var copySeries2 = (series) => ({
5953
7246
  ...series,
5954
7247
  histogram: series.histogram.slice()
5955
7248
  });
5956
- var resetSeries = (series) => {
7249
+ var resetSeries2 = (series) => {
5957
7250
  series.started = 0;
5958
7251
  series.completed = 0;
5959
7252
  series.failed = 0;
@@ -5964,13 +7257,13 @@ var resetSeries = (series) => {
5964
7257
  series.invalidTiming = 0;
5965
7258
  series.histogram.fill(0);
5966
7259
  };
5967
- var snapshotAndReset = (table) => {
7260
+ var snapshotAndReset2 = (table) => {
5968
7261
  const snapshot = /* @__PURE__ */ new Map();
5969
7262
  for (const [functionHandle, byExecution] of table) {
5970
7263
  const copied = /* @__PURE__ */ new Map();
5971
7264
  for (const [executionHandle, series] of byExecution) {
5972
- if (seriesHasMarks(series)) copied.set(executionHandle, copySeries(series));
5973
- resetSeries(series);
7265
+ if (seriesHasMarks2(series)) copied.set(executionHandle, copySeries2(series));
7266
+ resetSeries2(series);
5974
7267
  }
5975
7268
  if (copied.size > 0) snapshot.set(functionHandle, copied);
5976
7269
  }
@@ -5985,10 +7278,11 @@ var declarationAccepted = (declaration) => {
5985
7278
  return true;
5986
7279
  };
5987
7280
  var createFunctionMetricsCollector = (options) => {
5988
- const limits = { ...defaultLimits(), ...options.limits };
5989
- const clock = options.clock ?? defaultClock();
7281
+ const limits = { ...defaultLimits2(), ...options.limits };
7282
+ const clock = options.clock ?? defaultClock2();
5990
7283
  const batchId = options.batchId ?? newFunctionMetricsBatchId;
5991
- const coverage = emptyCoverage2();
7284
+ const measurementFormat = options.sampledMeasurementFormat ? FUNCTION_METRICS_SAMPLED_MEASUREMENT_FORMAT2 : FUNCTION_METRICS_MEASUREMENT_FORMAT2;
7285
+ const coverage = emptyCoverage4();
5992
7286
  const functions = [];
5993
7287
  const functionHandleByRuntimeId = /* @__PURE__ */ new Map();
5994
7288
  const executionKeys = [];
@@ -6002,7 +7296,7 @@ var createFunctionMetricsCollector = (options) => {
6002
7296
  let sealed = false;
6003
7297
  const reserve = (bytes) => {
6004
7298
  if (stateBytes > limits.maxStateBytes - bytes) {
6005
- note(coverage, "dropped_byte_budget");
7299
+ note2(coverage, "dropped_byte_budget");
6006
7300
  return false;
6007
7301
  }
6008
7302
  stateBytes += bytes;
@@ -6010,17 +7304,17 @@ var createFunctionMetricsCollector = (options) => {
6010
7304
  };
6011
7305
  const internDeclaration = (declaration) => {
6012
7306
  if (!declaration) {
6013
- note(coverage, "dropped_unexportable");
7307
+ note2(coverage, "dropped_unexportable");
6014
7308
  return void 0;
6015
7309
  }
6016
7310
  const existing = functionHandleByRuntimeId.get(declaration.runtime_id);
6017
7311
  if (existing !== void 0) return existing;
6018
7312
  if (!declarationAccepted(declaration)) {
6019
- note(coverage, "dropped_unexportable");
7313
+ note2(coverage, "dropped_unexportable");
6020
7314
  return void 0;
6021
7315
  }
6022
7316
  if (functions.length >= limits.maxFunctions) {
6023
- note(coverage, "dropped_unexportable");
7317
+ note2(coverage, "dropped_unexportable");
6024
7318
  return void 0;
6025
7319
  }
6026
7320
  if (!reserve(DECLARATION_BYTES + declaration.runtime_id.length)) return void 0;
@@ -6030,11 +7324,11 @@ var createFunctionMetricsCollector = (options) => {
6030
7324
  return handle;
6031
7325
  };
6032
7326
  const internExecutionKey = (key) => {
6033
- if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
7327
+ if (!key || !isCanonicalFunctionMetricsExecutionKey2(key)) return void 0;
6034
7328
  const existing = executionHandleByKey.get(key);
6035
7329
  if (existing !== void 0) return existing;
6036
7330
  if (executionKeys.length >= limits.maxExecutionTypes) {
6037
- note(coverage, "dropped_unexportable");
7331
+ note2(coverage, "dropped_unexportable");
6038
7332
  return void 0;
6039
7333
  }
6040
7334
  if (!reserve(key.length)) return void 0;
@@ -6057,10 +7351,10 @@ var createFunctionMetricsCollector = (options) => {
6057
7351
  const existing = byExecution.get(executionHandle);
6058
7352
  if (existing) return existing;
6059
7353
  if (activeSeries >= limits.maxActiveSeries) {
6060
- note(coverage, "dropped_active_series");
7354
+ note2(coverage, "dropped_active_series");
6061
7355
  return void 0;
6062
7356
  }
6063
- if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
7357
+ if (!reserve(SERIES_BYTES2 + HISTOGRAM_BYTES2)) return void 0;
6064
7358
  const series = {
6065
7359
  started: 0,
6066
7360
  completed: 0,
@@ -6070,15 +7364,15 @@ var createFunctionMetricsCollector = (options) => {
6070
7364
  sampleMinUs: null,
6071
7365
  sampleMaxUs: null,
6072
7366
  invalidTiming: 0,
6073
- histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
6074
- bytes: SERIES_BYTES + HISTOGRAM_BYTES
7367
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT2),
7368
+ bytes: SERIES_BYTES2 + HISTOGRAM_BYTES2
6075
7369
  };
6076
7370
  byExecution.set(executionHandle, series);
6077
7371
  activeSeries += 1;
6078
7372
  return series;
6079
7373
  };
6080
7374
  const appendQueue = (entry) => {
6081
- if (discardedMarks(entry.series) === 0) {
7375
+ if (discardedMarks2(entry.series) === 0) {
6082
7376
  stateBytes -= entry.bytes;
6083
7377
  if (stateBytes < 0) stateBytes = 0;
6084
7378
  return;
@@ -6090,14 +7384,14 @@ var createFunctionMetricsCollector = (options) => {
6090
7384
  if (!dropped) break;
6091
7385
  stateBytes -= dropped.bytes;
6092
7386
  if (stateBytes < 0) stateBytes = 0;
6093
- note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
7387
+ note2(coverage, "dropped_queue_budget", discardedMarks2(dropped.series));
6094
7388
  }
6095
7389
  };
6096
7390
  const closeMinute = (minute, table) => {
6097
7391
  active.delete(minute);
6098
- activeSeries -= countSeries(table);
7392
+ activeSeries -= countSeries2(table);
6099
7393
  if (minute > lastClosedMinute) lastClosedMinute = minute;
6100
- appendQueue({ minute, series: table, bytes: tableBytes(table) });
7394
+ appendQueue({ minute, series: table, bytes: tableBytes2(table) });
6101
7395
  };
6102
7396
  const rotate = (currentMinute) => {
6103
7397
  for (const minute of [...active.keys()]) {
@@ -6115,7 +7409,7 @@ var createFunctionMetricsCollector = (options) => {
6115
7409
  };
6116
7410
  const snapshotActive = () => {
6117
7411
  for (const [minute, table] of active) {
6118
- appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
7412
+ appendQueue({ minute, series: snapshotAndReset2(table), bytes: 0 });
6119
7413
  }
6120
7414
  };
6121
7415
  const moveAllActive = () => {
@@ -6139,14 +7433,34 @@ var createFunctionMetricsCollector = (options) => {
6139
7433
  series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
6140
7434
  return true;
6141
7435
  };
7436
+ const rememberOutcome = (series, failed) => {
7437
+ const completed = series.completed + 1;
7438
+ const failures = series.failed + (failed ? 1 : 0);
7439
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
7440
+ series.completed = completed;
7441
+ series.failed = failures;
7442
+ return true;
7443
+ };
7444
+ const rememberInvalidTiming = (series, failed) => {
7445
+ const completed = series.completed + 1;
7446
+ const failures = series.failed + (failed ? 1 : 0);
7447
+ const invalidTiming = series.invalidTiming + 1;
7448
+ if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures) || !Number.isSafeInteger(invalidTiming)) {
7449
+ return false;
7450
+ }
7451
+ series.completed = completed;
7452
+ series.failed = failures;
7453
+ series.invalidTiming = invalidTiming;
7454
+ return true;
7455
+ };
6142
7456
  const rememberCompletion = (series, startedNs, failed, endedNs) => {
6143
7457
  const completed = series.completed + 1;
6144
7458
  const failures = series.failed + (failed ? 1 : 0);
6145
7459
  if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
6146
7460
  const elapsed = endedNs - startedNs;
6147
7461
  const durationUs = Number(elapsed) / 1e3;
6148
- const placed = durationHistogramBucket(durationUs);
6149
- const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
7462
+ const placed = durationHistogramBucket2(durationUs);
7463
+ const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS2;
6150
7464
  const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
6151
7465
  if (!sampled) {
6152
7466
  const invalidTiming = series.invalidTiming + 1;
@@ -6157,73 +7471,99 @@ var createFunctionMetricsCollector = (options) => {
6157
7471
  series.failed = failures;
6158
7472
  return true;
6159
7473
  };
6160
- const startCall = (functionHandle, executionHandle, startedNs) => {
7474
+ const startCall = (functionHandle, executionHandle, callOptions) => {
6161
7475
  if (sealed) {
6162
- note(coverage, "dropped_unexportable");
7476
+ note2(coverage, "dropped_unexportable");
6163
7477
  return void 0;
6164
7478
  }
6165
7479
  if (executionHandle === void 0) {
6166
- note(coverage, "skipped_unresolved_execution_type");
7480
+ note2(coverage, "skipped_unresolved_execution_type");
6167
7481
  return void 0;
6168
7482
  }
6169
- const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
7483
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
6170
7484
  rotateIfNeeded(minute);
6171
7485
  if (minute <= lastClosedMinute) {
6172
- note(coverage, "dropped_late_completion");
7486
+ note2(coverage, "dropped_late_completion");
6173
7487
  return void 0;
6174
7488
  }
6175
7489
  const series = ensureSeries(minute, functionHandle, executionHandle);
6176
7490
  if (!series) return void 0;
6177
7491
  const started = series.started + 1;
6178
7492
  if (!Number.isSafeInteger(started)) {
6179
- note(coverage, "dropped_unexportable");
7493
+ note2(coverage, "dropped_unexportable");
6180
7494
  return void 0;
6181
7495
  }
6182
7496
  series.started = started;
6183
- return startedNs ?? clock.monotonicNs();
7497
+ const measure = callOptions?.measure !== false;
7498
+ if (!measure) return { measure: false };
7499
+ if (callOptions && "startedNs" in callOptions) {
7500
+ return { measure: true, startedNs: callOptions.startedNs };
7501
+ }
7502
+ try {
7503
+ return { measure: true, startedNs: clock.monotonicNs() };
7504
+ } catch {
7505
+ return { measure: true };
7506
+ }
6184
7507
  };
6185
- const finishCall = (functionHandle, executionHandle, startedNs, failed, endedNs) => {
7508
+ const finishCall = (functionHandle, executionHandle, failed, timing) => {
6186
7509
  if (sealed) {
6187
- note(coverage, "dropped_late_completion");
7510
+ note2(coverage, "dropped_late_completion");
6188
7511
  return;
6189
7512
  }
6190
- const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
7513
+ const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3);
6191
7514
  rotateIfNeeded(minute);
6192
7515
  if (minute <= lastClosedMinute && !active.has(minute)) {
6193
- note(coverage, "dropped_late_completion");
7516
+ note2(coverage, "dropped_late_completion");
6194
7517
  return;
6195
7518
  }
6196
7519
  const series = ensureSeries(minute, functionHandle, executionHandle);
6197
7520
  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");
7521
+ 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);
7522
+ if (!remembered) note2(coverage, "dropped_unexportable");
6205
7523
  };
6206
7524
  const beginCall = (input) => {
6207
7525
  const functionHandle = internDeclaration(input.declaration);
6208
7526
  if (functionHandle === void 0) return void 0;
6209
- if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey(input.executionKey)) {
7527
+ if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey2(input.executionKey)) {
6210
7528
  startCall(functionHandle, void 0);
6211
7529
  return void 0;
6212
7530
  }
6213
7531
  const executionHandle = internExecutionKey(input.executionKey);
6214
7532
  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 };
7533
+ const started = startCall(functionHandle, executionHandle, {
7534
+ measure: input.measure,
7535
+ ..."startedNs" in input ? { startedNs: input.startedNs } : {}
7536
+ });
7537
+ if (!started) return void 0;
7538
+ return {
7539
+ settled: false,
7540
+ functionHandle,
7541
+ executionHandle,
7542
+ startedNs: started.startedNs,
7543
+ measure: started.measure
7544
+ };
6218
7545
  };
6219
7546
  const completeCall = (call, failed) => {
6220
7547
  if (!call || call.settled) return;
6221
7548
  call.settled = true;
6222
- finishCall(call.functionHandle, call.executionHandle, call.startedNs, failed);
7549
+ if (!call.measure) {
7550
+ finishCall(call.functionHandle, call.executionHandle, failed);
7551
+ return;
7552
+ }
7553
+ let endedNs;
7554
+ try {
7555
+ endedNs = clock.monotonicNs();
7556
+ } catch {
7557
+ endedNs = void 0;
7558
+ }
7559
+ finishCall(call.functionHandle, call.executionHandle, failed, {
7560
+ startedNs: call.startedNs,
7561
+ endedNs
7562
+ });
6223
7563
  };
6224
7564
  const drain = (drainOptions) => {
6225
7565
  if (!sealed) {
6226
- rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
7566
+ rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS3));
6227
7567
  if (drainOptions?.flushAll) snapshotActive();
6228
7568
  }
6229
7569
  const batches = functionMetricsBatchesFromQueue({
@@ -6237,7 +7577,8 @@ var createFunctionMetricsCollector = (options) => {
6237
7577
  functions,
6238
7578
  executionKeys,
6239
7579
  queued: queue,
6240
- coverage: { ...coverage, covered_bucket_starts: [] }
7580
+ coverage: { ...coverage, covered_bucket_starts: [] },
7581
+ measurementFormat
6241
7582
  });
6242
7583
  if (batches.length === 0) return [];
6243
7584
  for (const queued of queue) stateBytes -= queued.bytes;
@@ -6270,27 +7611,27 @@ var createFunctionMetricsCollector = (options) => {
6270
7611
  // src/function-metrics/encode-function-metrics-upload.ts
6271
7612
  import {
6272
7613
  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
7614
+ encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync3,
7615
+ FUNCTION_METRICS_BUCKET_LATENESS_MS as FUNCTION_METRICS_BUCKET_LATENESS_MS2,
7616
+ FUNCTION_METRICS_MAX_DECODED_BYTES as FUNCTION_METRICS_MAX_DECODED_BYTES2,
7617
+ FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS4,
7618
+ parseFunctionMetricsBucketStart as parseFunctionMetricsBucketStart2
6278
7619
  } from "@rasputin-ai/core";
6279
- var minuteMarks = (minute) => {
7620
+ var minuteMarks2 = (minute) => {
6280
7621
  const next = minute.started_calls + minute.completed_calls;
6281
7622
  return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
6282
7623
  };
6283
- var expiresAtMsFor = (batch, nowMs) => {
7624
+ var expiresAtMsFor2 = (batch, nowMs) => {
6284
7625
  let oldest;
6285
7626
  for (const start of batch.coverage.covered_bucket_starts) {
6286
- const bucket = parseFunctionMetricsBucketStart(start);
7627
+ const bucket = parseFunctionMetricsBucketStart2(start);
6287
7628
  if (bucket === void 0) continue;
6288
7629
  if (oldest === void 0 || bucket < oldest) oldest = bucket;
6289
7630
  }
6290
- if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
6291
- return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
7631
+ if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
7632
+ return oldest + FUNCTION_METRICS_MINUTE_MS4 + FUNCTION_METRICS_BUCKET_LATENESS_MS2;
6292
7633
  };
6293
- var zeroLossCoverage = (coverage) => ({
7634
+ var zeroLossCoverage2 = (coverage) => ({
6294
7635
  ...coverage,
6295
7636
  skipped_unresolved_execution_type: 0,
6296
7637
  dropped_active_series: 0,
@@ -6299,7 +7640,7 @@ var zeroLossCoverage = (coverage) => ({
6299
7640
  dropped_late_completion: 0,
6300
7641
  dropped_unexportable: 0
6301
7642
  });
6302
- var projectMinutes = (source, minutes, coverage, batchId) => {
7643
+ var projectMinutes2 = (source, minutes, coverage, batchId) => {
6303
7644
  const functionIndexes = /* @__PURE__ */ new Map();
6304
7645
  const typeIndexes = /* @__PURE__ */ new Map();
6305
7646
  const functions = [];
@@ -6338,7 +7679,7 @@ var projectMinutes = (source, minutes, coverage, batchId) => {
6338
7679
  coverage: { ...coverage, covered_bucket_starts: covered }
6339
7680
  };
6340
7681
  };
6341
- var withLoss = (batch, loss) => ({
7682
+ var withLoss2 = (batch, loss) => ({
6342
7683
  ...batch,
6343
7684
  coverage: {
6344
7685
  ...batch.coverage,
@@ -6346,37 +7687,37 @@ var withLoss = (batch, loss) => ({
6346
7687
  dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
6347
7688
  }
6348
7689
  });
6349
- var encodeOne = async (batch, nowMs, signal) => {
7690
+ var encodeOne2 = async (batch, nowMs, signal) => {
6350
7691
  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);
7692
+ if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES2) return void 0;
7693
+ const encoded = await encodeJsonRequestBodyAsync3(decodedBytes, void 0, signal);
6353
7694
  return {
6354
7695
  decodedBytes,
6355
7696
  body: encoded.body,
6356
7697
  gzip: encoded.gzip,
6357
7698
  batchId: batch.batch_id,
6358
- expiresAtMs: expiresAtMsFor(batch, nowMs)
7699
+ expiresAtMs: expiresAtMsFor2(batch, nowMs)
6359
7700
  };
6360
7701
  };
6361
- var encodeFitting = async (batch, nowMs, signal) => {
6362
- const encoded = await encodeOne(batch, nowMs, signal);
7702
+ var encodeFitting2 = async (batch, nowMs, signal) => {
7703
+ const encoded = await encodeOne2(batch, nowMs, signal);
6363
7704
  if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
6364
7705
  if (batch.minutes.length <= 1) {
6365
7706
  return {
6366
7707
  uploads: [],
6367
- droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
7708
+ droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks2(minute), 0)
6368
7709
  };
6369
7710
  }
6370
7711
  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(
7712
+ const first = projectMinutes2(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
7713
+ const rest = projectMinutes2(
6373
7714
  batch,
6374
7715
  batch.minutes.slice(mid),
6375
- zeroLossCoverage(batch.coverage),
7716
+ zeroLossCoverage2(batch.coverage),
6376
7717
  newFunctionMetricsBatchId()
6377
7718
  );
6378
- const left = await encodeFitting(first, nowMs, signal);
6379
- const right = await encodeFitting(rest, nowMs, signal);
7719
+ const left = await encodeFitting2(first, nowMs, signal);
7720
+ const right = await encodeFitting2(rest, nowMs, signal);
6380
7721
  return {
6381
7722
  uploads: [...left.uploads, ...right.uploads],
6382
7723
  droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
@@ -6389,105 +7730,21 @@ var encodeFunctionMetricsUploads = async (batches, input) => {
6389
7730
  dropped_queue_budget: input.queueDrops ?? 0
6390
7731
  };
6391
7732
  for (const batch of batches) {
6392
- const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
7733
+ const fitted = await encodeFitting2(withLoss2(batch, extra), input.nowMs, input.signal);
6393
7734
  extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
6394
7735
  uploads.push(...fitted.uploads);
6395
7736
  }
6396
7737
  return uploads;
6397
7738
  };
6398
7739
 
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
7740
  // 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) => {
7741
+ var MAX_QUEUE_ITEMS2 = 32;
7742
+ var MAX_QUEUE_BYTES2 = 4 * 1024 * 1024;
7743
+ var DEFAULT_SCHEDULE_MS2 = 6e4;
7744
+ var FLUSH_MS2 = 1e4;
7745
+ var SHUTDOWN_FLUSH_MS2 = 2e3;
7746
+ var MAX_ATTEMPTS2 = 8;
7747
+ var sleep2 = (ms, signal) => new Promise((resolve) => {
6491
7748
  if (ms <= 0 || signal.aborted) {
6492
7749
  resolve();
6493
7750
  return;
@@ -6508,7 +7765,7 @@ var sleep = (ms, signal) => new Promise((resolve) => {
6508
7765
  var createFunctionMetricsExporter = (input) => {
6509
7766
  const nowMs = input.nowMs ?? Date.now;
6510
7767
  const random = input.random ?? Math.random;
6511
- const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
7768
+ const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS2;
6512
7769
  const queue = [];
6513
7770
  let queueBytes = 0;
6514
7771
  let queueDrops = 0;
@@ -6532,7 +7789,7 @@ var createFunctionMetricsExporter = (input) => {
6532
7789
  const enqueue = (upload) => {
6533
7790
  queue.push({ upload, attempt: 0 });
6534
7791
  queueBytes += upload.decodedBytes.byteLength;
6535
- while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
7792
+ while (queue.length > MAX_QUEUE_ITEMS2 || queueBytes > MAX_QUEUE_BYTES2) dropOldest();
6536
7793
  };
6537
7794
  const drainAndEnqueue = async (flushAll2) => {
6538
7795
  if (halted || stopped) return;
@@ -6567,7 +7824,7 @@ var createFunctionMetricsExporter = (input) => {
6567
7824
  dropped += 1;
6568
7825
  continue;
6569
7826
  }
6570
- if (item.attempt >= MAX_ATTEMPTS) {
7827
+ if (item.attempt >= MAX_ATTEMPTS2) {
6571
7828
  queue.shift();
6572
7829
  queueBytes -= item.upload.decodedBytes.byteLength;
6573
7830
  dropped += 1;
@@ -6601,7 +7858,7 @@ var createFunctionMetricsExporter = (input) => {
6601
7858
  continue;
6602
7859
  }
6603
7860
  item.attempt += 1;
6604
- await sleep(result.waitMs, signal);
7861
+ await sleep2(result.waitMs, signal);
6605
7862
  }
6606
7863
  };
6607
7864
  const abortCurrent = () => {
@@ -6677,7 +7934,7 @@ var createFunctionMetricsExporter = (input) => {
6677
7934
  const flush = async (timeoutMs) => {
6678
7935
  if (closed || halted) return;
6679
7936
  const abort = new AbortController();
6680
- const budget = timeoutMs ?? FLUSH_MS;
7937
+ const budget = timeoutMs ?? FLUSH_MS2;
6681
7938
  const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
6682
7939
  try {
6683
7940
  await runWork(abort.signal, async (signal) => {
@@ -6698,7 +7955,7 @@ var createFunctionMetricsExporter = (input) => {
6698
7955
  if (timer) clearTimeout(timer);
6699
7956
  timer = void 0;
6700
7957
  const abort = new AbortController();
6701
- const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
7958
+ const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS2);
6702
7959
  abortCurrent();
6703
7960
  try {
6704
7961
  await runWork(abort.signal, async (signal) => {
@@ -6731,29 +7988,31 @@ var installFunctionMetricDeclarationSink = () => {
6731
7988
  };
6732
7989
 
6733
7990
  // 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) => {
7991
+ var SLOT2 = Symbol.for("rasputin.functionMetrics.runtime.v1");
7992
+ var releasedHandles2 = /* @__PURE__ */ new WeakSet();
7993
+ var isRuntime2 = (value) => {
6737
7994
  if (typeof value !== "object" || value === null) return false;
6738
7995
  return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
6739
7996
  };
6740
- var bindingIdentity = (input) => `${input.ingestToken}
7997
+ var bindingIdentity2 = (input) => `${input.ingestToken}
6741
7998
  ${input.url}
6742
7999
  ${input.environment}
6743
- ${input.release}`;
6744
- var warnIncompatible = (runtime) => {
8000
+ ${input.release}
8001
+ ${input.sampledMeasurementFormat ? "1" : "0"}`;
8002
+ var warnIncompatible2 = (runtime) => {
6745
8003
  if (runtime.warnedMismatch) return;
6746
8004
  runtime.warnedMismatch = true;
6747
8005
  console.warn(
6748
8006
  "[rasputin] function metrics already running with a different configuration; this client will not collect function metrics"
6749
8007
  );
6750
8008
  };
6751
- var createBindings = (input) => {
8009
+ var createBindings2 = (input) => {
6752
8010
  installFunctionMetricDeclarationSink();
6753
8011
  const collector = createFunctionMetricsCollector({
6754
8012
  environment: input.environment,
6755
- producerId: randomUUID2(),
6756
- release: input.release
8013
+ producerId: randomUUID4(),
8014
+ release: input.release,
8015
+ sampledMeasurementFormat: input.sampledMeasurementFormat
6757
8016
  });
6758
8017
  return {
6759
8018
  collector,
@@ -6761,39 +8020,41 @@ var createBindings = (input) => {
6761
8020
  collector,
6762
8021
  url: input.url,
6763
8022
  ingestToken: input.ingestToken,
6764
- fetch: input.fetch ?? defaultIngestFetch2()
8023
+ fetch: input.fetch ?? defaultIngestFetch3()
6765
8024
  })
6766
8025
  };
6767
8026
  };
6768
8027
  var bindFunctionMetrics = (input) => {
6769
8028
  if (!input.clientEnabled) return void 0;
6770
- if (input.options?.enabled === false) return void 0;
6771
8029
  const release = input.release.trim().toLowerCase();
6772
8030
  if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
6773
- const url = resolveEndpointUrls3(input.apiUrl).functionMetricsUrl;
6774
- const key = bindingIdentity({
8031
+ const url = resolveEndpointUrls4(input.apiUrl).functionMetricsUrl;
8032
+ const sampledMeasurementFormat = input.sampledMeasurementFormat === true;
8033
+ const key = bindingIdentity2({
6775
8034
  ingestToken: input.ingestToken,
6776
8035
  url,
6777
8036
  environment: input.environment,
6778
- release
8037
+ release,
8038
+ sampledMeasurementFormat
6779
8039
  });
6780
- const existing = Reflect.get(globalThis, SLOT);
6781
- if (isRuntime(existing)) {
8040
+ const existing = Reflect.get(globalThis, SLOT2);
8041
+ if (isRuntime2(existing)) {
6782
8042
  if (existing.identity !== key) {
6783
- warnIncompatible(existing);
8043
+ warnIncompatible2(existing);
6784
8044
  return void 0;
6785
8045
  }
6786
8046
  existing.refs += 1;
6787
8047
  return { collector: existing.collector, exporter: existing.exporter };
6788
8048
  }
6789
- const bindings2 = createBindings({
8049
+ const bindings2 = createBindings2({
6790
8050
  release,
6791
8051
  ingestToken: input.ingestToken,
6792
8052
  url,
6793
8053
  environment: input.environment,
6794
- fetch: input.fetch
8054
+ fetch: input.fetch,
8055
+ sampledMeasurementFormat
6795
8056
  });
6796
- Reflect.set(globalThis, SLOT, {
8057
+ Reflect.set(globalThis, SLOT2, {
6797
8058
  ...bindings2,
6798
8059
  refs: 1,
6799
8060
  identity: key,
@@ -6802,13 +8063,13 @@ var bindFunctionMetrics = (input) => {
6802
8063
  return bindings2;
6803
8064
  };
6804
8065
  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) {
8066
+ if (!bindings2 || releasedHandles2.has(bindings2)) return;
8067
+ releasedHandles2.add(bindings2);
8068
+ const existing = Reflect.get(globalThis, SLOT2);
8069
+ if (isRuntime2(existing) && existing.exporter === bindings2.exporter) {
6809
8070
  existing.refs -= 1;
6810
8071
  if (existing.refs > 0) return;
6811
- Reflect.deleteProperty(globalThis, SLOT);
8072
+ Reflect.deleteProperty(globalThis, SLOT2);
6812
8073
  }
6813
8074
  await bindings2.exporter.close();
6814
8075
  };
@@ -6949,9 +8210,77 @@ var installGlobalHandlers = (client, options = {}) => {
6949
8210
  };
6950
8211
  };
6951
8212
 
8213
+ // src/runtime-timing/dynamic-duration-sampling.ts
8214
+ var DYNAMIC_DURATION_SAMPLE_STAGES = [
8215
+ { below: 10, divisor: 1 },
8216
+ { below: 30, divisor: 2 },
8217
+ { below: 100, divisor: 3 },
8218
+ { below: 500, divisor: 11 },
8219
+ { below: 1e3, divisor: 23 },
8220
+ { below: 5e3, divisor: 53 }
8221
+ ];
8222
+ var MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS = 4096;
8223
+ var DYNAMIC_DURATION_SAMPLE_TAIL_AFTER = 5e3;
8224
+ var DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR = 100;
8225
+ var DYNAMIC_DURATION_SAMPLE_RESET_MS = 60 * 60 * 1e3;
8226
+ var EXECUTION_DURATION_SAMPLE_PREFIX = "\0execution-metrics\0";
8227
+ var dynamicDurationSampleDivisor = (index) => {
8228
+ for (const stage of DYNAMIC_DURATION_SAMPLE_STAGES) {
8229
+ if (index < stage.below) return stage.divisor;
8230
+ }
8231
+ return DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8232
+ };
8233
+ var shouldSampleDynamicDuration = (index) => {
8234
+ return index % dynamicDurationSampleDivisor(index) === 0;
8235
+ };
8236
+ var nextDurationSampleIndex = (index) => {
8237
+ if (index < Number.MAX_SAFE_INTEGER) return index + 1;
8238
+ return DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + (index - DYNAMIC_DURATION_SAMPLE_TAIL_AFTER + 1) % DYNAMIC_DURATION_SAMPLE_TAIL_DIVISOR;
8239
+ };
8240
+ var createDynamicDurationSampleBuckets = (options) => {
8241
+ const functionBuckets = /* @__PURE__ */ new Map();
8242
+ const executionBuckets = /* @__PURE__ */ new Map();
8243
+ const maxBuckets = options.maxBuckets ?? MAX_DYNAMIC_DURATION_SAMPLE_BUCKETS;
8244
+ const resetMs = options.resetMs ?? DYNAMIC_DURATION_SAMPLE_RESET_MS;
8245
+ let lastResetAtMs = options.nowMs();
8246
+ let stopped = false;
8247
+ const reset = () => {
8248
+ functionBuckets.clear();
8249
+ executionBuckets.clear();
8250
+ lastResetAtMs = options.nowMs();
8251
+ };
8252
+ const resetTimer = setInterval(reset, resetMs);
8253
+ resetTimer.unref?.();
8254
+ const takeKey = (buckets, key) => {
8255
+ if (options.nowMs() - lastResetAtMs >= resetMs) reset();
8256
+ const existing = buckets.get(key);
8257
+ if (existing !== void 0) {
8258
+ buckets.delete(key);
8259
+ buckets.set(key, nextDurationSampleIndex(existing));
8260
+ return shouldSampleDynamicDuration(existing);
8261
+ }
8262
+ while (buckets.size >= maxBuckets) {
8263
+ const oldest = buckets.keys().next().value;
8264
+ if (oldest === void 0) break;
8265
+ buckets.delete(oldest);
8266
+ }
8267
+ buckets.set(key, nextDurationSampleIndex(0));
8268
+ return shouldSampleDynamicDuration(0);
8269
+ };
8270
+ return {
8271
+ take: (executionType, callerFunctionId, functionId) => takeKey(functionBuckets, `${executionType}\0${callerFunctionId}\0${functionId}`),
8272
+ takeExecution: (executionType) => takeKey(executionBuckets, `${EXECUTION_DURATION_SAMPLE_PREFIX}${executionType}`),
8273
+ stop: () => {
8274
+ if (stopped) return;
8275
+ stopped = true;
8276
+ clearInterval(resetTimer);
8277
+ }
8278
+ };
8279
+ };
8280
+
6952
8281
  // src/sdk-meta.ts
6953
8282
  var SDK_NAME = "@rasputin-ai/node";
6954
- var SDK_VERSION = "0.13.1";
8283
+ var SDK_VERSION = "0.15.0";
6955
8284
 
6956
8285
  // src/rasputin-init.ts
6957
8286
  var publicExecution = (runtime) => ({
@@ -6967,7 +8296,7 @@ var publicExecution = (runtime) => ({
6967
8296
  getStats: runtime.getStats
6968
8297
  });
6969
8298
  var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
6970
- }, policy, metrics) => {
8299
+ }, policy, metrics, executionMetrics) => {
6971
8300
  const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
6972
8301
  };
6973
8302
  const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
@@ -6988,11 +8317,13 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
6988
8317
  if (timeoutMs === void 0) {
6989
8318
  await policy?.flush();
6990
8319
  await metrics?.exporter.flush();
8320
+ await executionMetrics?.exporter.flush();
6991
8321
  await manifestUpload.wait();
6992
8322
  return;
6993
8323
  }
6994
8324
  await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
6995
8325
  await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8326
+ await executionMetrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
6996
8327
  await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
6997
8328
  },
6998
8329
  close: async () => {
@@ -7003,6 +8334,7 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
7003
8334
  const startedAt = Date.now();
7004
8335
  await policy?.close();
7005
8336
  await releaseFunctionMetricsBindings(metrics);
8337
+ await releaseExecutionMetricsBindings(executionMetrics);
7006
8338
  await client.close();
7007
8339
  await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
7008
8340
  }
@@ -7013,15 +8345,27 @@ function RasputinInit(options, hooks = {}) {
7013
8345
  const enabled = isClientEnabled(options);
7014
8346
  const activation = resolveClientActivation2(options);
7015
8347
  const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
8348
+ const durationSampling = options.dynamicDurationSampling === true;
7016
8349
  const metrics = activation.enabled ? bindFunctionMetrics({
7017
- options: options.functionMetrics,
7018
8350
  clientEnabled: true,
7019
8351
  environment: activation.environment,
7020
8352
  release: activation.release,
7021
8353
  ingestToken: activation.ingestToken,
7022
8354
  apiUrl: activation.apiUrl,
7023
- fetch: hooks.fetch
8355
+ fetch: hooks.fetch,
8356
+ sampledMeasurementFormat: durationSampling
8357
+ }) : void 0;
8358
+ const executionMetrics = activation.enabled ? bindExecutionMetrics({
8359
+ clientEnabled: true,
8360
+ environment: activation.environment,
8361
+ release: activation.release,
8362
+ ingestToken: activation.ingestToken,
8363
+ apiUrl: activation.apiUrl,
8364
+ fetch: hooks.fetch,
8365
+ sampledMeasurementFormat: durationSampling
7024
8366
  }) : void 0;
8367
+ const observeExecutions = recorderEnabled || Boolean(metrics) || Boolean(executionMetrics);
8368
+ const durationSampler = durationSampling && observeExecutions ? createDynamicDurationSampleBuckets({ nowMs: () => Date.now() }) : void 0;
7025
8369
  const { runtime, policy } = bindAdaptiveRecorder({
7026
8370
  executionRecorder: options.executionRecorder,
7027
8371
  recorderEnabled,
@@ -7035,7 +8379,9 @@ function RasputinInit(options, hooks = {}) {
7035
8379
  sdkVersion: SDK_VERSION,
7036
8380
  scrubPII: options.scrubPII,
7037
8381
  fetch: hooks.fetch,
7038
- functionMetrics: metrics?.collector
8382
+ functionMetrics: metrics?.collector,
8383
+ executionMetrics: executionMetrics?.collector,
8384
+ durationSampler
7039
8385
  });
7040
8386
  const client = createClient(options, {
7041
8387
  sdkVersion: SDK_VERSION,
@@ -7055,7 +8401,7 @@ function RasputinInit(options, hooks = {}) {
7055
8401
  const wrappedClient = withExecution(
7056
8402
  client,
7057
8403
  runtime,
7058
- recorderEnabled || Boolean(metrics),
8404
+ observeExecutions,
7059
8405
  {
7060
8406
  projectApiKey: options.projectApiKey,
7061
8407
  release: options.release,
@@ -7067,7 +8413,8 @@ function RasputinInit(options, hooks = {}) {
7067
8413
  },
7068
8414
  () => uninstallHandlers(),
7069
8415
  policy,
7070
- metrics
8416
+ metrics,
8417
+ executionMetrics
7071
8418
  );
7072
8419
  if (enabled && options.installGlobalHandlers !== false) {
7073
8420
  uninstallHandlers = installGlobalHandlers(wrappedClient);