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