@rasputin-ai/node 0.16.0 → 1.0.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 (33) hide show
  1. package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts.map +1 -1
  2. package/dist/auto-instrumentation/schedule-instrumentation-manifest-upload.d.ts.map +1 -1
  3. package/dist/create-rasputin-runtime.d.ts +72 -0
  4. package/dist/create-rasputin-runtime.d.ts.map +1 -0
  5. package/dist/execution-metrics/encode-execution-metrics-upload.d.ts.map +1 -1
  6. package/dist/execution-metrics/execution-metrics-collector.d.ts +3 -3
  7. package/dist/execution-metrics/execution-metrics-collector.d.ts.map +1 -1
  8. package/dist/execution-recorder/adaptive-recording-options.d.ts +3 -0
  9. package/dist/execution-recorder/adaptive-recording-options.d.ts.map +1 -1
  10. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -1
  11. package/dist/execution-recorder/execution-journal.d.ts +16 -1
  12. package/dist/execution-recorder/execution-journal.d.ts.map +1 -1
  13. package/dist/execution-recorder/execution-recorder-types.d.ts +18 -13
  14. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  15. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  16. package/dist/execution-recorder/execution-recording-sync.d.ts +0 -1
  17. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -1
  18. package/dist/execution-recorder/runtime-state-size-budget.d.ts +3 -3
  19. package/dist/execution-recorder/runtime-state-size-budget.d.ts.map +1 -1
  20. package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -1
  21. package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -1
  22. package/dist/index.js +878 -412
  23. package/dist/instrument/build.js +211 -355
  24. package/dist/instrument/bun.js +135 -246
  25. package/dist/instrument/node.js +135 -246
  26. package/dist/internal.d.ts +2 -0
  27. package/dist/internal.d.ts.map +1 -1
  28. package/dist/internal.js +983 -341
  29. package/dist/rasputin-init.d.ts +7 -60
  30. package/dist/rasputin-init.d.ts.map +1 -1
  31. package/dist/sdk-meta.d.ts +1 -1
  32. package/dist/sdk-meta.d.ts.map +1 -1
  33. package/package.json +3 -3
package/dist/internal.js CHANGED
@@ -121,10 +121,11 @@ var runtimeLabel = () => {
121
121
  };
122
122
 
123
123
  // src/auto-instrumentation/instrumentation-manifest-registry.ts
124
- import { createHash } from "node:crypto";
124
+ import { existsSync, readFileSync } from "node:fs";
125
125
  import {
126
126
  INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
127
- sourceLocatorFromFile as sourceLocatorFromFile2
127
+ sourceLocatorFromFile as sourceLocatorFromFile2,
128
+ sourceLocatorKey
128
129
  } from "@rasputin-ai/core";
129
130
 
130
131
  // ../recorder/src/run-exactly-once.ts
@@ -241,7 +242,7 @@ var getAutomaticRuntimeRegistry = () => {
241
242
  };
242
243
 
243
244
  // src/auto-instrumentation/instrumentation-manifest-registry.ts
244
- var INSTRUMENTATION_MANIFEST_SYMBOL = "rasputin.instrumentation.manifest.v3";
245
+ var INSTRUMENTATION_MANIFEST_SYMBOL = "rasputin.instrumentation.manifest.v4";
245
246
  var registrySymbol = Symbol.for(INSTRUMENTATION_MANIFEST_SYMBOL);
246
247
  var getRegistry = () => {
247
248
  const existing = Reflect.get(globalThis, registrySymbol);
@@ -260,11 +261,37 @@ var getRegistry = () => {
260
261
  Reflect.set(globalThis, registrySymbol, registry);
261
262
  return registry;
262
263
  };
263
- var sourceAt = (filePath, line, column) => {
264
- const source = sourceLocatorFromFile2(filePath);
265
- return source ? { ...source, line, column } : void 0;
264
+ var rememberSource = (sources, source) => {
265
+ const key = sourceLocatorKey(source);
266
+ const previous = sources.get(key);
267
+ sources.set(key, {
268
+ ...previous,
269
+ packageRelativePath: source.packageRelativePath,
270
+ ...source.packageName ? { packageName: source.packageName } : previous?.packageName ? { packageName: previous.packageName } : {},
271
+ ...source.repositoryPath ? { repositoryPath: source.repositoryPath } : previous?.repositoryPath ? { repositoryPath: previous.repositoryPath } : {}
272
+ });
273
+ };
274
+ var recordPrebuiltInstrumentationManifest = (manifest) => {
275
+ const registry = getRegistry();
276
+ registry.prebuilt = manifest;
277
+ registry.generation += 1;
278
+ registry.onDirty?.();
279
+ };
280
+ var loadInstrumentationManifestFile = (path) => {
281
+ try {
282
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
283
+ if (parsed.schema_version !== INSTRUMENTATION_MANIFEST_SCHEMA_VERSION) return false;
284
+ if (!Array.isArray(parsed.sources)) return false;
285
+ recordPrebuiltInstrumentationManifest(parsed);
286
+ return true;
287
+ } catch {
288
+ return false;
289
+ }
290
+ };
291
+ var loadInstrumentationManifestIfPresent = (path) => {
292
+ if (!path || !existsSync(path)) return;
293
+ loadInstrumentationManifestFile(path);
266
294
  };
267
- var stableId = (kind, ...parts) => `${kind}_${createHash("sha256").update(parts.join("\0")).digest("base64url").slice(0, 24)}`;
268
295
  var isInstrumentationManifestDirty = () => {
269
296
  const registry = getRegistry();
270
297
  return registry.generation !== registry.uploadedGeneration && (registry.files.size > 0 || registry.prebuilt !== void 0);
@@ -300,7 +327,7 @@ var instrumentationManifestModuleCount = () => {
300
327
  const registry = getRegistry();
301
328
  if (registry.files.size > 0) return registry.files.size;
302
329
  if (!registry.prebuilt) return 0;
303
- return new Set(registry.prebuilt.functions.map((fn) => fn.source.packageRelativePath)).size;
330
+ return registry.prebuilt.sources.length;
304
331
  };
305
332
  var snapshotOptionsKey = (options) => JSON.stringify({
306
333
  sourceRoot: options.sourceRoot ?? "",
@@ -312,12 +339,8 @@ var snapshotInstrumentationManifest = (options = {}) => {
312
339
  if (registry.snapshotCache && registry.snapshotCache.generation === registry.generation && registry.snapshotCache.optionsKey === optionsKey) {
313
340
  return registry.snapshotCache.manifest;
314
341
  }
315
- const functions = new Map(
316
- registry.prebuilt?.functions.map((fn) => [fn.functionId, fn])
317
- );
318
- const callSites = new Map(
319
- registry.prebuilt?.callSites.map((site) => [site.id, site])
320
- );
342
+ const sources = /* @__PURE__ */ new Map();
343
+ for (const source of registry.prebuilt?.sources ?? []) rememberSource(sources, source);
321
344
  const remember = (manifest) => {
322
345
  registry.snapshotCache = {
323
346
  generation: registry.generation,
@@ -326,53 +349,21 @@ var snapshotInstrumentationManifest = (options = {}) => {
326
349
  };
327
350
  return manifest;
328
351
  };
329
- for (const delta of registry.files.values()) {
352
+ for (const [filePath, delta] of registry.files) {
353
+ let recorded = false;
330
354
  for (const fn of delta.functions) {
331
355
  const definition = definitionFromEncodedPlan(fn.plan);
332
356
  if (!definition.source) continue;
333
- if (!fn.metricsDeclaration) {
334
- throw new Error(`Missing function metrics declaration: ${fn.functionId}`);
335
- }
336
- functions.set(definition.functionId, {
337
- ...functions.get(definition.functionId),
338
- functionId: definition.functionId,
339
- source: {
340
- packageRelativePath: definition.source.packageRelativePath,
341
- ...definition.source.packageName ? { packageName: definition.source.packageName } : {},
342
- ...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
343
- },
344
- name: fn.name,
345
- startLine: fn.startLine,
346
- startColumn: fn.startColumn,
347
- endLine: fn.endLine,
348
- endColumn: fn.endColumn,
349
- metricsDeclaration: fn.metricsDeclaration,
350
- ...fn.instrumented === false ? { instrumented: false, skipReason: fn.skipReason } : {}
351
- });
352
- }
353
- for (const site of delta.callSites) {
354
- const source = sourceAt(site.filePath, site.line, site.column);
355
- if (!source) continue;
356
- const id = stableId(
357
- "cs",
358
- site.callerFunctionId,
359
- source.packageName ?? "",
360
- source.packageRelativePath,
361
- site.line,
362
- site.column
363
- );
364
- callSites.set(id, {
365
- id,
366
- callerFunctionId: site.callerFunctionId,
367
- calleeName: site.calleeName,
368
- calleeText: site.calleeText,
369
- line: site.line,
370
- column: site.column,
371
- endLine: site.endLine,
372
- endColumn: site.endColumn,
373
- resultBinding: site.resultBinding
357
+ rememberSource(sources, {
358
+ packageRelativePath: definition.source.packageRelativePath,
359
+ ...definition.source.packageName ? { packageName: definition.source.packageName } : {},
360
+ ...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
374
361
  });
362
+ recorded = true;
375
363
  }
364
+ if (recorded) continue;
365
+ const locator = sourceLocatorFromFile2(filePath);
366
+ if (locator) rememberSource(sources, locator);
376
367
  }
377
368
  if (registry.prebuilt && registry.files.size === 0) {
378
369
  if (!options.sourceRoot && !options.sourceRoots) return remember(registry.prebuilt);
@@ -384,9 +375,7 @@ var snapshotInstrumentationManifest = (options = {}) => {
384
375
  }
385
376
  });
386
377
  }
387
- if (functions.size === 0 && callSites.size === 0) {
388
- return remember(void 0);
389
- }
378
+ if (sources.size === 0) return remember(void 0);
390
379
  const packages = { ...registry.prebuilt?.sourceRoots?.packages, ...options.sourceRoots };
391
380
  const sourceRoot = options.sourceRoot ?? registry.prebuilt?.sourceRoots?.default;
392
381
  return remember({
@@ -397,8 +386,7 @@ var snapshotInstrumentationManifest = (options = {}) => {
397
386
  packages
398
387
  }
399
388
  } : {},
400
- functions: [...functions.values()],
401
- callSites: [...callSites.values()]
389
+ sources: [...sources.values()]
402
390
  });
403
391
  };
404
392
  var collectParamsByFunctionId = () => {
@@ -469,17 +457,21 @@ var scheduleInstrumentationManifestUpload = (options) => {
469
457
  const maxAttempts = 5;
470
458
  const packageNamesOf = (manifest) => [
471
459
  ...new Set(
472
- manifest.functions.map((fn) => fn.source.packageName).filter((name) => Boolean(name))
460
+ manifest.sources.map((source) => source.packageName).filter((name) => Boolean(name))
473
461
  )
474
462
  ].sort();
475
463
  const report = (manifest, uploaded, next) => {
476
464
  const coverage = instrumentationCoverageStats();
465
+ const skippedFunctions = Object.values(coverage.skippedByReason).reduce(
466
+ (total, count) => total + count,
467
+ 0
468
+ );
477
469
  return formatConfigurationReport({
478
470
  release,
479
471
  runtime: runtimeLabel(),
480
472
  modules: instrumentationManifestModuleCount(),
481
- functions: manifest.functions.filter((fn) => fn.instrumented !== false).length,
482
- skippedFunctions: manifest.functions.filter((fn) => fn.instrumented === false).length,
473
+ functions: coverage.instrumented,
474
+ skippedFunctions,
483
475
  instrumentedAsync: coverage.instrumentedAsync,
484
476
  skippedByReason: coverage.skippedByReason,
485
477
  packageNames: packageNamesOf(manifest),
@@ -647,6 +639,17 @@ var scheduleInstrumentationManifestUpload = (options) => {
647
639
  };
648
640
  };
649
641
 
642
+ // src/create-rasputin-runtime.ts
643
+ import { join } from "node:path";
644
+ import {
645
+ copyRedactKeys as copyRedactKeys2,
646
+ createClient,
647
+ isClientEnabled,
648
+ resolveClientActivation as resolveClientActivation2,
649
+ resolveEndpointUrls as resolveEndpointUrls5,
650
+ scheduleAnnounceDeploy
651
+ } from "@rasputin-ai/core";
652
+
650
653
  // src/execution-metrics/bind-execution-metrics.ts
651
654
  import { randomUUID as randomUUID2 } from "node:crypto";
652
655
  import {
@@ -911,6 +914,18 @@ var createExecutionMetricsCollector = (options) => {
911
914
  executionHandleByKey.set(key, handle);
912
915
  return handle;
913
916
  };
917
+ const newSeries = () => ({
918
+ started: 0,
919
+ completed: 0,
920
+ failed: 0,
921
+ sampleCount: 0,
922
+ sampleSumUs: 0,
923
+ sampleMinUs: null,
924
+ sampleMaxUs: null,
925
+ invalidTiming: 0,
926
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
927
+ bytes: SERIES_BYTES + HISTOGRAM_BYTES
928
+ });
914
929
  const ensureSeries = (minute, executionHandle) => {
915
930
  let byExecution = active.get(minute);
916
931
  if (!byExecution) {
@@ -924,18 +939,7 @@ var createExecutionMetricsCollector = (options) => {
924
939
  return void 0;
925
940
  }
926
941
  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
- };
942
+ const series = newSeries();
939
943
  byExecution.set(executionHandle, series);
940
944
  activeSeries += 1;
941
945
  return series;
@@ -956,11 +960,22 @@ var createExecutionMetricsCollector = (options) => {
956
960
  note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
957
961
  }
958
962
  };
963
+ const markedSeries = (table) => {
964
+ const marked = /* @__PURE__ */ new Map();
965
+ for (const [executionHandle, series] of table) {
966
+ if (seriesHasMarks(series)) marked.set(executionHandle, series);
967
+ }
968
+ return marked;
969
+ };
959
970
  const closeMinute = (minute, table) => {
960
971
  active.delete(minute);
961
972
  activeSeries -= countSeries(table);
962
973
  if (minute > lastClosedMinute) lastClosedMinute = minute;
963
- appendQueue({ minute, series: table, bytes: tableBytes(table) });
974
+ const marked = markedSeries(table);
975
+ const markedBytes = tableBytes(marked);
976
+ stateBytes -= tableBytes(table) - markedBytes;
977
+ if (stateBytes < 0) stateBytes = 0;
978
+ appendQueue({ minute, series: marked, bytes: markedBytes });
964
979
  };
965
980
  const rotate = (currentMinute2) => {
966
981
  for (const minute of [...active.keys()]) {
@@ -1000,6 +1015,63 @@ var createExecutionMetricsCollector = (options) => {
1000
1015
  }
1001
1016
  return minute;
1002
1017
  };
1018
+ const bumpStarted = (series) => {
1019
+ const started = series.started + 1;
1020
+ if (!Number.isSafeInteger(started)) {
1021
+ note(coverage, "dropped_unexportable");
1022
+ return false;
1023
+ }
1024
+ series.started = started;
1025
+ return true;
1026
+ };
1027
+ const incrementStarted = (minute, handle) => {
1028
+ if (sealed) {
1029
+ note(coverage, "dropped_unexportable");
1030
+ return false;
1031
+ }
1032
+ const current = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
1033
+ rotateIfNeeded(current);
1034
+ if (minute > current) {
1035
+ note(coverage, "dropped_late_completion");
1036
+ return false;
1037
+ }
1038
+ if (minute === current || active.has(minute)) {
1039
+ const series2 = ensureSeries(minute, handle);
1040
+ if (!series2) return false;
1041
+ return bumpStarted(series2);
1042
+ }
1043
+ for (const entry of queue) {
1044
+ if (entry.minute !== minute) continue;
1045
+ let series2 = entry.series.get(handle);
1046
+ if (!series2) {
1047
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return false;
1048
+ series2 = newSeries();
1049
+ entry.series.set(handle, series2);
1050
+ entry.bytes += series2.bytes;
1051
+ }
1052
+ return bumpStarted(series2);
1053
+ }
1054
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return false;
1055
+ const series = newSeries();
1056
+ if (!bumpStarted(series)) {
1057
+ stateBytes -= series.bytes;
1058
+ if (stateBytes < 0) stateBytes = 0;
1059
+ return false;
1060
+ }
1061
+ appendQueue({ minute, series: /* @__PURE__ */ new Map([[handle, series]]), bytes: series.bytes });
1062
+ return true;
1063
+ };
1064
+ const rememberStart = (state, key) => {
1065
+ if (state.started) return;
1066
+ if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return;
1067
+ const handle = internExecutionKey(key);
1068
+ if (handle === void 0) return;
1069
+ if (incrementStarted(state.startedMinute, handle)) state.started = true;
1070
+ };
1071
+ const bindIdentity = (state, key) => {
1072
+ if (state.finished || state.started) return;
1073
+ rememberStart(state, key);
1074
+ };
1003
1075
  const rememberSample = (series, durationUs, bucket) => {
1004
1076
  const sampleCount = series.sampleCount + 1;
1005
1077
  const sampleSumUs = series.sampleSumUs + durationUs;
@@ -1015,46 +1087,19 @@ var createExecutionMetricsCollector = (options) => {
1015
1087
  series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
1016
1088
  return true;
1017
1089
  };
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
1090
  const finishExecution = (state, input) => {
1044
1091
  if (state.finished) return;
1045
1092
  state.finished = true;
1046
- if (state.dropped) return;
1047
- if (state.handle === void 0) {
1093
+ if (!input.key || !isCanonicalFunctionMetricsExecutionKey(input.key)) {
1048
1094
  note(coverage, "skipped_unresolved_execution_type");
1049
1095
  return;
1050
1096
  }
1051
- if (!state.started) {
1052
- if (!rememberStart(state.handle)) return;
1053
- state.started = true;
1054
- }
1055
- const minute = currentMinute(true);
1097
+ const handle = internExecutionKey(input.key);
1098
+ if (handle === void 0) return;
1099
+ rememberStart(state, input.key);
1100
+ const minute = currentMinute(false);
1056
1101
  if (minute === void 0) return;
1057
- const series = ensureSeries(minute, state.handle);
1102
+ const series = ensureSeries(minute, handle);
1058
1103
  if (!series) return;
1059
1104
  const completed = series.completed + 1;
1060
1105
  const failed = series.failed + (input.failed ? 1 : 0);
@@ -1120,10 +1165,9 @@ var createExecutionMetricsCollector = (options) => {
1120
1165
  };
1121
1166
  return {
1122
1167
  createState: () => ({
1123
- handle: void 0,
1124
- started: false,
1125
1168
  finished: false,
1126
- dropped: false
1169
+ started: false,
1170
+ startedMinute: Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS)
1127
1171
  }),
1128
1172
  bindIdentity,
1129
1173
  finishExecution,
@@ -1232,15 +1276,39 @@ var minuteMarks = (minute) => {
1232
1276
  const next = minute.started_executions + minute.completed_executions;
1233
1277
  return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
1234
1278
  };
1279
+ var bucketExpiresAtMs = (bucketStart3) => {
1280
+ const bucket = parseFunctionMetricsBucketStart(bucketStart3);
1281
+ if (bucket === void 0) return void 0;
1282
+ return bucket + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1283
+ };
1235
1284
  var expiresAtMsFor = (batch, nowMs) => {
1236
- let oldest;
1285
+ let earliest;
1237
1286
  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;
1287
+ const expires = bucketExpiresAtMs(start);
1288
+ if (expires === void 0) continue;
1289
+ if (earliest === void 0 || expires < earliest) earliest = expires;
1290
+ }
1291
+ if (earliest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1292
+ return earliest;
1293
+ };
1294
+ var minuteAlreadyExpired = (minute, nowMs) => {
1295
+ const expires = bucketExpiresAtMs(minute.bucket_start);
1296
+ return expires !== void 0 && expires <= nowMs;
1297
+ };
1298
+ var hasCoverageLoss = (coverage) => Object.entries(coverage).some(
1299
+ ([key, value]) => key !== "covered_bucket_starts" && typeof value === "number" && value > 0
1300
+ );
1301
+ var liveMinutesOf = (batch, nowMs) => {
1302
+ const live = [];
1303
+ let droppedLate = 0;
1304
+ for (const minute of batch.minutes) {
1305
+ if (minuteAlreadyExpired(minute, nowMs)) {
1306
+ droppedLate += minuteMarks(minute);
1307
+ continue;
1308
+ }
1309
+ live.push(minute);
1241
1310
  }
1242
- if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1243
- return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1311
+ return { live, droppedLate };
1244
1312
  };
1245
1313
  var zeroLossCoverage = (coverage) => ({
1246
1314
  ...coverage,
@@ -1280,7 +1348,8 @@ var withLoss = (batch, loss) => ({
1280
1348
  coverage: {
1281
1349
  ...batch.coverage,
1282
1350
  dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
1283
- dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
1351
+ dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget,
1352
+ dropped_late_completion: batch.coverage.dropped_late_completion + loss.dropped_late_completion
1284
1353
  }
1285
1354
  });
1286
1355
  var encodeOne = async (batch, nowMs, signal) => {
@@ -1323,11 +1392,30 @@ var encodeExecutionMetricsUploads = async (batches, input) => {
1323
1392
  const uploads = [];
1324
1393
  let extra = {
1325
1394
  dropped_unexportable: 0,
1326
- dropped_queue_budget: input.queueDrops ?? 0
1395
+ dropped_queue_budget: input.queueDrops ?? 0,
1396
+ dropped_late_completion: 0
1327
1397
  };
1328
1398
  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 };
1399
+ const { live, droppedLate } = liveMinutesOf(batch, input.nowMs);
1400
+ const loss = {
1401
+ dropped_unexportable: extra.dropped_unexportable,
1402
+ dropped_queue_budget: extra.dropped_queue_budget,
1403
+ dropped_late_completion: extra.dropped_late_completion + droppedLate
1404
+ };
1405
+ const lost = withLoss(batch, loss);
1406
+ const prepared = live.length === batch.minutes.length ? lost : projectMinutes(batch, live, lost.coverage, batch.batch_id);
1407
+ extra = {
1408
+ dropped_unexportable: 0,
1409
+ dropped_queue_budget: 0,
1410
+ dropped_late_completion: 0
1411
+ };
1412
+ if (prepared.minutes.length === 0 && !hasCoverageLoss(prepared.coverage)) continue;
1413
+ const fitted = await encodeFitting(prepared, input.nowMs, input.signal);
1414
+ extra = {
1415
+ dropped_unexportable: fitted.droppedUnexportable,
1416
+ dropped_queue_budget: 0,
1417
+ dropped_late_completion: 0
1418
+ };
1331
1419
  uploads.push(...fitted.uploads);
1332
1420
  }
1333
1421
  return uploads;
@@ -1906,13 +1994,13 @@ var definitionOf = (input) => {
1906
1994
  return { name: input, functionId: runtimeFunctionId2({ name: input }) };
1907
1995
  return input;
1908
1996
  };
1909
- var bindExecutionHandle = (collector, store) => {
1910
- if (!collector) return;
1911
- store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
1912
- };
1913
- var bindExecutionMetricsIdentity = (collector, store) => {
1914
- if (!collector || !store.executionMetrics) return;
1915
- collector.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
1997
+ var ensureExecutionHandle = (collector, store) => {
1998
+ if (!collector || !store) return void 0;
1999
+ const key = executionTypeKey(store.execution);
2000
+ if (store.executionKey === key) return store.executionHandle;
2001
+ store.executionKey = key;
2002
+ store.executionHandle = collector.internExecutionKey(key);
2003
+ return store.executionHandle;
1916
2004
  };
1917
2005
  var settleStarted = (collector, functionHandle, executionHandle, started, value, failed, endedNs) => {
1918
2006
  if (!started || functionHandle === void 0 || executionHandle === void 0) return;
@@ -1933,7 +2021,8 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1933
2021
  });
1934
2022
  const startedNs = duration.measure ? tryCallClock2() : void 0;
1935
2023
  const functionHandle = internPreparedMetrics(collector, plan);
1936
- const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
2024
+ const executionHandle = functionHandle !== void 0 ? ensureExecutionHandle(collector, store) : void 0;
2025
+ const started = startMetricsCall(collector, functionHandle, executionHandle, {
1937
2026
  measure: duration.selected,
1938
2027
  ...duration.selected ? { startedNs } : {}
1939
2028
  });
@@ -1943,7 +2032,7 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1943
2032
  settleStarted(
1944
2033
  collector,
1945
2034
  functionHandle,
1946
- store?.executionHandle,
2035
+ executionHandle,
1947
2036
  started,
1948
2037
  result,
1949
2038
  false,
@@ -1954,7 +2043,7 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1954
2043
  settleStarted(
1955
2044
  collector,
1956
2045
  functionHandle,
1957
- store?.executionHandle,
2046
+ executionHandle,
1958
2047
  started,
1959
2048
  error,
1960
2049
  true,
@@ -1976,14 +2065,14 @@ var metricsHandle = (collector, durationSampler, plan, store) => {
1976
2065
  });
1977
2066
  const startedNs = duration.measure ? tryCallClock2() : void 0;
1978
2067
  const functionHandle = internPreparedMetrics(collector, plan);
1979
- const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
2068
+ const executionHandle = functionHandle !== void 0 ? ensureExecutionHandle(collector, store) : void 0;
2069
+ const started = startMetricsCall(collector, functionHandle, executionHandle, {
1980
2070
  measure: duration.selected,
1981
2071
  ...duration.selected ? { startedNs } : {}
1982
2072
  });
1983
- if (!started || functionHandle === void 0 || store?.executionHandle === void 0) {
2073
+ if (!started || functionHandle === void 0 || executionHandle === void 0 || !store) {
1984
2074
  return passthroughHandle();
1985
2075
  }
1986
- const executionHandle = store.executionHandle;
1987
2076
  let failed = false;
1988
2077
  let settled = false;
1989
2078
  let previousFunctionId = store.currentFunctionId;
@@ -2075,18 +2164,21 @@ var createMetricsOnlyRuntime = (input) => {
2075
2164
  return runPrepared(plan, args, () => fn.apply(this, args));
2076
2165
  };
2077
2166
  }
2167
+ const bindNamedExecutionMetrics = (store) => {
2168
+ if (!executionMetrics || !store.executionMetrics) return;
2169
+ if (store.execution.kind === "http") return;
2170
+ executionMetrics.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
2171
+ };
2078
2172
  const finishScope = (store, next) => {
2079
2173
  if (next) {
2080
2174
  mergeMetadata(store, next);
2081
- bindExecutionHandle(collector, store);
2082
- bindExecutionMetricsIdentity(executionMetrics, store);
2083
2175
  }
2084
2176
  if (!executionMetrics || !store.executionMetrics) return;
2085
2177
  if (store.executionMetrics.finished) return;
2086
2178
  const endedNs = tryCallClock2();
2087
2179
  const executionKey = executionTypeKey(store.execution);
2088
- bindExecutionMetricsIdentity(executionMetrics, store);
2089
2180
  executionMetrics.finishExecution(store.executionMetrics, {
2181
+ key: executionKey,
2090
2182
  failed: executionOutcomeFailed({
2091
2183
  hasError: store.hasError,
2092
2184
  runFailed: store.runFailed,
@@ -2109,10 +2201,9 @@ var createMetricsOnlyRuntime = (input) => {
2109
2201
  hasError: false,
2110
2202
  runFailed: false
2111
2203
  };
2112
- bindExecutionHandle(collector, store);
2113
2204
  if (executionMetrics) {
2114
2205
  store.executionMetrics = executionMetrics.createState();
2115
- bindExecutionMetricsIdentity(executionMetrics, store);
2206
+ bindNamedExecutionMetrics(store);
2116
2207
  }
2117
2208
  return {
2118
2209
  run: (callback) => metricsStorage.run(store, () => {
@@ -2131,8 +2222,9 @@ var createMetricsOnlyRuntime = (input) => {
2131
2222
  finish: (next) => finishScope(store, next),
2132
2223
  mergeMetadata: (next) => {
2133
2224
  mergeMetadata(store, next);
2134
- bindExecutionHandle(collector, store);
2135
- bindExecutionMetricsIdentity(executionMetrics, store);
2225
+ bindNamedExecutionMetrics(store);
2226
+ },
2227
+ captureInput: () => {
2136
2228
  }
2137
2229
  };
2138
2230
  },
@@ -2154,9 +2246,12 @@ var createMetricsOnlyRuntime = (input) => {
2154
2246
  };
2155
2247
 
2156
2248
  // src/execution-recorder/adaptive-recording-options.ts
2157
- var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
2249
+ var DEFAULT_FULL_CAPTURE_DURATION_MS = 60 * 60 * 1e3;
2158
2250
  var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
2159
2251
  var MAX_FULL_CAPTURE_DURATION_MS = 7 * 24 * 60 * 60 * 1e3;
2252
+ var resolveExecutionRecordingMode = (options) => {
2253
+ return options?.alwaysCaptureValues === true ? "full" : "adaptive";
2254
+ };
2160
2255
  var sanitizeFullCaptureDurationMs = (value) => {
2161
2256
  if (typeof value !== "number" || !Number.isFinite(value)) {
2162
2257
  return DEFAULT_FULL_CAPTURE_DURATION_MS;
@@ -2173,6 +2268,45 @@ var KIND_EXIT = 2;
2173
2268
  var KIND_THROW = 3;
2174
2269
  var KIND_SUPPRESSED = 4;
2175
2270
  var ARGS_OMITTED = Symbol("rasputin.argsOmitted");
2271
+ var SESSION_CAPTURE_ID = "__rasputin_session_capture";
2272
+ var ORDINARY_VALUE = "__rasputin_ordinary_value";
2273
+ var tagSessionCapture = (sessionId, value) => ({
2274
+ [SESSION_CAPTURE_ID]: sessionId,
2275
+ value
2276
+ });
2277
+ var tagOrdinaryAndSessionCapture = (sessionId, sessionValue, ordinaryValue) => ({
2278
+ [SESSION_CAPTURE_ID]: sessionId,
2279
+ [ORDINARY_VALUE]: ordinaryValue,
2280
+ value: sessionValue
2281
+ });
2282
+ var sessionCaptureOf = (payload) => {
2283
+ if (typeof payload !== "object" || payload === null) return void 0;
2284
+ if (!Object.hasOwn(payload, SESSION_CAPTURE_ID)) return void 0;
2285
+ const sessionId = Object.getOwnPropertyDescriptor(payload, SESSION_CAPTURE_ID)?.value;
2286
+ if (typeof sessionId !== "string") return void 0;
2287
+ return {
2288
+ sessionId,
2289
+ value: Object.getOwnPropertyDescriptor(payload, "value")?.value
2290
+ };
2291
+ };
2292
+ var unpackCapture = (payload) => {
2293
+ const tagged = sessionCaptureOf(payload);
2294
+ if (!tagged) return { ordinaryPresent: true, ordinary: payload };
2295
+ if (typeof payload !== "object" || payload === null || !Object.hasOwn(payload, ORDINARY_VALUE)) {
2296
+ return {
2297
+ ordinaryPresent: false,
2298
+ ordinary: ARGS_OMITTED,
2299
+ sessionId: tagged.sessionId,
2300
+ sessionValue: tagged.value
2301
+ };
2302
+ }
2303
+ return {
2304
+ ordinaryPresent: true,
2305
+ ordinary: Object.getOwnPropertyDescriptor(payload, ORDINARY_VALUE)?.value,
2306
+ sessionId: tagged.sessionId,
2307
+ sessionValue: tagged.value
2308
+ };
2309
+ };
2176
2310
  var NO_PARENT = 4294967295;
2177
2311
  var NO_SUPPRESSION = 4294967295;
2178
2312
  var TIMING_UNAVAILABLE = -1n;
@@ -2375,19 +2509,24 @@ var ExecutionJournal = class {
2375
2509
  const functionId = plansByRuntimeId[this.planId[index] ?? 0]?.functionId;
2376
2510
  if (!functionId) return void 0;
2377
2511
  const parentCallId = this.parentCallId[index] ?? NO_PARENT;
2378
- const payload = this.payloads[index];
2512
+ const unpacked = unpackCapture(this.payloads[index]);
2513
+ const inner = unpacked.ordinaryPresent ? unpacked.ordinary : ARGS_OMITTED;
2379
2514
  const timestampMs = measuredRelativeMs(this.timestampNs[index] ?? TIMING_UNAVAILABLE);
2380
2515
  return {
2381
2516
  type: "function_enter",
2382
2517
  callId: this.callId[index] ?? 0,
2383
2518
  functionId,
2384
2519
  ...timestampMs === void 0 ? {} : { timestampMs },
2385
- ...payload === ARGS_OMITTED ? { argsOmitted: true } : { args: Array.isArray(payload) ? payload : [] },
2386
- ...parentCallId === NO_PARENT ? {} : { parentCallId }
2520
+ ...inner === ARGS_OMITTED ? { argsOmitted: true } : { args: Array.isArray(inner) ? inner : [] },
2521
+ ...parentCallId === NO_PARENT ? {} : { parentCallId },
2522
+ ...unpacked.ordinaryPresent && unpacked.sessionId ? { ordinaryCapture: true } : {},
2523
+ ...unpacked.sessionId ? { sessionCaptureId: unpacked.sessionId } : {},
2524
+ ...unpacked.sessionId && unpacked.sessionValue !== ARGS_OMITTED ? { sessionArgs: Array.isArray(unpacked.sessionValue) ? unpacked.sessionValue : [] } : {}
2387
2525
  };
2388
2526
  }
2389
2527
  if (kind === KIND_EXIT) {
2390
- const payload = this.payloads[index];
2528
+ const unpacked = unpackCapture(this.payloads[index]);
2529
+ const inner = unpacked.ordinaryPresent ? unpacked.ordinary : ARGS_OMITTED;
2391
2530
  const timestampMs = measuredRelativeMs(this.timestampNs[index] ?? TIMING_UNAVAILABLE);
2392
2531
  const durationMs = measuredRelativeMs(this.durationNs[index] ?? TIMING_UNAVAILABLE);
2393
2532
  return {
@@ -2395,7 +2534,10 @@ var ExecutionJournal = class {
2395
2534
  callId: this.callId[index] ?? 0,
2396
2535
  ...timestampMs === void 0 ? {} : { timestampMs },
2397
2536
  ...durationMs === void 0 ? {} : { durationMs },
2398
- ...payload === ARGS_OMITTED ? {} : { returnValue: payload }
2537
+ ...inner === ARGS_OMITTED ? {} : { returnValue: inner },
2538
+ ...unpacked.ordinaryPresent && unpacked.sessionId ? { ordinaryCapture: true } : {},
2539
+ ...unpacked.sessionId ? { sessionCaptureId: unpacked.sessionId } : {},
2540
+ ...unpacked.sessionId && unpacked.sessionValue !== ARGS_OMITTED ? { sessionReturnValue: unpacked.sessionValue } : {}
2399
2541
  };
2400
2542
  }
2401
2543
  if (kind === KIND_THROW) {
@@ -2902,6 +3044,13 @@ var enforceRuntimeStateSizeBudget = (input) => {
2902
3044
  withSizeMetadata({ ...state, captureProfile, events: stripped.events }, size)
2903
3045
  );
2904
3046
  if (encodedBytes(state) <= MAX_RUNTIME_STATE_BYTES) return state;
3047
+ if ("input" in state) {
3048
+ size.eventValuesDropped += 1;
3049
+ state = settleFinalBytes(
3050
+ withSizeMetadata({ ...state, input: rasputinUnavailable(VALUE_OMITTED_REASON) }, size)
3051
+ );
3052
+ if (encodedBytes(state) <= MAX_RUNTIME_STATE_BYTES) return state;
3053
+ }
2905
3054
  size.eventsDropped += state.events.length;
2906
3055
  size.functionDefinitionsDropped += state.functions.length;
2907
3056
  state = settleFinalBytes(
@@ -4157,6 +4306,8 @@ var noOpExecution = {
4157
4306
  finish: () => {
4158
4307
  },
4159
4308
  mergeMetadata: () => {
4309
+ },
4310
+ captureInput: () => {
4160
4311
  }
4161
4312
  }),
4162
4313
  getErrorState: () => void 0,
@@ -4219,24 +4370,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
4219
4370
  const functionMetrics = hooks.functionMetrics;
4220
4371
  const executionMetrics = hooks.executionMetrics;
4221
4372
  const durationSampler = hooks.durationSampler;
4222
- const bindMetricsExecution = (recording) => {
4223
- if (!functionMetrics) return;
4224
- recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
4225
- executionTypeKey(recording.execution)
4226
- );
4227
- };
4228
- const bindExecutionMetricsIdentity2 = (recording) => {
4229
- if (!executionMetrics || !recording.executionMetrics) return;
4230
- executionMetrics.bindIdentity(
4231
- recording.executionMetrics,
4232
- executionTypeKey(recording.execution)
4233
- );
4373
+ const metricsExecutionHandleFor = (recording) => {
4374
+ if (!functionMetrics) return void 0;
4375
+ const key = executionTypeKey(recording.execution);
4376
+ if (recording.metricsExecutionKey === key) return recording.metricsExecutionHandle;
4377
+ recording.metricsExecutionKey = key;
4378
+ recording.metricsExecutionHandle = functionMetrics.internExecutionKey(key);
4379
+ return recording.metricsExecutionHandle;
4234
4380
  };
4235
4381
  warnIfMissingAsyncContextFrame();
4236
- const adaptiveEnabled = options.adaptive?.enabled === true;
4237
- const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
4238
- options.adaptive?.fullCaptureDurationMs
4239
- );
4382
+ const adaptiveEnabled = resolveExecutionRecordingMode(options) === "adaptive";
4383
+ const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(options.dynamicFullCaptureDurationMs);
4240
4384
  const trackCallers = durationSampler !== void 0;
4241
4385
  const readCallClock = () => process.hrtime.bigint();
4242
4386
  const tryCallClock3 = () => {
@@ -4367,55 +4511,177 @@ var createExecutionRecorder = (options, hooks = {}) => {
4367
4511
  stats.totalInlineWallTimeMs = Math.round((stats.totalInlineWallTimeMs + inlineWallTimeMs) * 1e4) / 1e4;
4368
4512
  stats.maxInlineWallTimeMs = Math.max(stats.maxInlineWallTimeMs, inlineWallTimeMs);
4369
4513
  };
4370
- const freezeAndCount = (recording, value) => {
4371
- const frozen = (recording.serializer ?? serializer).freeze(value);
4514
+ const EMPTY_POLICY = {
4515
+ ordinary: false,
4516
+ sessionValues: false,
4517
+ captureValues: false
4518
+ };
4519
+ const freezeAndCount = (value, encodeSerializer = serializer) => {
4520
+ const frozen = encodeSerializer.freeze(value);
4372
4521
  stats.serializedValues++;
4373
4522
  stats.serializedValueNodes += frozen.visitedNodes;
4374
4523
  stats.serializedValueBytes += frozen.estimatedBytes;
4375
4524
  return frozen;
4376
4525
  };
4377
- const captureValue = (recording, value) => {
4526
+ const captureValue = (recording, value, encodeSerializer = serializer) => {
4378
4527
  try {
4379
4528
  return memoryBudget.captureValue(
4380
4529
  recording.memory,
4381
4530
  value,
4382
- (item) => freezeAndCount(recording, item)
4531
+ (item) => freezeAndCount(item, encodeSerializer)
4383
4532
  );
4384
4533
  } catch {
4385
4534
  return { __rasputin_type: "unserializable" };
4386
4535
  }
4387
4536
  };
4388
- const encodeEventValues = (recording, events) => events.map((event) => {
4389
- const encode = (recording.serializer ?? serializer).encode;
4390
- if (event.type === "function_enter") {
4391
- return {
4392
- ...event,
4393
- ...event.args === void 0 ? {} : { args: event.args.map((argument) => encode(argument)) }
4394
- };
4537
+ const sessionExcludedFor = (store, plan) => Boolean(store.sessionSuppressCapture) || Boolean(store.recording.sessionExcludes?.(plan.definition));
4538
+ const capturePolicyFor = (recording, store, plan, observedCalls) => {
4539
+ const sessionId = sessionExcludedFor(store, plan) ? void 0 : recording.sessionId;
4540
+ return {
4541
+ ordinary: recording.captureValues && observedCalls <= maxCapturedCallsPerFunction,
4542
+ sessionValues: Boolean(sessionId) && observedCalls <= (recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction),
4543
+ captureValues: recording.captureValues,
4544
+ ...sessionId ? { sessionId, serializer: recording.serializer ?? serializer } : {}
4545
+ };
4546
+ };
4547
+ const throwPolicyFrom = (policy) => ({
4548
+ ordinary: policy.captureValues,
4549
+ sessionValues: Boolean(policy.sessionId),
4550
+ captureValues: policy.captureValues,
4551
+ ...policy.sessionId ? { sessionId: policy.sessionId, serializer: policy.serializer } : {}
4552
+ });
4553
+ const packCapturedValue = (policy, ordinaryValue, sessionValue) => {
4554
+ if (policy.ordinary && policy.sessionValues && policy.sessionId) {
4555
+ return tagOrdinaryAndSessionCapture(policy.sessionId, sessionValue, ordinaryValue);
4395
4556
  }
4396
- if (event.type === "function_exit") {
4397
- return event.returnValue === void 0 ? event : { ...event, returnValue: encode(event.returnValue) };
4557
+ if (policy.sessionValues && policy.sessionId) {
4558
+ return tagSessionCapture(policy.sessionId, sessionValue);
4398
4559
  }
4399
- if (event.type === "function_throw") {
4400
- return { ...event, error: encode(event.error) };
4560
+ return ordinaryValue;
4561
+ };
4562
+ const encodeEventValues = (recording, events, includeSessionId) => {
4563
+ const encode = (includeSessionId ? recording.serializer ?? serializer : serializer).encode;
4564
+ const sessionCallIds = includeSessionId === void 0 ? void 0 : new Set(
4565
+ events.flatMap(
4566
+ (event) => event.type === "function_enter" && event.sessionCaptureId === includeSessionId ? [event.callId] : []
4567
+ )
4568
+ );
4569
+ const mapped = [];
4570
+ for (const event of events) {
4571
+ if (includeSessionId !== void 0) {
4572
+ if ((event.type === "function_enter" || event.type === "function_exit") && event.sessionCaptureId !== includeSessionId) {
4573
+ continue;
4574
+ }
4575
+ if (event.type === "function_throw" && !sessionCallIds?.has(event.callId)) continue;
4576
+ if (event.type === "function_calls_suppressed" && !events.some(
4577
+ (candidate) => candidate.type === "function_enter" && candidate.functionId === event.functionId && candidate.sessionCaptureId === includeSessionId
4578
+ )) {
4579
+ continue;
4580
+ }
4581
+ }
4582
+ if (event.type === "function_enter") {
4583
+ const next = {
4584
+ type: event.type,
4585
+ callId: event.callId,
4586
+ functionId: event.functionId,
4587
+ ...event.timestampMs === void 0 ? {} : { timestampMs: event.timestampMs },
4588
+ ...event.parentCallId === void 0 ? {} : { parentCallId: event.parentCallId },
4589
+ ...event.capturedAt === void 0 ? {} : { capturedAt: event.capturedAt },
4590
+ ...event.provenance === void 0 ? {} : { provenance: event.provenance }
4591
+ };
4592
+ if (includeSessionId !== void 0) {
4593
+ if (event.sessionArgs === void 0) {
4594
+ mapped.push({ ...next, argsOmitted: true });
4595
+ continue;
4596
+ }
4597
+ mapped.push({
4598
+ ...next,
4599
+ args: event.sessionArgs.map((argument) => encode(argument))
4600
+ });
4601
+ continue;
4602
+ }
4603
+ const keepOrdinary = event.ordinaryCapture || event.sessionCaptureId === void 0;
4604
+ if (!keepOrdinary || event.argsOmitted) {
4605
+ mapped.push({ ...next, argsOmitted: true });
4606
+ continue;
4607
+ }
4608
+ if (event.args === void 0) {
4609
+ mapped.push(next);
4610
+ continue;
4611
+ }
4612
+ mapped.push({ ...next, args: event.args.map((argument) => encode(argument)) });
4613
+ continue;
4614
+ }
4615
+ if (event.type === "function_exit") {
4616
+ const next = {
4617
+ type: event.type,
4618
+ callId: event.callId,
4619
+ ...event.timestampMs === void 0 ? {} : { timestampMs: event.timestampMs },
4620
+ ...event.durationMs === void 0 ? {} : { durationMs: event.durationMs }
4621
+ };
4622
+ if (includeSessionId !== void 0) {
4623
+ if (!Object.hasOwn(event, "sessionReturnValue")) {
4624
+ mapped.push(next);
4625
+ continue;
4626
+ }
4627
+ mapped.push({ ...next, returnValue: encode(event.sessionReturnValue) });
4628
+ continue;
4629
+ }
4630
+ const keepOrdinary = event.ordinaryCapture || event.sessionCaptureId === void 0;
4631
+ if (!keepOrdinary || event.returnValue === void 0) {
4632
+ mapped.push(next);
4633
+ continue;
4634
+ }
4635
+ mapped.push({ ...next, returnValue: encode(event.returnValue) });
4636
+ continue;
4637
+ }
4638
+ if (event.type === "function_throw") {
4639
+ mapped.push({
4640
+ type: event.type,
4641
+ callId: event.callId,
4642
+ ...event.timestampMs === void 0 ? {} : { timestampMs: event.timestampMs },
4643
+ ...event.durationMs === void 0 ? {} : { durationMs: event.durationMs },
4644
+ error: encode(event.error)
4645
+ });
4646
+ continue;
4647
+ }
4648
+ mapped.push(event);
4401
4649
  }
4402
- return event;
4403
- });
4404
- const enterPayload = (recording, omitCallValues, args) => {
4405
- if (!recording.captureValues) return ARGS_OMITTED;
4650
+ return mapped;
4651
+ };
4652
+ const captureArgs = (recording, omitCallValues, args, encodeSerializer) => {
4406
4653
  if (omitCallValues) return mapArrayLike(args, () => rasputinOmitted());
4407
- return mapArrayLike(args, (argument) => captureValue(recording, argument));
4654
+ return mapArrayLike(args, (argument) => captureValue(recording, argument, encodeSerializer));
4655
+ };
4656
+ const enterPayload = (recording, omitCallValues, args, policy) => {
4657
+ if (!policy.ordinary && !policy.sessionValues) return ARGS_OMITTED;
4658
+ const sessionSerializer = policy.serializer ?? serializer;
4659
+ if (omitCallValues || !policy.ordinary || !policy.sessionValues || sessionSerializer === serializer) {
4660
+ const shared = policy.ordinary ? captureArgs(recording, omitCallValues, args, serializer) : captureArgs(recording, omitCallValues, args, sessionSerializer);
4661
+ return packCapturedValue(policy, shared, shared);
4662
+ }
4663
+ return packCapturedValue(
4664
+ policy,
4665
+ captureArgs(recording, false, args, serializer),
4666
+ captureArgs(recording, false, args, sessionSerializer)
4667
+ );
4408
4668
  };
4409
- const exitPayload = (recording, omitCallValues, value) => {
4410
- if (!recording.captureValues) return ARGS_OMITTED;
4411
- if (omitCallValues) return rasputinOmitted();
4412
- return captureValue(recording, value);
4669
+ const exitPayload = (recording, omitCallValues, value, policy) => {
4670
+ if (!policy.ordinary && !policy.sessionValues) return ARGS_OMITTED;
4671
+ const sessionSerializer = policy.serializer ?? serializer;
4672
+ if (omitCallValues || !policy.ordinary || !policy.sessionValues || sessionSerializer === serializer) {
4673
+ const shared = omitCallValues ? rasputinOmitted() : captureValue(recording, value, policy.ordinary ? serializer : sessionSerializer);
4674
+ return packCapturedValue(policy, shared, shared);
4675
+ }
4676
+ return packCapturedValue(
4677
+ policy,
4678
+ captureValue(recording, value, serializer),
4679
+ captureValue(recording, value, sessionSerializer)
4680
+ );
4413
4681
  };
4414
4682
  const admitSession = (recording, session) => {
4415
- const wasLight = adaptiveEnabled && !recording.captureValues;
4416
4683
  recording.retainSuccess = true;
4417
4684
  recording.sessionId = session.sessionId;
4418
- recording.captureValues = true;
4419
4685
  if (session.serializer) recording.serializer = session.serializer;
4420
4686
  if (session.redactKeys?.length) recording.sessionRedactKeys = session.redactKeys;
4421
4687
  if (session.excludeSources?.length) {
@@ -4430,28 +4696,29 @@ var createExecutionRecorder = (options, hooks = {}) => {
4430
4696
  if (session.maxExecutionHoldMs !== void 0) {
4431
4697
  recording.sessionHoldNs = BigInt(Math.max(1, Math.round(session.maxExecutionHoldMs))) * 1000000n;
4432
4698
  }
4433
- if (wasLight) {
4434
- stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4435
- stats.adaptiveFullExecutions++;
4436
- }
4437
4699
  };
4438
- const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
4439
- const callStoreFor = (store, functionId, callId) => {
4440
- const next = { ...store, currentCallId: callId };
4700
+ const skipCapture = (store, plan) => store.suppressCapture || plan.excluded;
4701
+ const callStoreFor = (store, functionId, callId, sessionSuppress) => {
4702
+ const next = {
4703
+ ...store,
4704
+ currentCallId: callId,
4705
+ ...sessionSuppress ? { sessionSuppressCapture: true } : {}
4706
+ };
4441
4707
  if (trackCallers) next.currentFunctionId = functionId;
4442
4708
  return next;
4443
4709
  };
4444
4710
  const samplingStore = (store, functionId) => {
4445
4711
  return trackCallers ? { ...store, currentFunctionId: functionId } : store;
4446
4712
  };
4447
- const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess);
4713
+ const sessionBodyStore = (store, sessionExcluded) => sessionExcluded ? { ...store, sessionSuppressCapture: true } : store;
4714
+ const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.resolvedExecutionKey !== void 0 && !recording.captureValues && !recording.retainSuccess);
4448
4715
  const planInvocationDuration = (recording, plan, callerFunctionId) => planCallDuration(durationSampler, {
4449
4716
  forceMeasure: recorderForceMeasure(recording),
4450
4717
  executionType: executionTypeKey(recording.execution),
4451
4718
  callerFunctionId: callerFunctionId ?? "",
4452
4719
  functionId: plan.functionId
4453
4720
  });
4454
- const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
4721
+ const capturedCallLimitFor = (recording) => Math.max(maxCapturedCallsPerFunction, recording.sessionMaxCapturedCalls ?? 0);
4455
4722
  const tryAdmitLiveSession = (recording) => {
4456
4723
  if (recording.retainSuccess || recording.finished) return;
4457
4724
  const key = executionTypeKey(recording.execution);
@@ -4459,29 +4726,59 @@ var createExecutionRecorder = (options, hooks = {}) => {
4459
4726
  const peek = hooks.sessionCaptureSnapshot?.().get(key);
4460
4727
  if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
4461
4728
  const live = hooks.consumeSession?.(key, peek.sessionId);
4462
- if (live) admitSession(recording, live);
4463
- };
4464
- const tryAdmitFromStartSnapshot = (recording) => {
4465
- if (recording.retainSuccess || recording.finished) return;
4729
+ if (!live) return;
4730
+ admitSession(recording, live);
4731
+ recording.sessionReserved = true;
4732
+ };
4733
+ const setCaptureValues = (recording, next) => {
4734
+ if (recording.captureValues === next) return;
4735
+ recording.captureValues = next;
4736
+ if (!adaptiveEnabled) return;
4737
+ if (next) {
4738
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4739
+ stats.adaptiveFullExecutions++;
4740
+ return;
4741
+ }
4742
+ stats.adaptiveFullExecutions = Math.max(0, stats.adaptiveFullExecutions - 1);
4743
+ stats.adaptiveLightExecutions++;
4744
+ };
4745
+ const detachSession = (recording) => {
4746
+ if (!recording.sessionId) return;
4747
+ delete recording.sessionId;
4748
+ delete recording.sessionReserved;
4749
+ delete recording.retainSuccess;
4750
+ delete recording.serializer;
4751
+ delete recording.sessionRedactKeys;
4752
+ delete recording.sessionExcludes;
4753
+ delete recording.sessionMaxCapturedCalls;
4754
+ delete recording.sessionHoldNs;
4755
+ };
4756
+ const applyExecutionIdentity = (recording) => {
4757
+ if (recording.finished) return;
4466
4758
  const key = executionTypeKey(recording.execution);
4467
- if (!key) return;
4468
- const peek = recording.sessionCaptureSnapshot.get(key);
4469
- if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
4470
- const live = hooks.consumeSession?.(key, peek.sessionId);
4471
- if (live) admitSession(recording, live);
4759
+ if (!key || recording.resolvedExecutionKey === key) return;
4760
+ detachSession(recording);
4761
+ recording.resolvedExecutionKey = key;
4762
+ if (adaptiveEnabled) {
4763
+ setCaptureValues(
4764
+ recording,
4765
+ keyIsActive(recording.policySnapshot, key, recording.startedAtMs)
4766
+ );
4767
+ }
4768
+ const session = recording.sessionCaptureSnapshot.get(key);
4769
+ if (session && session.expiresAtMs > recording.startedAtMs) {
4770
+ admitSession(recording, session);
4771
+ }
4472
4772
  };
4473
- const completeIdentityFromSnapshot = (recording) => {
4474
- if (recording.identityResolved || recording.finished) return;
4773
+ const reserveSession = (recording) => {
4774
+ if (!recording.sessionId || recording.sessionReserved || !hooks.consumeSession) return;
4475
4775
  const key = executionTypeKey(recording.execution);
4476
- if (!key) return;
4477
- recording.identityResolved = true;
4478
- tryAdmitFromStartSnapshot(recording);
4479
- if (recording.captureValues || !adaptiveEnabled) return;
4480
- if (keyIsActive(recording.policySnapshot, key, recording.startedAtMs)) {
4481
- recording.captureValues = true;
4482
- stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4483
- stats.adaptiveFullExecutions++;
4776
+ const reserved = key ? hooks.consumeSession(key, recording.sessionId) : void 0;
4777
+ if (reserved) {
4778
+ recording.sessionReserved = true;
4779
+ return;
4484
4780
  }
4781
+ detachSession(recording);
4485
4782
  };
4486
4783
  const maybeActivateAdaptive = (recording) => {
4487
4784
  if (!adaptiveEnabled || recording.adaptiveActivated) return;
@@ -4554,7 +4851,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4554
4851
  }
4555
4852
  return false;
4556
4853
  };
4557
- const resolveCaptureProfile = (recording, events, truncated, capture) => {
4854
+ const resolveCaptureProfile = (recording, events, truncated, capture, includeSessionId) => {
4558
4855
  const source = recording.sawAutomatic ? "automatic" : recording.sawManual ? "manual" : "scope-only";
4559
4856
  if (source === "scope-only") {
4560
4857
  return {
@@ -4590,20 +4887,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
4590
4887
  }
4591
4888
  const droppedEvents = Boolean(truncated?.eventsDropped || capture?.eventsDropped);
4592
4889
  const evidence = retainedTimingsCoverage(events);
4890
+ const includeValues = recording.captureValues || includeSessionId !== void 0;
4593
4891
  return {
4594
4892
  source,
4595
4893
  functionBoundaries: droppedEvents ? "partial" : "full",
4596
- functionValues: recording.captureValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
4894
+ functionValues: includeValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
4597
4895
  timings: droppedEvents && evidence === "full" ? "partial" : evidence
4598
4896
  };
4599
4897
  };
4600
- const stateFrom = (recording, endedAtNs = process.hrtime.bigint()) => {
4898
+ const stateFrom = (recording, endedAtNs = process.hrtime.bigint(), includeSessionId) => {
4601
4899
  const recorderStartedAtNs = process.hrtime.bigint();
4602
4900
  let events = [];
4603
4901
  let functions = [];
4604
4902
  let truncated;
4605
4903
  let capture;
4606
- if (recording.cachedState) {
4904
+ if (recording.cachedState && includeSessionId === void 0) {
4607
4905
  events = recording.cachedState.events;
4608
4906
  functions = recording.cachedState.functions;
4609
4907
  truncated = recording.cachedState.truncated;
@@ -4611,13 +4909,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
4611
4909
  } else {
4612
4910
  if (recording.journal) {
4613
4911
  const materialized = recording.journal.materialize(plansByRuntimeId, recording.startedAtNs);
4614
- events = encodeEventValues(recording, materialized.events);
4912
+ events = encodeEventValues(recording, materialized.events, includeSessionId);
4615
4913
  if (recording.lateCapturedCallIds && recording.lateCapturedCallIds.size > 0) {
4616
4914
  events = events.map(
4617
4915
  (event) => event.type === "function_enter" && recording.lateCapturedCallIds?.has(event.callId) ? { ...event, capturedAt: "throw" } : event
4618
4916
  );
4619
4917
  }
4620
- functions = materialized.functions;
4918
+ if (includeSessionId === void 0) {
4919
+ functions = materialized.functions;
4920
+ } else {
4921
+ const usedIds = /* @__PURE__ */ new Set();
4922
+ for (const event of events) {
4923
+ if (event.type === "function_enter" || event.type === "function_calls_suppressed") {
4924
+ usedIds.add(event.functionId);
4925
+ }
4926
+ }
4927
+ functions = materialized.functions.filter(
4928
+ (definition) => usedIds.has(definition.functionId)
4929
+ );
4930
+ }
4621
4931
  truncated = recording.journal.dropped > 0 ? { eventsDropped: recording.journal.dropped } : void 0;
4622
4932
  }
4623
4933
  if (recording.budgetExpired) {
@@ -4642,13 +4952,19 @@ var createExecutionRecorder = (options, hooks = {}) => {
4642
4952
  eventsDropped: recording.memory.eventsDropped
4643
4953
  };
4644
4954
  }
4645
- if (recording.finished && recording.inFlightCalls === 0 && recording.journal) {
4955
+ if (includeSessionId === void 0 && recording.finished && recording.inFlightCalls === 0 && recording.journal) {
4646
4956
  recording.cachedState = { events, functions, truncated, capture };
4647
4957
  journalPool.release(recording.journal);
4648
4958
  recording.journal = void 0;
4649
4959
  }
4650
4960
  }
4651
- const captureProfile = resolveCaptureProfile(recording, events, truncated, capture);
4961
+ const captureProfile = resolveCaptureProfile(
4962
+ recording,
4963
+ events,
4964
+ truncated,
4965
+ capture,
4966
+ includeSessionId
4967
+ );
4652
4968
  const fullyTimed = eventsAreFullyTimed(events);
4653
4969
  const state = {
4654
4970
  version: 4,
@@ -4665,7 +4981,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
4665
4981
  events: fullyTimed ? asFullyTimedEvents(events) : events.slice(),
4666
4982
  ...fullyTimed || !durationSampler ? {} : { durationSampling: { policy: "progressive" } },
4667
4983
  ...truncated ? { truncated: { ...truncated } } : {},
4668
- ...capture ? { capture: { ...capture } } : {}
4984
+ ...capture ? { capture: { ...capture } } : {},
4985
+ ...includeSessionId === void 0 ? recording.inputSnapshot && Object.hasOwn(recording.inputSnapshot, "ordinary") ? { input: serializer.encode(recording.inputSnapshot.ordinary) } : {} : recording.inputSnapshot?.sessionId === includeSessionId && Object.hasOwn(recording.inputSnapshot, "sessionValue") ? {
4986
+ input: (recording.serializer ?? serializer).encode(
4987
+ recording.inputSnapshot.sessionValue
4988
+ )
4989
+ } : {}
4669
4990
  };
4670
4991
  if (phaseTimingEnabled)
4671
4992
  addPhase("materializeNs", process.hrtime.bigint() - recorderStartedAtNs);
@@ -4691,6 +5012,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4691
5012
  recording.cachedState = void 0;
4692
5013
  recording.repeatedCalls = void 0;
4693
5014
  recording.lateCapturedCallIds = void 0;
5015
+ recording.inputSnapshot = void 0;
4694
5016
  recording.capturedErrors = /* @__PURE__ */ new WeakMap();
4695
5017
  if (recording.journal) {
4696
5018
  journalPool.release(recording.journal);
@@ -4726,6 +5048,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4726
5048
  recording.journal = void 0;
4727
5049
  }
4728
5050
  recording.evicted = true;
5051
+ recording.inputSnapshot = void 0;
4729
5052
  detachLiveRecording(recording);
4730
5053
  recording.cachedState = {
4731
5054
  events: [],
@@ -4779,6 +5102,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4779
5102
  journalPool.release(recording.journal);
4780
5103
  recording.journal = void 0;
4781
5104
  }
5105
+ recording.inputSnapshot = void 0;
4782
5106
  recording.cachedState = {
4783
5107
  events: [],
4784
5108
  functions: [],
@@ -4815,7 +5139,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4815
5139
  liveRecordings.splice(index, 1);
4816
5140
  continue;
4817
5141
  }
4818
- if (nowNs - recording.startedAtNs < (recording.sessionHoldNs ?? maxExecutionHoldNs)) continue;
5142
+ const holdNs = recording.sessionHoldNs !== void 0 && recording.sessionHoldNs > maxExecutionHoldNs ? recording.sessionHoldNs : maxExecutionHoldNs;
5143
+ if (nowNs - recording.startedAtNs < holdNs) continue;
4819
5144
  try {
4820
5145
  expireLongLivedRecording(recording, nowNs);
4821
5146
  } catch {
@@ -4923,7 +5248,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4923
5248
  // snapshot without the exception itself would not be useful for investigation.
4924
5249
  value: (() => {
4925
5250
  try {
4926
- return freezeAndCount(recording, error).value;
5251
+ return freezeAndCount(error).value;
4927
5252
  } catch {
4928
5253
  return { __rasputin_type: "unserializable" };
4929
5254
  }
@@ -4933,7 +5258,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4933
5258
  }
4934
5259
  };
4935
5260
  };
4936
- const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
5261
+ const captureCompletedThrow = (recording, plan, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
4937
5262
  if (!recording.journal) {
4938
5263
  return;
4939
5264
  }
@@ -4942,7 +5267,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4942
5267
  }
4943
5268
  const callId = ++recording.nextCallId;
4944
5269
  const capturedError = serializedError(recording, error, callId);
4945
- const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
5270
+ const recordedArgs = capturedArgs;
4946
5271
  const endedAtNs = timed ? completedAtNs : void 0;
4947
5272
  const droppedBefore = recording.journal.dropped;
4948
5273
  const retained = recording.journal.forceCompletedCall(
@@ -5026,7 +5351,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5026
5351
  sessionId: recording.sessionId,
5027
5352
  executionId: recording.executionId,
5028
5353
  outcome: recording.hasError || recording.runFailed ? "error" : "success",
5029
- runtimeState: stateFrom(recording),
5354
+ runtimeState: stateFrom(recording, void 0, recording.sessionId),
5030
5355
  redactKeys: recording.sessionRedactKeys
5031
5356
  });
5032
5357
  } catch {
@@ -5062,16 +5387,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
5062
5387
  return;
5063
5388
  }
5064
5389
  const recorderStartedAtNs = process.hrtime.bigint();
5065
- recording.finished = true;
5066
5390
  if (metadata) {
5067
5391
  mergeExecutionMetadata(recording.execution, metadata);
5068
- bindMetricsExecution(recording);
5069
- bindExecutionMetricsIdentity2(recording);
5392
+ applyExecutionIdentity(recording);
5070
5393
  }
5394
+ recording.finished = true;
5395
+ reserveSession(recording);
5071
5396
  if (executionMetrics && recording.executionMetrics) {
5072
5397
  const executionKey = executionTypeKey(recording.execution);
5073
- bindExecutionMetricsIdentity2(recording);
5074
5398
  executionMetrics.finishExecution(recording.executionMetrics, {
5399
+ key: executionKey,
5075
5400
  failed: executionOutcomeFailed({
5076
5401
  hasError: recording.hasError,
5077
5402
  runFailed: recording.runFailed === true,
@@ -5116,7 +5441,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
5116
5441
  ...metadata,
5117
5442
  ...metadata.request ? { request: { ...metadata.request } } : {}
5118
5443
  };
5119
- const identityComplete = executionTypeKey(execution) !== void 0;
5444
+ const initialKey = executionTypeKey(execution);
5445
+ const identityComplete = initialKey !== void 0;
5120
5446
  const captureValues = captureValuesFor(execution, livePolicy, startedAtMs);
5121
5447
  const policySnapshot = adaptiveEnabled && !identityComplete ? new Map(livePolicy) : EMPTY_POLICY_SNAPSHOT;
5122
5448
  const liveSessions = hooks.sessionCaptureSnapshot?.() ?? EMPTY_SESSION_SNAPSHOT;
@@ -5144,14 +5470,15 @@ var createExecutionRecorder = (options, hooks = {}) => {
5144
5470
  sawManual: false,
5145
5471
  captureValues,
5146
5472
  policySnapshot,
5147
- identityResolved: identityComplete,
5473
+ resolvedExecutionKey: initialKey,
5148
5474
  sessionCaptureSnapshot
5149
5475
  };
5150
5476
  if (identityComplete) tryAdmitLiveSession(recording);
5151
- bindMetricsExecution(recording);
5152
5477
  if (executionMetrics) {
5153
5478
  recording.executionMetrics = executionMetrics.createState();
5154
- bindExecutionMetricsIdentity2(recording);
5479
+ if (execution.kind !== "http") {
5480
+ executionMetrics.bindIdentity(recording.executionMetrics, initialKey);
5481
+ }
5155
5482
  }
5156
5483
  stats.activeExecutions++;
5157
5484
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
@@ -5203,9 +5530,32 @@ var createExecutionRecorder = (options, hooks = {}) => {
5203
5530
  mergeMetadata: (nextMetadata) => {
5204
5531
  try {
5205
5532
  mergeExecutionMetadata(recording.execution, nextMetadata);
5206
- completeIdentityFromSnapshot(recording);
5207
- bindMetricsExecution(recording);
5208
- bindExecutionMetricsIdentity2(recording);
5533
+ applyExecutionIdentity(recording);
5534
+ if (executionMetrics && recording.executionMetrics && recording.execution.kind !== "http") {
5535
+ executionMetrics.bindIdentity(
5536
+ recording.executionMetrics,
5537
+ executionTypeKey(recording.execution)
5538
+ );
5539
+ }
5540
+ } catch {
5541
+ }
5542
+ },
5543
+ captureInput: (value) => {
5544
+ try {
5545
+ if (recording.inputSnapshot || recording.evidenceDiscarded || recording.evicted || recording.budgetExpired) {
5546
+ return;
5547
+ }
5548
+ const ordinary = captureValue(recording, value, serializer);
5549
+ if (!recording.sessionId) {
5550
+ recording.inputSnapshot = { ordinary };
5551
+ return;
5552
+ }
5553
+ const sessionSerializer = recording.serializer ?? serializer;
5554
+ recording.inputSnapshot = {
5555
+ ordinary,
5556
+ sessionId: recording.sessionId,
5557
+ sessionValue: sessionSerializer === serializer ? ordinary : captureValue(recording, value, sessionSerializer)
5558
+ };
5209
5559
  } catch {
5210
5560
  }
5211
5561
  }
@@ -5225,7 +5575,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5225
5575
  const duration = plan.excluded ? { selected: false, measure: false } : store ? planInvocationDuration(store.recording, plan, store.currentFunctionId) : { selected: false, measure: false };
5226
5576
  const startedNs = duration.measure ? tryCallClock3() : void 0;
5227
5577
  const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
5228
- const executionHandle = store?.recording.metricsExecutionHandle;
5578
+ const executionHandle = functionHandle !== void 0 && store ? metricsExecutionHandleFor(store.recording) : void 0;
5229
5579
  const metricsStart = startMetricsCall(functionMetrics, functionHandle, executionHandle, {
5230
5580
  measure: duration.selected,
5231
5581
  ...duration.selected ? { startedNs } : {}
@@ -5316,10 +5666,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
5316
5666
  const recorderStartedAtNs = process.hrtime.bigint();
5317
5667
  if (skipCapture(store, plan)) {
5318
5668
  stats.functionCallsExcluded++;
5319
- return runStore({ ...store, suppressCapture: true }, function __rasputinHandleRun__5() {
5320
- addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
5321
- return callback();
5322
- });
5669
+ return runStore(
5670
+ { ...store, suppressCapture: true, sessionSuppressCapture: true },
5671
+ function __rasputinHandleRun__5() {
5672
+ addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
5673
+ return callback();
5674
+ }
5675
+ );
5323
5676
  }
5324
5677
  const recording = store.recording;
5325
5678
  recording.inFlightCalls++;
@@ -5333,10 +5686,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
5333
5686
  }
5334
5687
  const timed = sharedClock.timed;
5335
5688
  const startedAtNs = sharedClock.start ?? 0n;
5689
+ const sessionExcluded = sessionExcludedFor(store, plan);
5690
+ const policy = capturePolicyFor(recording, store, plan, group.observedCalls);
5336
5691
  if (group.observedCalls > capturedCallLimitFor(recording)) {
5337
5692
  try {
5338
5693
  const result = runStore(
5339
- samplingStore(store, plan.functionId),
5694
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5340
5695
  function __rasputinHandleRun__5() {
5341
5696
  return callback();
5342
5697
  }
@@ -5371,12 +5726,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
5371
5726
  captureCompletedThrow(
5372
5727
  recording,
5373
5728
  plan,
5374
- args,
5375
5729
  parentCallId,
5376
5730
  startedAtNs,
5377
5731
  error,
5378
5732
  timed,
5379
- void 0,
5733
+ enterPayload(recording, omitCallValues, args, throwPolicyFrom(policy)),
5380
5734
  sharedClock.end
5381
5735
  );
5382
5736
  settleInFlight(recording);
@@ -5385,17 +5739,20 @@ var createExecutionRecorder = (options, hooks = {}) => {
5385
5739
  }
5386
5740
  if (!journal) {
5387
5741
  memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes);
5388
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5389
- return observeRecordedCallback(
5390
- recording,
5391
- recorderStartedAtNs,
5392
- callback,
5393
- () => settleInFlight(recording),
5394
- (_error) => {
5395
- settleInFlight(recording);
5396
- }
5397
- );
5398
- });
5742
+ return runStore(
5743
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5744
+ function __rasputinHandleRun__5() {
5745
+ return observeRecordedCallback(
5746
+ recording,
5747
+ recorderStartedAtNs,
5748
+ callback,
5749
+ () => settleInFlight(recording),
5750
+ (_error) => {
5751
+ settleInFlight(recording);
5752
+ }
5753
+ );
5754
+ }
5755
+ );
5399
5756
  }
5400
5757
  if (!journal.canStartCall()) {
5401
5758
  const captureSuccess = () => {
@@ -5404,63 +5761,71 @@ var createExecutionRecorder = (options, hooks = {}) => {
5404
5761
  countDroppedEvents(recording, droppedBefore);
5405
5762
  settleInFlight(recording);
5406
5763
  };
5407
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5408
- return observeRecordedCallback(
5409
- recording,
5410
- recorderStartedAtNs,
5411
- callback,
5412
- captureSuccess,
5413
- (error) => {
5414
- if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5415
- captureCompletedThrow(
5416
- recording,
5417
- plan,
5418
- args,
5419
- parentCallId,
5420
- startedAtNs,
5421
- error,
5422
- timed,
5423
- void 0,
5424
- sharedClock.end
5425
- );
5426
- settleInFlight(recording);
5427
- }
5428
- );
5429
- });
5764
+ return runStore(
5765
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5766
+ function __rasputinHandleRun__5() {
5767
+ return observeRecordedCallback(
5768
+ recording,
5769
+ recorderStartedAtNs,
5770
+ callback,
5771
+ captureSuccess,
5772
+ (error) => {
5773
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5774
+ captureCompletedThrow(
5775
+ recording,
5776
+ plan,
5777
+ parentCallId,
5778
+ startedAtNs,
5779
+ error,
5780
+ timed,
5781
+ enterPayload(recording, omitCallValues, args, policy),
5782
+ sharedClock.end
5783
+ );
5784
+ settleInFlight(recording);
5785
+ }
5786
+ );
5787
+ }
5788
+ );
5430
5789
  }
5431
5790
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
5432
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5433
- return observeRecordedCallback(
5434
- recording,
5435
- recorderStartedAtNs,
5436
- callback,
5437
- () => settleInFlight(recording),
5438
- (_error) => {
5439
- settleInFlight(recording);
5440
- }
5441
- );
5442
- });
5791
+ return runStore(
5792
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5793
+ function __rasputinHandleRun__5() {
5794
+ return observeRecordedCallback(
5795
+ recording,
5796
+ recorderStartedAtNs,
5797
+ callback,
5798
+ () => settleInFlight(recording),
5799
+ (_error) => {
5800
+ settleInFlight(recording);
5801
+ }
5802
+ );
5803
+ }
5804
+ );
5443
5805
  }
5444
5806
  const callId = ++recording.nextCallId;
5445
5807
  const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
5446
- const capturedArgs = enterPayload(recording, omitCallValues, args);
5808
+ const capturedArgs = enterPayload(recording, omitCallValues, args, policy);
5447
5809
  try {
5448
5810
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
5449
5811
  } catch {
5450
5812
  journal.dropCall();
5451
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5452
- return observeRecordedCallback(
5453
- recording,
5454
- recorderStartedAtNs,
5455
- callback,
5456
- () => settleInFlight(recording),
5457
- (_error) => {
5458
- settleInFlight(recording);
5459
- }
5460
- );
5461
- });
5813
+ return runStore(
5814
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5815
+ function __rasputinHandleRun__5() {
5816
+ return observeRecordedCallback(
5817
+ recording,
5818
+ recorderStartedAtNs,
5819
+ callback,
5820
+ () => settleInFlight(recording),
5821
+ (_error) => {
5822
+ settleInFlight(recording);
5823
+ }
5824
+ );
5825
+ }
5826
+ );
5462
5827
  }
5463
- const callStore = callStoreFor(store, plan.functionId, callId);
5828
+ const callStore = callStoreFor(store, plan.functionId, callId, sessionExcluded);
5464
5829
  return runStore(callStore, function __rasputinHandleRun__5() {
5465
5830
  return observeRecordedCallback(
5466
5831
  recording,
@@ -5471,7 +5836,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5471
5836
  const pending = value instanceof Promise;
5472
5837
  const endedAtNs = timed && !pending ? tryCallClock3() : void 0;
5473
5838
  if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5474
- const returnValue = exitPayload(recording, omitCallValues, value);
5839
+ const returnValue = exitPayload(recording, omitCallValues, value, policy);
5475
5840
  if (endedAtNs !== void 0) {
5476
5841
  recording.journal.finishCall(
5477
5842
  KIND_EXIT,
@@ -5553,6 +5918,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5553
5918
  this.plan = plan;
5554
5919
  this.args = args;
5555
5920
  this.omitCallValues = omitCallValues;
5921
+ this.policy = EMPTY_POLICY;
5556
5922
  this.parentCallId = parentCallId;
5557
5923
  this.activeStore = activeStore;
5558
5924
  this.parentStore = parentStore;
@@ -5590,7 +5956,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5590
5956
  try {
5591
5957
  if (this.status !== "failed") {
5592
5958
  this.status = "left";
5593
- if (this.recording.captureValues) this.pendingReturn = value;
5959
+ if (this.policy.ordinary || this.policy.sessionValues) this.pendingReturn = value;
5594
5960
  }
5595
5961
  return value;
5596
5962
  } catch {
@@ -5607,27 +5973,32 @@ var createExecutionRecorder = (options, hooks = {}) => {
5607
5973
  }
5608
5974
  if (this.mode === "captured") writeCapturedThrow(this, error);
5609
5975
  else if (this.mode === "suppressed" && this.plan) {
5976
+ const throwPolicy = throwPolicyFrom(this.policy);
5610
5977
  captureCompletedThrow(
5611
5978
  this.recording,
5612
5979
  this.plan,
5613
- this.recording.captureValues ? liveArgs ?? this.args : EMPTY_ARGS,
5614
5980
  this.parentCallId,
5615
5981
  this.startedAtNs,
5616
5982
  error,
5617
5983
  this.timed,
5618
- this.recording.captureValues ? void 0 : ARGS_OMITTED,
5984
+ throwPolicy.ordinary || throwPolicy.sessionValues ? enterPayload(
5985
+ this.recording,
5986
+ this.omitCallValues,
5987
+ liveArgs ?? this.args,
5988
+ throwPolicy
5989
+ ) : ARGS_OMITTED,
5619
5990
  this.completedAtNs
5620
5991
  );
5621
5992
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
5993
+ const throwPolicy = throwPolicyFrom(this.policy);
5622
5994
  captureCompletedThrow(
5623
5995
  this.recording,
5624
5996
  this.plan,
5625
- this.recording.captureValues ? this.args : EMPTY_ARGS,
5626
5997
  this.parentCallId,
5627
5998
  this.startedAtNs,
5628
5999
  error,
5629
6000
  this.timed,
5630
- this.recording.captureValues ? void 0 : ARGS_OMITTED,
6001
+ throwPolicy.ordinary || throwPolicy.sessionValues ? enterPayload(this.recording, this.omitCallValues, this.args, throwPolicy) : ARGS_OMITTED,
5631
6002
  this.completedAtNs
5632
6003
  );
5633
6004
  }
@@ -5744,7 +6115,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5744
6115
  const writeCapturedExit = (frame, value, completedAtNs) => {
5745
6116
  if (!frame.recording.journal) return;
5746
6117
  const endedAtNs = frame.timed ? completedAtNs : void 0;
5747
- const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
6118
+ const returnValue = exitPayload(frame.recording, frame.omitCallValues, value, frame.policy);
5748
6119
  if (endedAtNs !== void 0) {
5749
6120
  frame.recording.journal.finishCall(
5750
6121
  KIND_EXIT,
@@ -5791,14 +6162,14 @@ var createExecutionRecorder = (options, hooks = {}) => {
5791
6162
  const armCallFrameMetrics = (frame, plan) => {
5792
6163
  if (!functionMetrics || plan.excluded) return;
5793
6164
  const functionHandle = internPreparedMetrics(functionMetrics, plan);
6165
+ const executionHandle = functionHandle !== void 0 ? metricsExecutionHandleFor(frame.recording) : void 0;
5794
6166
  const started = startMetricsCall(
5795
6167
  functionMetrics,
5796
6168
  functionHandle,
5797
- frame.recording.metricsExecutionHandle,
6169
+ executionHandle,
5798
6170
  frame.metricsSelected ? { measure: true, startedNs: frame.timed ? frame.startedAtNs : void 0 } : { measure: false }
5799
6171
  );
5800
6172
  if (!started || functionHandle === void 0) return;
5801
- const executionHandle = frame.recording.metricsExecutionHandle;
5802
6173
  if (executionHandle === void 0) return;
5803
6174
  frame.metricsOpen = true;
5804
6175
  frame.metricsMeasure = started.measure;
@@ -5806,12 +6177,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
5806
6177
  frame.metricsExecutionHandle = executionHandle;
5807
6178
  frame.metricsStartedNs = started.startedNs;
5808
6179
  };
5809
- const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected) => {
6180
+ const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected, policy = EMPTY_POLICY, sessionExcluded = false) => {
6181
+ const activeStore = sessionExcluded ? {
6182
+ ...parentStore,
6183
+ sessionSuppressCapture: true,
6184
+ ...trackCallers ? { currentFunctionId: plan.functionId } : {}
6185
+ } : parentStore;
5810
6186
  const frame = new CallFrame(
5811
6187
  mode,
5812
6188
  recording,
5813
6189
  parentStore,
5814
- parentStore,
6190
+ activeStore,
5815
6191
  plan,
5816
6192
  args,
5817
6193
  omitCallValues,
@@ -5823,8 +6199,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5823
6199
  captureDroppedThrow
5824
6200
  );
5825
6201
  frame.metricsSelected = selected;
6202
+ frame.policy = policy;
5826
6203
  frame.claimCaller();
5827
- enterStore(frame, parentStore);
6204
+ enterStore(frame, activeStore);
5828
6205
  armCallFrameMetrics(frame, plan);
5829
6206
  return frame;
5830
6207
  };
@@ -5866,7 +6243,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
5866
6243
  stats.functionCallsExcluded++;
5867
6244
  const excludedDuration = plan.excluded ? { selected: false, measure: false } : planInvocationDuration(recording, plan, store.currentFunctionId);
5868
6245
  const start2 = invocationStart(excludedDuration.measure);
5869
- const excludedStore = { ...store, suppressCapture: true };
6246
+ const excludedStore = {
6247
+ ...store,
6248
+ suppressCapture: true,
6249
+ sessionSuppressCapture: true
6250
+ };
5870
6251
  const frame = new CallFrame(
5871
6252
  "excluded",
5872
6253
  recording,
@@ -5900,7 +6281,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5900
6281
  const timed = start.timed;
5901
6282
  const startedAtNs = start.startedAtNs;
5902
6283
  const parentStore = store;
5903
- const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
6284
+ const sessionExcluded = sessionExcludedFor(store, plan);
6285
+ const policy = capturePolicyFor(recording, store, plan, group.observedCalls);
6286
+ const retainedArgs = policy.ordinary || policy.sessionValues || recording.captureValues || policy.sessionId ? args : EMPTY_ARGS;
5904
6287
  if (group.observedCalls > capturedCallLimitFor(recording)) {
5905
6288
  return activateUncaptured(
5906
6289
  "suppressed",
@@ -5914,7 +6297,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5914
6297
  timed,
5915
6298
  group,
5916
6299
  false,
5917
- duration.selected
6300
+ duration.selected,
6301
+ policy,
6302
+ sessionExcluded
5918
6303
  );
5919
6304
  }
5920
6305
  if (!journal) {
@@ -5931,7 +6316,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5931
6316
  timed,
5932
6317
  group,
5933
6318
  false,
5934
- duration.selected
6319
+ duration.selected,
6320
+ policy,
6321
+ sessionExcluded
5935
6322
  );
5936
6323
  }
5937
6324
  if (!journal.canStartCall()) {
@@ -5947,7 +6334,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5947
6334
  timed,
5948
6335
  group,
5949
6336
  true,
5950
- duration.selected
6337
+ duration.selected,
6338
+ policy,
6339
+ sessionExcluded
5951
6340
  );
5952
6341
  }
5953
6342
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
@@ -5963,12 +6352,14 @@ var createExecutionRecorder = (options, hooks = {}) => {
5963
6352
  timed,
5964
6353
  group,
5965
6354
  false,
5966
- duration.selected
6355
+ duration.selected,
6356
+ policy,
6357
+ sessionExcluded
5967
6358
  );
5968
6359
  }
5969
6360
  const callId = ++recording.nextCallId;
5970
6361
  const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
5971
- const capturedArgs = enterPayload(recording, omitCallValues, args);
6362
+ const capturedArgs = enterPayload(recording, omitCallValues, args, policy);
5972
6363
  try {
5973
6364
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
5974
6365
  } catch {
@@ -5985,10 +6376,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
5985
6376
  timed,
5986
6377
  group,
5987
6378
  false,
5988
- duration.selected
6379
+ duration.selected,
6380
+ policy,
6381
+ sessionExcluded
5989
6382
  );
5990
6383
  }
5991
- const callStore = callStoreFor(store, plan.functionId, callId);
6384
+ const callStore = callStoreFor(store, plan.functionId, callId, sessionExcluded);
5992
6385
  const captured = new CallFrame(
5993
6386
  "captured",
5994
6387
  recording,
@@ -6005,6 +6398,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
6005
6398
  false
6006
6399
  );
6007
6400
  captured.metricsSelected = duration.selected;
6401
+ captured.policy = policy;
6008
6402
  enterStore(captured, callStore);
6009
6403
  armCallFrameMetrics(captured, plan);
6010
6404
  return captured;
@@ -6282,7 +6676,7 @@ var reportedRecorderSettings = (options) => ({
6282
6676
  maxActiveMemoryBytes: options?.maxActiveMemoryBytes,
6283
6677
  maxExecutionHoldMs: options?.maxExecutionHoldMs,
6284
6678
  maxRetainedErrorRecordings: options?.maxRetainedErrorRecordings,
6285
- fullCaptureDurationMs: options?.adaptive?.fullCaptureDurationMs,
6679
+ fullCaptureDurationMs: options?.dynamicFullCaptureDurationMs,
6286
6680
  recorder_enabled: options?.enabled !== false,
6287
6681
  excludeSources: serializeSourceExclusions(options?.excludeSources),
6288
6682
  redactKeys: options?.redactKeys
@@ -6321,6 +6715,8 @@ var DEFAULT_POLL_INTERVAL_MS = 3e4;
6321
6715
  var REQUEST_TIMEOUT_MS2 = 5e3;
6322
6716
  var MAX_RETRIES = 5;
6323
6717
  var MAX_POLL_JITTER_MS = 2e3;
6718
+ var UPLOAD_GRACE_MS = 6e4;
6719
+ var MAX_RETAINED_SESSIONS = 256;
6324
6720
  var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
6325
6721
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6326
6722
  var unwrapPayload = (body) => {
@@ -6342,6 +6738,7 @@ var abortFrom = (parent, child) => {
6342
6738
  };
6343
6739
  var createExecutionRecordingCoordinator = (options) => {
6344
6740
  const environment = options.environment;
6741
+ const mode = resolveExecutionRecordingMode(options.recorderOptions);
6345
6742
  const nowMs = () => options.nowMs?.() ?? Date.now();
6346
6743
  const fetchFn = options.fetch ?? defaultIngestFetch2();
6347
6744
  const instanceId = crypto.randomUUID();
@@ -6351,6 +6748,7 @@ var createExecutionRecordingCoordinator = (options) => {
6351
6748
  const cache = /* @__PURE__ */ new Map();
6352
6749
  const pending = /* @__PURE__ */ new Map();
6353
6750
  const sessionsById = /* @__PURE__ */ new Map();
6751
+ const retainedById = /* @__PURE__ */ new Map();
6354
6752
  const completedSessionIds = /* @__PURE__ */ new Set();
6355
6753
  const recordings = [];
6356
6754
  const capabilities = ["manual_sessions", "settings_overrides"];
@@ -6400,6 +6798,26 @@ var createExecutionRecordingCoordinator = (options) => {
6400
6798
  maxExecutionHoldMs: session.maxExecutionHoldMs
6401
6799
  });
6402
6800
  const sessionHasRoom = (session, atMs) => session.admitted < session.requestedCount && session.expiresAtMs > atMs;
6801
+ const withinUploadGrace = (session, atMs) => atMs <= session.expiresAtMs + UPLOAD_GRACE_MS;
6802
+ const pruneRetained = (atMs) => {
6803
+ for (const [id, session] of retainedById) {
6804
+ if (completedSessionIds.has(id) || session.admitted >= session.requestedCount || !withinUploadGrace(session, atMs)) {
6805
+ retainedById.delete(id);
6806
+ }
6807
+ }
6808
+ while (retainedById.size > MAX_RETAINED_SESSIONS) {
6809
+ let oldestId;
6810
+ let oldestExpires = Number.POSITIVE_INFINITY;
6811
+ for (const [id, session] of retainedById) {
6812
+ if (session.expiresAtMs < oldestExpires) {
6813
+ oldestExpires = session.expiresAtMs;
6814
+ oldestId = id;
6815
+ }
6816
+ }
6817
+ if (oldestId === void 0) break;
6818
+ retainedById.delete(oldestId);
6819
+ }
6820
+ };
6403
6821
  const rebuildSessionSnapshot = () => {
6404
6822
  const atMs = nowMs();
6405
6823
  const map = /* @__PURE__ */ new Map();
@@ -6593,7 +7011,7 @@ var createExecutionRecordingCoordinator = (options) => {
6593
7011
  }
6594
7012
  };
6595
7013
  const kickNotify = () => {
6596
- if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
7014
+ if (closed || closing || pending.size === 0 || mode !== "adaptive") return;
6597
7015
  void drainNotifies(notifySignal());
6598
7016
  };
6599
7017
  const applyCompletedSessionIds = (value) => {
@@ -6603,6 +7021,7 @@ var createExecutionRecordingCoordinator = (options) => {
6603
7021
  if (!sessionId) continue;
6604
7022
  completedSessionIds.add(sessionId);
6605
7023
  sessionsById.delete(sessionId);
7024
+ retainedById.delete(sessionId);
6606
7025
  }
6607
7026
  markSessionsDirty();
6608
7027
  };
@@ -6620,7 +7039,7 @@ var createExecutionRecordingCoordinator = (options) => {
6620
7039
  if (!sessionId || !executionKeyValue || status !== "active") continue;
6621
7040
  if (completedSessionIds.has(sessionId)) continue;
6622
7041
  if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
6623
- const existing = sessionsById.get(sessionId);
7042
+ const existing = sessionsById.get(sessionId) ?? retainedById.get(sessionId);
6624
7043
  const overrides = parseSessionSettings(entry.overrides);
6625
7044
  next.set(sessionId, {
6626
7045
  sessionId,
@@ -6635,8 +7054,19 @@ var createExecutionRecordingCoordinator = (options) => {
6635
7054
  maxExecutionHoldMs: overrides?.maxExecutionHoldMs
6636
7055
  });
6637
7056
  }
7057
+ for (const [id, existing] of sessionsById) {
7058
+ if (next.has(id) || completedSessionIds.has(id)) continue;
7059
+ if (existing.expiresAtMs > atMs) continue;
7060
+ if (existing.admitted >= existing.requestedCount) continue;
7061
+ if (!withinUploadGrace(existing, atMs)) continue;
7062
+ retainedById.set(id, existing);
7063
+ }
7064
+ for (const id of [...retainedById.keys()]) {
7065
+ if (next.has(id) || completedSessionIds.has(id)) retainedById.delete(id);
7066
+ }
6638
7067
  sessionsById.clear();
6639
7068
  for (const [id, session] of next) sessionsById.set(id, session);
7069
+ pruneRetained(atMs);
6640
7070
  markSessionsDirty();
6641
7071
  };
6642
7072
  const applyActivations = (activations) => {
@@ -6668,7 +7098,7 @@ var createExecutionRecordingCoordinator = (options) => {
6668
7098
  release: options.release,
6669
7099
  pid: process.pid,
6670
7100
  started_at: startedAt.toISOString(),
6671
- reported_mode: options.mode,
7101
+ reported_mode: mode,
6672
7102
  reported_settings: reportedRecorderSettings(options.recorderOptions),
6673
7103
  capabilities
6674
7104
  }
@@ -6804,7 +7234,7 @@ var createExecutionRecordingCoordinator = (options) => {
6804
7234
  });
6805
7235
  };
6806
7236
  const activate = (metadata, window) => {
6807
- if (closed || options.mode !== "adaptive") return;
7237
+ if (closed || mode !== "adaptive") return;
6808
7238
  const key = executionTypeKey(metadata);
6809
7239
  if (!key) return;
6810
7240
  const atMs = nowMs();
@@ -6839,11 +7269,15 @@ var createExecutionRecordingCoordinator = (options) => {
6839
7269
  };
6840
7270
  const consumeSession = (executionKeyValue, sessionId) => {
6841
7271
  const atMs = nowMs();
6842
- for (const session of sessionsById.values()) {
7272
+ pruneRetained(atMs);
7273
+ const candidates = [...sessionsById.values(), ...retainedById.values()];
7274
+ for (const session of candidates) {
6843
7275
  if (session.executionKey !== executionKeyValue) continue;
6844
7276
  if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
6845
- if (!sessionHasRoom(session, atMs)) continue;
7277
+ if (session.admitted >= session.requestedCount) continue;
7278
+ if (!withinUploadGrace(session, atMs)) continue;
6846
7279
  session.admitted += 1;
7280
+ if (session.admitted >= session.requestedCount) retainedById.delete(session.sessionId);
6847
7281
  markSessionsDirty();
6848
7282
  return sessionView(session);
6849
7283
  }
@@ -6924,6 +7358,7 @@ var createExecutionRecordingCoordinator = (options) => {
6924
7358
  closed = true;
6925
7359
  interruptWork();
6926
7360
  pending.clear();
7361
+ retainedById.clear();
6927
7362
  }
6928
7363
  }
6929
7364
  };
@@ -6932,7 +7367,7 @@ var createExecutionRecordingCoordinator = (options) => {
6932
7367
  // src/execution-recorder/bind-adaptive-recorder.ts
6933
7368
  var bindAdaptiveRecorder = (input) => {
6934
7369
  const options = input.executionRecorder;
6935
- const adaptiveEnabled = options?.adaptive?.enabled === true;
7370
+ const adaptiveEnabled = resolveExecutionRecordingMode(options) === "adaptive";
6936
7371
  const activation = resolveClientActivation({
6937
7372
  enabled: input.enabled,
6938
7373
  dsn: input.dsn,
@@ -6951,7 +7386,6 @@ var bindAdaptiveRecorder = (input) => {
6951
7386
  sdkVersion: input.sdkVersion,
6952
7387
  release: activation.release,
6953
7388
  recorderOptions: options,
6954
- mode: adaptiveEnabled ? "adaptive" : "full",
6955
7389
  fetch: input.fetch
6956
7390
  }) : void 0;
6957
7391
  const recorderHooks = {};
@@ -7347,11 +7781,26 @@ var createFunctionMetricsCollector = (options) => {
7347
7781
  note2(coverage, "dropped_queue_budget", discardedMarks2(dropped.series));
7348
7782
  }
7349
7783
  };
7784
+ const markedSeries = (table) => {
7785
+ const marked = /* @__PURE__ */ new Map();
7786
+ for (const [functionHandle, byExecution] of table) {
7787
+ const copied = /* @__PURE__ */ new Map();
7788
+ for (const [executionHandle, series] of byExecution) {
7789
+ if (seriesHasMarks2(series)) copied.set(executionHandle, series);
7790
+ }
7791
+ if (copied.size > 0) marked.set(functionHandle, copied);
7792
+ }
7793
+ return marked;
7794
+ };
7350
7795
  const closeMinute = (minute, table) => {
7351
7796
  active.delete(minute);
7352
7797
  activeSeries -= countSeries2(table);
7353
7798
  if (minute > lastClosedMinute) lastClosedMinute = minute;
7354
- appendQueue({ minute, series: table, bytes: tableBytes2(table) });
7799
+ const marked = markedSeries(table);
7800
+ const markedBytes = tableBytes2(marked);
7801
+ stateBytes -= tableBytes2(table) - markedBytes;
7802
+ if (stateBytes < 0) stateBytes = 0;
7803
+ appendQueue({ minute, series: marked, bytes: markedBytes });
7355
7804
  };
7356
7805
  const rotate = (currentMinute) => {
7357
7806
  for (const minute of [...active.keys()]) {
@@ -8237,12 +8686,205 @@ var createDynamicDurationSampleBuckets = (options) => {
8237
8686
  }
8238
8687
  };
8239
8688
  };
8689
+
8690
+ // src/create-rasputin-runtime.ts
8691
+ var publicExecution = (runtime) => ({
8692
+ createScope: (metadata) => {
8693
+ const scope = runtime.createScope(metadata);
8694
+ return {
8695
+ run: scope.run,
8696
+ observeError: scope.observeError,
8697
+ finish: scope.finish,
8698
+ captureInput: scope.captureInput
8699
+ };
8700
+ },
8701
+ trace: runtime.trace,
8702
+ getStats: runtime.getStats
8703
+ });
8704
+ var wrapClient = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
8705
+ }, policy, metrics, executionMetrics) => {
8706
+ const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
8707
+ };
8708
+ const manifestUpload = scheduleInstrumentationManifestUpload({
8709
+ ...manifest,
8710
+ deferStart: true
8711
+ });
8712
+ const execution = publicExecution(runtime);
8713
+ return {
8714
+ client: {
8715
+ ...client,
8716
+ execution,
8717
+ getStats: () => ({ ...client.getStats(), recorder: execution.getStats() }),
8718
+ verifyConfiguration: manifestUpload.verify,
8719
+ captureException: (error, context) => {
8720
+ const result = client.captureException(error, context);
8721
+ manifestUpload.flushSoon();
8722
+ return result;
8723
+ },
8724
+ flush: async (timeoutMs) => {
8725
+ const startedAt = Date.now();
8726
+ await client.flush(timeoutMs);
8727
+ if (timeoutMs === void 0) {
8728
+ await policy?.flush();
8729
+ await metrics?.exporter.flush();
8730
+ await executionMetrics?.exporter.flush();
8731
+ await manifestUpload.wait();
8732
+ return;
8733
+ }
8734
+ await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8735
+ await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8736
+ await executionMetrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8737
+ await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8738
+ },
8739
+ close: async () => {
8740
+ uninstallHandlers();
8741
+ uninstallRuntime();
8742
+ runtime.close();
8743
+ manifestUpload.disconnect();
8744
+ const startedAt = Date.now();
8745
+ await policy?.close();
8746
+ await releaseFunctionMetricsBindings(metrics);
8747
+ await releaseExecutionMetricsBindings(executionMetrics);
8748
+ await client.close();
8749
+ await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
8750
+ }
8751
+ },
8752
+ startManifestUpload: manifestUpload.start
8753
+ };
8754
+ };
8755
+ var inertHandle = (options) => {
8756
+ const runtime = createExecutionRecorder({ enabled: false });
8757
+ const { client } = wrapClient(createClient({ ...options, enabled: false }), runtime, false, {
8758
+ projectApiKey: options.projectApiKey,
8759
+ release: options.release,
8760
+ apiUrl: options.apiUrl,
8761
+ enabled: false,
8762
+ sourceRoot: options.sourceRoot,
8763
+ sourceRoots: options.sourceRoots,
8764
+ logSuccess: options.logSuccess
8765
+ });
8766
+ return {
8767
+ client,
8768
+ runtime,
8769
+ observeExecutions: false,
8770
+ startStartupWork: () => {
8771
+ }
8772
+ };
8773
+ };
8774
+ var createRasputinRuntime = (options, config) => {
8775
+ try {
8776
+ const enabled = isClientEnabled(options);
8777
+ const activation = resolveClientActivation2(options);
8778
+ const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
8779
+ const durationSampling = options.dynamicDurationSampling === true;
8780
+ const fetch = config.fetch;
8781
+ const metrics = activation.enabled ? bindFunctionMetrics({
8782
+ clientEnabled: true,
8783
+ environment: activation.environment,
8784
+ release: activation.release,
8785
+ ingestToken: activation.ingestToken,
8786
+ apiUrl: activation.apiUrl,
8787
+ fetch,
8788
+ sampledMeasurementFormat: durationSampling
8789
+ }) : void 0;
8790
+ const executionMetrics = activation.enabled ? bindExecutionMetrics({
8791
+ clientEnabled: true,
8792
+ environment: activation.environment,
8793
+ release: activation.release,
8794
+ ingestToken: activation.ingestToken,
8795
+ apiUrl: activation.apiUrl,
8796
+ fetch,
8797
+ sampledMeasurementFormat: durationSampling
8798
+ }) : void 0;
8799
+ const observeExecutions = recorderEnabled || Boolean(metrics) || Boolean(executionMetrics);
8800
+ const durationSampler = durationSampling && observeExecutions ? createDynamicDurationSampleBuckets({ nowMs: () => Date.now() }) : void 0;
8801
+ const { runtime, policy } = bindAdaptiveRecorder({
8802
+ executionRecorder: options.executionRecorder,
8803
+ recorderEnabled,
8804
+ dsn: options.dsn,
8805
+ projectApiKey: options.projectApiKey,
8806
+ apiUrl: options.apiUrl,
8807
+ release: options.release,
8808
+ environment: options.environment,
8809
+ enabled: options.enabled,
8810
+ sdkName: config.sdkName,
8811
+ sdkVersion: config.sdkVersion,
8812
+ fetch,
8813
+ functionMetrics: metrics?.collector,
8814
+ executionMetrics: executionMetrics?.collector,
8815
+ durationSampler
8816
+ });
8817
+ const client = createClient(options, {
8818
+ sdkVersion: config.sdkVersion,
8819
+ sdkName: config.sdkName,
8820
+ fetch,
8821
+ announceDeploy: false,
8822
+ installTransportSignalHandlers: config.installTransportSignalHandlers ?? options.installTransportSignalHandlers,
8823
+ redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
8824
+ resolveObservation: (observation) => runtime.getErrorState(observation)
8825
+ });
8826
+ if (enabled) {
8827
+ loadInstrumentationManifestIfPresent(
8828
+ options.instrumentationManifestPath ?? process.env.RASPUTIN_INSTRUMENTATION_MANIFEST ?? join(process.cwd(), ".rasputin", "instrumentation-manifest.json")
8829
+ );
8830
+ }
8831
+ let uninstallHandlers = () => {
8832
+ };
8833
+ const { client: wrappedClient, startManifestUpload } = wrapClient(
8834
+ client,
8835
+ runtime,
8836
+ observeExecutions,
8837
+ {
8838
+ projectApiKey: options.projectApiKey,
8839
+ release: options.release,
8840
+ apiUrl: options.apiUrl,
8841
+ fetch,
8842
+ enabled,
8843
+ sourceRoot: options.sourceRoot,
8844
+ sourceRoots: options.sourceRoots,
8845
+ logSuccess: options.logSuccess
8846
+ },
8847
+ () => uninstallHandlers(),
8848
+ policy,
8849
+ metrics,
8850
+ executionMetrics
8851
+ );
8852
+ const installProcessHandlers = (config.installGlobalHandlers ?? options.installGlobalHandlers) !== false;
8853
+ if (enabled && installProcessHandlers) {
8854
+ uninstallHandlers = installGlobalHandlers(wrappedClient);
8855
+ }
8856
+ let started = false;
8857
+ const startStartupWork = () => {
8858
+ if (started) return;
8859
+ started = true;
8860
+ startManifestUpload();
8861
+ if (!enabled || config.announceDeploy === false || !activation.enabled) return;
8862
+ scheduleAnnounceDeploy({
8863
+ deployUrl: resolveEndpointUrls5(activation.apiUrl).deployUrl,
8864
+ projectApiKey: activation.projectApiKey,
8865
+ environment: activation.environment,
8866
+ release: activation.release,
8867
+ fetch
8868
+ });
8869
+ };
8870
+ if (!config.deferStartupWork) startStartupWork();
8871
+ return {
8872
+ client: wrappedClient,
8873
+ runtime,
8874
+ observeExecutions,
8875
+ startStartupWork
8876
+ };
8877
+ } catch {
8878
+ return inertHandle(options);
8879
+ }
8880
+ };
8240
8881
  export {
8241
8882
  bindAdaptiveRecorder,
8242
8883
  bindExecutionMetrics,
8243
8884
  bindFunctionMetrics,
8244
8885
  createDynamicDurationSampleBuckets,
8245
8886
  createExecutionRecorder,
8887
+ createRasputinRuntime,
8246
8888
  inertErrorObservation,
8247
8889
  installAutomaticExecutionRuntime,
8248
8890
  installGlobalHandlers,