Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(deja): [2/5] per-request correlation substrate + ingress boundary + clock/id seams (#13286)
Uzair Khan4ded16aa9a9f
diff --git a/Cargo.lock b/Cargo.lockindex e7180fc508..6a718bd1fd 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2867,12 +2867,13 @@ checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"[[package]]name = "deja"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"dependencies = ["deja-context","deja-core","deja-derive","deja-runtime",+ "error-stack 0.4.1","serde","serde_json",]@@ -2880,7 +2881,7 @@ dependencies = [[[package]]name = "deja-context"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"dependencies = ["pin-project-lite",]@@ -2888,7 +2889,7 @@ dependencies = [[[package]]name = "deja-core"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"dependencies = ["serde","serde_json",@@ -2898,7 +2899,7 @@ dependencies = [[[package]]name = "deja-derive"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"dependencies = ["proc-macro2","quote",@@ -2908,7 +2909,7 @@ dependencies = [[[package]]name = "deja-runtime"version = "0.1.0"-source = "git+https://github.com/juspay/deja?rev=075a614324897b8b6a878af36d7ac243fbec5d33#075a614324897b8b6a878af36d7ac243fbec5d33"+source = "git+https://github.com/juspay/deja?rev=2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3#2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3"dependencies = ["async-trait","deja-context",@@ -3556,6 +3557,7 @@ dependencies = ["error-stack 0.4.1","hex","http 0.2.12",+ "http-body 1.0.1","http-body-util","hyper 0.14.32","hyper-proxy",@@ -3566,6 +3568,7 @@ dependencies = ["once_cell","open-feature","prost 0.14.3",+ "prost-reflect","prost-types 0.14.3","quick-xml","reqwest 0.11.27",@@ -3580,6 +3583,7 @@ dependencies = ["thiserror 1.0.69","time 0.3.41","tokio 1.48.0",+ "tokio-stream","tonic 0.14.5","tonic-prost","tonic-prost-build",@@ -7466,6 +7470,19 @@ dependencies = ["syn 2.0.101",]+[[package]]+name = "prost-reflect"+version = "0.16.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1"+dependencies = [+ "base64 0.22.1",+ "prost 0.14.3",+ "prost-types 0.14.3",+ "serde",+ "serde-value",+]+[[package]]name = "prost-types"version = "0.13.5"@@ -8403,6 +8420,7 @@ dependencies = ["deja-core","error-stack 0.4.1","gethostname",+ "hyperswitch_masking","opentelemetry","opentelemetry-aws","opentelemetry-otlp",diff --git a/config/config.example.toml b/config/config.example.tomlindex 278ce7c65a..0bac2f0b20 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -181,9 +181,6 @@ bg_metrics_collection_interval_in_secs = 15 # Interval for collectingmode = "disabled" # allowed values: "disabled", "record", "replay"run_id = "" # stable run identifier; empty lets the runtime choose a safe default-[deja.recording]-graph = "disabled" # allowed values: "disabled", "enabled" — execution-graph nodes on the recording stream-[deja.recording.kafka]brokers = []topic = "hyperswitch-deja-recording-events"@@ -199,7 +196,6 @@ lookup_dir = ""observed_sink = ""[deja.sampler]-enabled = falserecord_key = "deja_record"timeout_ms = 25fail_closed = truediff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 8f21cce125..3a55356489 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -166,47 +166,6 @@ use_xray_generator = false # Set this to true for AWSroute_to_trace = ["*/confirm"]bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread--[deja]-mode = "disabled"-run_id = ""--[deja.recording]-graph = "disabled"--[deja.recording.kafka]-brokers = []-topic = "hyperswitch-deja-recording-events"-client_id = "hyperswitch-deja-router"-acks = "all"-idempotence = true-linger = 5-message_timeout = 30000--[deja.replay]-source = ""-lookup_dir = ""-observed_sink = ""--[deja.sampler]-enabled = false-record_key = "deja_record"-timeout_ms = 25-fail_closed = true--[deja.identity]-pod_name_env = "POD_NAME"-git_sha_env = "VERGEN_GIT_SHA"-instance_id = ""-code_sha = ""--[deja.writer]-queue_capacity = 8192-batch_size = 500-flush_after_records = 500-flush_interval_ms = 1000-shutdown_flush_ms = 5000-[lock_settings]delay_between_retries_in_milliseconds = 500 # Delay between retries in millisecondsredis_lock_expiry_seconds = 180 # Seconds before the redis lock expiresdiff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex 97058ea745..74e208118b 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -1053,3 +1053,45 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list"28" = { description = "Retry after 6 days", recommended_action = "retry_after_6_days" }"29" = { description = "Retry after 8 days", recommended_action = "retry_after_8_days" }"30" = { description = "Retry after 10 days", recommended_action = "retry_after_10_days" }++# Deja (record/replay instrumentation) — this environment's posture, stated in+# its own file (single source: moved out of env_specific.toml so the README's+# cat-merge of the two files does not declare the [deja] tables twice). Integration_test is+# explicitly DISABLED.+# NOTE: deja config keys must match the typed DejaSettings struct exactly —+# unknown or misspelled keys are silently ignored, not rejected.+[deja]+mode = "disabled"+run_id = ""++[deja.recording.kafka]+brokers = []+topic = "hyperswitch-deja-recording-events"+client_id = "hyperswitch-deja-router"+acks = "all"+idempotence = true+linger = 5+message_timeout = 30000++[deja.replay]+source = ""+lookup_dir = ""+observed_sink = ""++[deja.sampler]+record_key = "deja_record"+timeout_ms = 25+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = ""+code_sha = ""++[deja.writer]+queue_capacity = 8192+batch_size = 500+flush_after_records = 500+flush_interval_ms = 1000+shutdown_flush_ms = 5000diff --git a/config/deployments/production.toml b/config/deployments/production.tomlindex b7b202f29c..8485b842f0 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -1061,3 +1061,45 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list"28" = { description = "Retry after 6 days", recommended_action = "retry_after_6_days" }"29" = { description = "Retry after 8 days", recommended_action = "retry_after_8_days" }"30" = { description = "Retry after 10 days", recommended_action = "retry_after_10_days" }++# Deja (record/replay instrumentation) — this environment's posture, stated in+# its own file (single source: moved out of env_specific.toml so the README's+# cat-merge of the two files does not declare the [deja] tables twice). Production is+# explicitly DISABLED.+# NOTE: deja config keys must match the typed DejaSettings struct exactly —+# unknown or misspelled keys are silently ignored, not rejected.+[deja]+mode = "disabled"+run_id = ""++[deja.recording.kafka]+brokers = []+topic = "hyperswitch-deja-recording-events"+client_id = "hyperswitch-deja-router"+acks = "all"+idempotence = true+linger = 5+message_timeout = 30000++[deja.replay]+source = ""+lookup_dir = ""+observed_sink = ""++[deja.sampler]+record_key = "deja_record"+timeout_ms = 25+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = ""+code_sha = ""++[deja.writer]+queue_capacity = 8192+batch_size = 500+flush_after_records = 500+flush_interval_ms = 1000+shutdown_flush_ms = 5000diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex db6bd46b09..2bdf11819e 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -1072,3 +1072,45 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list"28" = { description = "Retry after 6 days", recommended_action = "retry_after_6_days" }"29" = { description = "Retry after 8 days", recommended_action = "retry_after_8_days" }"30" = { description = "Retry after 10 days", recommended_action = "retry_after_10_days" }++# Deja (record/replay instrumentation) — this environment's posture, stated in+# its own file (single source: moved out of env_specific.toml so the README's+# cat-merge of the two files does not declare the [deja] tables twice). Sandbox is DISABLED until+# recording is enabled with the sink/boot layer (stack part 5).+# NOTE: deja config keys must match the typed DejaSettings struct exactly —+# unknown or misspelled keys are silently ignored, not rejected.+[deja]+mode = "disabled"+run_id = ""++[deja.recording.kafka]+brokers = []+topic = "hyperswitch-deja-recording-events"+client_id = "hyperswitch-deja-router"+acks = "all"+idempotence = true+linger = 5+message_timeout = 30000++[deja.replay]+source = ""+lookup_dir = ""+observed_sink = ""++[deja.sampler]+record_key = "deja_record"+timeout_ms = 25+fail_closed = true++[deja.identity]+pod_name_env = "POD_NAME"+git_sha_env = "VERGEN_GIT_SHA"+instance_id = ""+code_sha = ""++[deja.writer]+queue_capacity = 8192+batch_size = 500+flush_after_records = 500+flush_interval_ms = 1000+shutdown_flush_ms = 5000diff --git a/config/development.toml b/config/development.tomlindex 0172effb12..f7a12ba0f9 100644--- a/config/development.toml+++ b/config/development.toml@@ -19,9 +19,6 @@ bg_metrics_collection_interval_in_secs = 15mode = "disabled"run_id = ""-[deja.recording]-graph = "disabled"-[deja.recording.kafka]brokers = ["localhost:9092"]topic = "hyperswitch-deja-recording-events"@@ -37,7 +34,6 @@ lookup_dir = ""observed_sink = ""[deja.sampler]-enabled = falserecord_key = "deja_record"timeout_ms = 25fail_closed = truediff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex cc3cd98dc2..68f8b5cbb6 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -31,9 +31,6 @@ bg_metrics_collection_interval_in_secs = 15 # Interval for collemode = "disabled"run_id = ""-[deja.recording]-graph = "disabled"-[deja.recording.kafka]brokers = ["kafka0:29092"]topic = "hyperswitch-deja-recording-events"@@ -49,7 +46,6 @@ lookup_dir = ""observed_sink = ""[deja.sampler]-enabled = falserecord_key = "deja_record"timeout_ms = 25fail_closed = truediff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex d8e57a9b0e..3768ef4a39 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -11,10 +11,10 @@overrides = [][default-configs.deja_record]-value = true+value = falseschema = { type = "boolean" }-description = "Whether Deja request recording is enabled for matching request contexts (inert unless deja.sampler.enabled is set)"-change_reason = "Initial setup"+description = "Deja per-request recording decision — default SKIP (false). The deja_dimension cohort override (seeded by scripts/seed_superposition.sh) sets this true for the recordable endpoint bucket; /health and other probe traffic fall through to false."+change_reason = "Deja recording sampler"[dimensions.connector]@@ -71,6 +71,24 @@ schema = { type = "string" }description = "Business profile identifier"change_reason = "Initial setup"+# ── Deja recording sampler dimensions ────────────────────────────────────────+# The sampler passes the RAW request `path` + `method` as evaluation context;+# Superposition derives the `deja_dimension` cohort (a LOCAL_COHORT on `path`,+# seeded by scripts/seed_superposition.sh) and resolves `deja_record`. `path`+# must be a registered dimension so the server builds the cohort's dependency+# graph (path → deja_dimension).+[dimensions.path]+position = 10+schema = { type = "string" }+description = "HTTP request path (Deja recording sampler context; basis of the deja_dimension cohort)"+change_reason = "Deja recording sampler"++[dimensions.method]+position = 11+schema = { type = "string" }+description = "HTTP request method (Deja recording sampler context)"+change_reason = "Deja recording sampler"+[default-configs.requires_cvv]value = trueschema = { type = "boolean" }diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.tomlindex 73de9f0f36..5317a89d10 100644--- a/crates/common_utils/Cargo.toml+++ b/crates/common_utils/Cargo.toml@@ -31,7 +31,7 @@ base64-serde = "0.8.0"blake3 = { version = "1.8.2", features = ["serde"] }bytes = "1.10.1"diesel = "2.2.10"-deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }error-stack = "0.4.1"futures = { version = "0.3.31", optional = true }globset = "0.4.16"diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rsindex 36f912952b..f87a6ea4ef 100644--- a/crates/common_utils/src/crypto.rs+++ b/crates/common_utils/src/crypto.rs@@ -26,7 +26,32 @@ use crate::{};#[derive(Clone, Debug)]-struct NonceSequence(u128);+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]+struct NonceSequence(+ // deja: serialize the 96-bit nonce as its 16 big-endian BYTES, not a bare+ // u128. A nonce routinely exceeds u64::MAX, and `serde_json::Value::Number`+ // cannot hold a u128 beyond u64 range — so capturing it as a number FAILED+ // and the boundary recorded `null`, leaving nothing to substitute (the real+ // random nonce then ran on replay → divergent at-rest ciphertext). A byte+ // array is small-int-only, so it round-trips through serde_json and any+ // JSON event transport losslessly, exactly like `generate_aes256_key`.+ #[cfg_attr(feature = "deja", serde(with = "deja_nonce_bytes"))] u128,+);++/// deja: lossless u128 nonce (de)serialization via its 16 big-endian bytes.+#[cfg(feature = "deja")]+mod deja_nonce_bytes {+ use serde::{Deserialize, Deserializer, Serialize, Serializer};++ pub fn serialize<S: Serializer>(v: &u128, s: S) -> Result<S::Ok, S::Error> {+ v.to_be_bytes().serialize(s)+ }++ pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<u128, D::Error> {+ let bytes = <[u8; 16]>::deserialize(d)?;+ Ok(u128::from_be_bytes(bytes))+ }+}impl NonceSequence {/// Byte index at which sequence number starts in a 16-byte (128-bit) sequence.@@ -35,6 +60,21 @@ impl NonceSequence {const SEQUENCE_NUMBER_START_INDEX: usize = 4;/// Generate a random nonce sequence.+ //+ // deja: the AEAD nonce is the single source of ciphertext non-determinism.+ // Recording it (Ok-only; the ring error type is non-serializable) and+ // replaying it in call order makes `encode_message` reproduce byte-identical+ // ciphertext for the same key+plaintext, so encrypted DB columns and HTTP+ // bodies match the recording exactly. Real AES still runs; only the random+ // nonce is substituted.+ #[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils::crypto",+ operation = "GcmAes256::nonce",+ codec = ResultOkCodec,+ )+ )]fn new() -> Result<Self, ring::error::Unspecified> {use ring::rand::{SecureRandom, SystemRandom};@@ -608,6 +648,14 @@ impl EncodeMessage for TripleDesEde3CBC {/// Generate a random string using a cryptographically secure pseudo-random number generator/// (CSPRNG). Typically used for generating (readable) keys and passwords.#[inline]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils::crypto",+ operation = "generate_cryptographically_secure_random_string",+ codec = SerdeCodec,+ )+)]pub fn generate_cryptographically_secure_random_string(length: usize) -> String {use rand::distributions::DistString;diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rsindex 215c73d8f0..8cd8809251 100644--- a/crates/common_utils/src/lib.rs+++ b/crates/common_utils/src/lib.rs@@ -72,6 +72,11 @@ pub mod date_time {}/// Create a new [`PrimitiveDateTime`] with the current date and time in UTC.+ #[cfg_attr(feature = "deja", track_caller)]+ #[cfg_attr(+ feature = "deja",+ deja::time(component = "common_utils", operation = "date_time::now", codec = SerdeCodec,)+ )]pub fn now() -> PrimitiveDateTime {let utc_date_time = OffsetDateTime::now_utc();PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())@@ -83,6 +88,15 @@ pub mod date_time {}/// Return the UNIX timestamp of the current date and time in UTC+ #[cfg_attr(feature = "deja", track_caller)]+ #[cfg_attr(+ feature = "deja",+ deja::time(+ component = "common_utils",+ operation = "date_time::now_unix_timestamp",+ codec = SerdeCodec,+ )+ )]pub fn now_unix_timestamp() -> i64 {OffsetDateTime::now_utc().unix_timestamp()}@@ -107,16 +121,36 @@ pub mod date_time {}/// Return the current date and time in UTC with the format [year]-[month]-[day]T[hour]:[minute]:[second].mmmZ Eg: 2023-02-15T13:33:18.898Z+ #[cfg_attr(feature = "deja", track_caller)]+ #[cfg_attr(+ feature = "deja",+ deja::time(+ component = "common_utils",+ operation = "date_time::date_as_yyyymmddthhmmssmmmz",+ )+ )]pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> {const ISO_CONFIG: EncodedConfig = Config::DEFAULT.set_time_precision(TimePrecision::Second {decimal_digits: NonZeroU8::new(3),}).encode();- now().assume_utc().format(&Iso8601::<ISO_CONFIG>)+ // Read the clock directly rather than via `now()`: both are instrumented seams, and+ // nesting them would record a redundant inner event for every outer call.+ convert_to_pdt(OffsetDateTime::now_utc())+ .assume_utc()+ .format(&Iso8601::<ISO_CONFIG>)}/// Return the current date and time in UTC formatted as "ddd, DD MMM YYYY HH:mm:ss GMT".+ #[cfg_attr(feature = "deja", track_caller)]+ #[cfg_attr(+ feature = "deja",+ deja::time(+ component = "common_utils",+ operation = "date_time::now_rfc7231_http_date",+ )+ )]pub fn now_rfc7231_http_date() -> Result<String, time::error::Format> {let now_utc = OffsetDateTime::now_utc();// Desired format: ddd, DD MMM YYYY HH:mm:ss GMT@@ -224,11 +258,17 @@ pub mod date_time {/// Generate a nanoid with the given prefix and length#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(component = "common_utils", operation = "generate_id", codec = SerdeCodec,)+)]pub fn generate_id(length: usize, prefix: &str) -> String {format!("{}_{}", prefix, nanoid::nanoid!(length, &consts::ALPHABETS))}/// Generate a ReferenceId with the default length with the given prefix+#[cfg_attr(feature = "deja", track_caller)]fn generate_ref_id_with_default_length<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(prefix: &str,) -> id_type::LengthId<MAX_LENGTH, MIN_LENGTH> {@@ -236,6 +276,7 @@ fn generate_ref_id_with_default_length<const MAX_LENGTH: u8, const MIN_LENGTH: u}/// Generate a customer id with default length, with prefix as `cus`+#[cfg_attr(feature = "deja", track_caller)]pub fn generate_customer_id_of_default_length() -> id_type::CustomerId {use id_type::GenerateId;@@ -243,6 +284,7 @@ pub fn generate_customer_id_of_default_length() -> id_type::CustomerId {}/// Generate a organization id with default length, with prefix as `org`+#[cfg_attr(feature = "deja", track_caller)]pub fn generate_organization_id_of_default_length() -> id_type::OrganizationId {use id_type::GenerateId;@@ -250,6 +292,7 @@ pub fn generate_organization_id_of_default_length() -> id_type::OrganizationId {}/// Generate a profile id with default length, with prefix as `pro`+#[cfg_attr(feature = "deja", track_caller)]pub fn generate_profile_id_of_default_length() -> id_type::ProfileId {use id_type::GenerateId;@@ -257,12 +300,14 @@ pub fn generate_profile_id_of_default_length() -> id_type::ProfileId {}/// Generate a routing id with default length, with prefix as `routing`+#[cfg_attr(feature = "deja", track_caller)]pub fn generate_routing_id_of_default_length() -> id_type::RoutingId {use id_type::GenerateId;id_type::RoutingId::generate()}/// Generate a merchant_connector_account id with default length, with prefix as `mca`+#[cfg_attr(feature = "deja", track_caller)]pub fn generate_merchant_connector_account_id_of_default_length() -> id_type::MerchantConnectorAccountId {use id_type::GenerateId;@@ -271,6 +316,7 @@ pub fn generate_merchant_connector_account_id_of_default_length(}/// Generate a profile_acquirer id with default length, with prefix as `mer_acq`+#[cfg_attr(feature = "deja", track_caller)]pub fn generate_profile_acquirer_id_of_default_length() -> id_type::ProfileAcquirerId {use id_type::GenerateId;@@ -279,6 +325,15 @@ pub fn generate_profile_acquirer_id_of_default_length() -> id_type::ProfileAcqui/// Generate a nanoid with the given prefix and a default length#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_id_with_default_len",+ codec = SerdeCodec,+ )+)]pub fn generate_id_with_default_len(prefix: &str) -> String {let len: usize = consts::ID_LENGTH;format!("{}_{}", prefix, nanoid::nanoid!(len, &consts::ALPHABETS))@@ -286,18 +341,41 @@ pub fn generate_id_with_default_len(prefix: &str) -> String {/// Generate a time-ordered (time-sortable) unique identifier using the current time#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_time_ordered_id",+ codec = SerdeCodec,+ )+)]pub fn generate_time_ordered_id(prefix: &str) -> String {format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple())}/// Generate a time-ordered (time-sortable) unique identifier using the current time without prefix#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "common_utils",+ operation = "generate_time_ordered_id_without_prefix",+ codec = SerdeCodec,+ )+)]pub fn generate_time_ordered_id_without_prefix() -> String {uuid::Uuid::now_v7().as_simple().to_string()}/// Generate a nanoid with the specified length#[inline]+#[cfg_attr(feature = "deja", track_caller)]+#[cfg_attr(+ feature = "deja",+ deja::id(component = "common_utils", operation = "generate_id_with_len", codec = SerdeCodec,)+)]pub fn generate_id_with_len(length: usize) -> String {nanoid::nanoid!(length, &consts::ALPHABETS)}diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.tomlindex ff43dc73f0..8e7fa3f53d 100644--- a/crates/diesel_models/Cargo.toml+++ b/crates/diesel_models/Cargo.toml@@ -33,7 +33,7 @@ common_types = { version = "0.1.0", path = "../common_types" }hyperswitch_masking = "0.0.1"router_derive = { version = "0.1.0", path = "../router_derive" }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }-deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false, features = ["error-stack"] }[lints]workspace = truediff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rsindex 99d1fdd887..7de95d96a2 100644--- a/crates/diesel_models/src/business_profile.rs+++ b/crates/diesel_models/src/business_profile.rs@@ -19,6 +19,7 @@ use crate::schema_v2::business_profile;/// fields read / written will be interchanged#[cfg(feature = "v1")]#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))]pub struct Profile {pub profile_id: common_utils::id_type::ProfileId,@@ -233,6 +234,7 @@ pub struct ProfileUpdateInternal {/// fields read / written will be interchanged#[cfg(feature = "v2")]#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = business_profile, primary_key(id), check_for_backend(diesel::pg::Pg))]pub struct Profile {pub merchant_id: common_utils::id_type::MerchantId,diff --git a/crates/diesel_models/src/callback_mapper.rs b/crates/diesel_models/src/callback_mapper.rsindex f9a8fa47c8..04ffd21c53 100644--- a/crates/diesel_models/src/callback_mapper.rs+++ b/crates/diesel_models/src/callback_mapper.rs@@ -5,6 +5,7 @@ use diesel::{Identifiable, Insertable, Queryable, Selectable};use crate::schema::callback_mapper;#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))]pub struct CallbackMapper {pub id: String,diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rsindex f60db1e9fb..a006b835f0 100644--- a/crates/diesel_models/src/dynamic_routing_stats.rs+++ b/crates/diesel_models/src/dynamic_routing_stats.rs@@ -24,6 +24,7 @@ pub struct DynamicRoutingStatsNew {}#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = dynamic_routing_stats, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]pub struct DynamicRoutingStats {pub payment_id: common_utils::id_type::PaymentId,diff --git a/crates/diesel_models/src/errors.rs b/crates/diesel_models/src/errors.rsindex f074ef36f2..ac5e2db842 100644--- a/crates/diesel_models/src/errors.rs+++ b/crates/diesel_models/src/errors.rs@@ -1,3 +1,7 @@+// Deja replay reconstructs a recorded DB error as the SAME typed context the+// recording threw ("recording threw ⇒ replay throws"); the serde derives give+// the fieldless variants a lossless wire form (the bare variant-name string).+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[derive(Copy, Clone, Debug, thiserror::Error)]pub enum DatabaseError {#[error("An error occurred when obtaining database connection")]diff --git a/crates/diesel_models/src/gsm.rs b/crates/diesel_models/src/gsm.rsindex 3a6a3bf783..ca43cb124e 100644--- a/crates/diesel_models/src/gsm.rs+++ b/crates/diesel_models/src/gsm.rs@@ -20,6 +20,9 @@ use crate::schema::gateway_status_map;Selectable,serde::Serialize,)]+// Deja replay reconstructs recorded rows, so it also needs Deserialize; base+// keeps its unconditional Serialize so feature-off is byte-identical.+#[cfg_attr(feature = "deja", derive(serde::Deserialize))]#[diesel(table_name = gateway_status_map, primary_key(connector, flow, sub_flow, code, message), check_for_backend(diesel::pg::Pg))]pub struct GatewayStatusMap {pub connector: String,diff --git a/crates/diesel_models/src/locker_mock_up.rs b/crates/diesel_models/src/locker_mock_up.rsindex 99e0b2d098..d5ae4586b0 100644--- a/crates/diesel_models/src/locker_mock_up.rs+++ b/crates/diesel_models/src/locker_mock_up.rs@@ -3,6 +3,9 @@ use diesel::{Identifiable, Insertable, Queryable, Selectable};use crate::schema::locker_mock_up;#[derive(Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq)]+// deja-only: this row embeds raw card_number/card_cvc, so the serde impls that+// the db boundary needs for record/replay must never exist in default builds.+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = locker_mock_up, primary_key(card_id), check_for_backend(diesel::pg::Pg))]pub struct LockerMockUp {pub card_id: String,diff --git a/crates/diesel_models/src/query/authentication.rs b/crates/diesel_models/src/query/authentication.rsindex 6af586aba2..bb2edbb24a 100644--- a/crates/diesel_models/src/query/authentication.rs+++ b/crates/diesel_models/src/query/authentication.rs@@ -10,7 +10,7 @@ use crate::{impl AuthenticationNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> {- generics::generic_insert(conn, self).await+ Box::pin(generics::generic_insert(conn, self)).await}pub async fn generate_drainer_insert_query(diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rsindex 3617155fbb..172590888c 100644--- a/crates/diesel_models/src/query/business_profile.rs+++ b/crates/diesel_models/src/query/business_profile.rs@@ -12,7 +12,7 @@ use crate::{impl ProfileNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Profile> {- generics::generic_insert(conn, self).await+ Box::pin(generics::generic_insert(conn, self)).await}}@@ -22,11 +22,12 @@ impl Profile {conn: &PgPooledConn,business_profile: ProfileUpdateInternal,) -> StorageResult<Self> {- match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(- conn,- self.get_id().to_owned(),- business_profile,- )+ match Box::pin(generics::generic_update_by_id::<+ <Self as HasTable>::Table,+ _,+ _,+ _,+ >(conn, self.get_id().to_owned(), business_profile)).await{Err(error) => match error.current_context() {diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rsindex d809f3cb19..aba801f3ad 100644--- a/crates/diesel_models/src/query/generics.rs+++ b/crates/diesel_models/src/query/generics.rs@@ -20,6 +20,9 @@ use diesel::{Expression, ExpressionMethods, Insertable, QueryDsl, QuerySource, Table,};use error_stack::{report, ResultExt};+#[cfg(feature = "deja")]+use hyperswitch_masking::PeekInterface;+use hyperswitch_masking::Secret;use router_env::logger;use crate::{errors, query::utils::GetPrimaryKey, PgPooledConn, StorageResult};@@ -63,6 +66,430 @@ pub mod db_metrics {use db_metrics::*;+fn table_name<T>() -> &'static str {+ std::any::type_name::<T>()+ .rsplit("::")+ .nth(1)+ .unwrap_or("unknown")+}++/// Bound alias for generic query results. Recording/replaying a db row needs+/// serde only when the `deja` feature is compiled in; default builds must not+/// force `Serialize`/`Deserialize` onto every row type (some rows — e.g.+/// `LockerMockUp` with raw card data — deliberately have no serde impls+/// outside deja builds).+#[cfg(feature = "deja")]+pub trait DejaQueryResult: Debug + serde::Serialize + serde::de::DeserializeOwned {}+#[cfg(feature = "deja")]+impl<T: Debug + serde::Serialize + serde::de::DeserializeOwned> DejaQueryResult for T {}+#[cfg(not(feature = "deja"))]+pub trait DejaQueryResult {}+#[cfg(not(feature = "deja"))]+impl<T> DejaQueryResult for T {}++// ---------------------------------------------------------------------------+// Deja boundary executors+// ---------------------------------------------------------------------------+// Each `generic_*` helper is split builder/executor: the PUBLIC builder keeps+// its exact pre-fold signature, constructs the diesel query plus its+// metrics-tracked future, and hands the capture-worthy values — `table`,+// `sql`, `inputs` — to a small PRIVATE executor whose real fn args ARE the+// boundary's args. The `#[deja::boundary]` attribute owns record/replay via+// the shared dispatch seam:+// - `codec = ResultCodec<_, DatabaseError>` reconstructs the typed result on+// substitution — a recording that threw replays the SAME `DatabaseError`+// context ("recording threw ⇒ replay throws").+// - `result = deja::db::recorded_output(..)` is the explicit state-key /+// row-image / binds-read-key producer (the recorder itself never infers).+// - `state_read`/`state_write`/`state_touch` declare the query-fingerprint+// fallback key.+// - `replay` is the per-op routing knob: writes and row-returning reads+// `Execute` (run live against the per-correlation schema and+// shadow-compare), the read-only scalar `count` `Substitute`s (a count is+// a non-seedable scalar; re-running it against a partially-seeded schema+// would only measure seed incompleteness).+// `sql`/`inputs` are `Secret`-wrapped so their `Debug` output is redacted+// (bind values / changeset debug strings can carry PII); the deja attribute+// exprs `.peek()` them at the boundary, and the tape keeps full fidelity.+// Feature-off, every executor is a plain async fn passthrough.++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_insert",+ op = Create,+ replay = Execute,+ effect = Db,+ returns = Value,+ codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ args = deja::db::args("generic_insert", table, sql.peek(), inputs.peek()),+ state_write = deja::db::query_state_key("generic_insert", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Write, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_insert<F, R>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<R>+where+ F: std::future::Future<Output = Result<R, DieselError>> + Send,+ R: Send + 'static + DejaQueryResult,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ match fut.await {+ Ok(value) => Ok(value),+ Err(err) => match err {+ DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => {+ Err(report!(err)).change_context(errors::DatabaseError::UniqueViolation)+ }+ _ => Err(report!(err)).change_context(errors::DatabaseError::Others),+ },+ }+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_update",+ op = Update,+ replay = Execute,+ effect = Db,+ returns = Count,+ codec = deja::codec::ResultCodec::<usize, errors::DatabaseError>,+ args = deja::db::args("generic_update", table, sql.peek(), inputs.peek()),+ state_touch = deja::db::query_state_key("generic_update", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_update<F>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<usize>+where+ F: std::future::Future<Output = Result<usize, DieselError>> + Send,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ fut.await.change_context(errors::DatabaseError::Others)+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_update_with_results",+ op = Update,+ replay = Execute,+ effect = Db,+ returns = Rows,+ codec = deja::codec::ResultCodec::<Vec<R>, errors::DatabaseError>,+ args = deja::db::args("generic_update_with_results", table, sql.peek(), inputs.peek()),+ state_touch = deja::db::query_state_key("generic_update_with_results", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_update_with_results<F, R>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<Vec<R>>+where+ F: std::future::Future<Output = Result<Vec<R>, DieselError>> + Send,+ R: Send + 'static + DejaQueryResult,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ match fut.await {+ Ok(result) => Ok(result),+ Err(DieselError::QueryBuilderError(_)) => {+ Err(report!(errors::DatabaseError::NoFieldsToUpdate))+ }+ Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)),+ Err(error) => Err(error).change_context(errors::DatabaseError::Others),+ }+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_update_by_id",+ op = Update,+ replay = Execute,+ effect = Db,+ returns = Value,+ codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ args = deja::db::args("generic_update_by_id", table, sql.peek(), inputs.peek()),+ state_touch = deja::db::query_state_key("generic_update_by_id", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_update_by_id<F, R>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<R>+where+ F: std::future::Future<Output = Result<R, DieselError>> + Send,+ R: Send + 'static + DejaQueryResult,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ match fut.await {+ Ok(result) => Ok(result),+ Err(DieselError::QueryBuilderError(_)) => {+ Err(report!(errors::DatabaseError::NoFieldsToUpdate))+ }+ Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)),+ Err(error) => Err(error).change_context(errors::DatabaseError::Others),+ }+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_delete",+ op = Delete,+ replay = Execute,+ effect = Db,+ returns = Bool,+ codec = deja::codec::ResultCodec::<bool, errors::DatabaseError>,+ args = deja::db::args("generic_delete", table, sql.peek(), inputs.peek()),+ state_touch = deja::db::query_state_key("generic_delete", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_delete<F>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<bool>+where+ F: std::future::Future<Output = Result<usize, DieselError>> + Send,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ fut.await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error while deleting")+ .and_then(|result| match result {+ n if n > 0 => {+ logger::debug!("{n} records deleted");+ Ok(true)+ }+ 0 => {+ Err(report!(errors::DatabaseError::NotFound).attach_printable("No records deleted"))+ }+ _ => Ok(true), // n is usize, rustc requires this for exhaustive check+ })+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_delete_one_with_result",+ op = Delete,+ replay = Execute,+ effect = Db,+ returns = Value,+ codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ args = deja::db::args("generic_delete_one_with_result", table, sql.peek(), inputs.peek()),+ state_touch = deja::db::query_state_key("generic_delete_one_with_result", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Touch, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_delete_one_with_result<F, R>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<R>+where+ F: std::future::Future<Output = Result<Vec<R>, DieselError>> + Send,+ R: Send + Clone + 'static + DejaQueryResult,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ fut.await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error while deleting")+ .and_then(|result| {+ result.first().cloned().ok_or_else(|| {+ report!(errors::DatabaseError::NotFound)+ .attach_printable("Object to be deleted does not exist")+ })+ })+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_find_by_id_core",+ op = Read,+ replay = Execute,+ effect = Db,+ returns = Value,+ codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ args = deja::db::args("generic_find_by_id_core", table, sql.peek(), inputs.peek()),+ state_read = deja::db::query_state_key("generic_find_by_id_core", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_find_by_id<F, R>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<R>+where+ F: std::future::Future<Output = Result<R, DieselError>> + Send,+ R: Send + 'static + DejaQueryResult,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ match fut.await {+ Ok(value) => Ok(value),+ Err(err) => match err {+ DieselError::NotFound => {+ Err(report!(err)).change_context(errors::DatabaseError::NotFound)+ }+ _ => Err(report!(err)).change_context(errors::DatabaseError::Others),+ },+ }+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_find_one_core",+ op = Read,+ replay = Execute,+ effect = Db,+ returns = Value,+ codec = deja::codec::ResultCodec::<R, errors::DatabaseError>,+ args = deja::db::args("generic_find_one_core", table, sql.peek(), inputs.peek()),+ state_read = deja::db::query_state_key("generic_find_one_core", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_find_one<F, R>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<R>+where+ F: std::future::Future<Output = Result<R, DieselError>> + Send,+ R: Send + 'static + DejaQueryResult,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ fut.await+ .map_err(|err| match err {+ DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound),+ _ => report!(err).change_context(errors::DatabaseError::Others),+ })+ .attach_printable("Error finding record by predicate")+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_filter",+ op = Read,+ replay = Execute,+ effect = Db,+ returns = Rows,+ codec = deja::codec::ResultCodec::<Vec<R>, errors::DatabaseError>,+ args = deja::db::args("generic_filter", table, sql.peek(), inputs.peek()),+ state_read = deja::db::query_state_key("generic_filter", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_filter<F, R>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<Vec<R>>+where+ F: std::future::Future<Output = Result<Vec<R>, DieselError>> + Send,+ R: Send + 'static + DejaQueryResult,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ fut.await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error filtering records by predicate")+}++#[cfg_attr(+ feature = "deja",+ deja::boundary(+ boundary = "db",+ component = "diesel_models::query::generics",+ operation = "generic_count",+ op = Read,+ replay = Substitute,+ effect = Db,+ returns = Count,+ codec = deja::codec::ResultCodec::<usize, errors::DatabaseError>,+ args = deja::db::args("generic_count", table, sql.peek(), inputs.peek()),+ state_read = deja::db::query_state_key("generic_count", table, sql.peek(), inputs.peek()),+ result = deja::db::recorded_output(deja::db::StateAxis::Read, table, sql.peek(), __deja_result),+ )+)]+async fn execute_generic_count<F>(+ fut: F,+ table: &'static str,+ sql: Secret<String>,+ inputs: Secret<serde_json::Value>,+) -> StorageResult<usize>+where+ F: std::future::Future<Output = Result<i64, DieselError>> + Send,+{+ #[cfg(not(feature = "deja"))]+ let _ = (&table, &sql, &inputs);+ let count_i64: i64 = fut+ .await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error counting records by predicate")?;++ let count_usize = usize::try_from(count_i64).map_err(|_| {+ report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize")+ })?;++ Ok(count_usize)+}++// ---------------------------------------------------------------------------+// Public builders (signatures identical to pre-fold — zero call-site changes)+// ---------------------------------------------------------------------------+pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R>whereT: HasTable<Table = T> + Table + 'static + Debug,@@ -71,24 +498,24 @@ where<V as Insertable<T>>::Values: CanInsertInSingleQuery<Pg> + QueryFragment<Pg> + 'static,InsertStatement<T, <V as Insertable<T>>::Values>:AsQuery + LoadQuery<'static, PgConnection, R> + Send,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{let debug_values = format!("{values:?}");let query = diesel::insert_into(<T as HasTable>::table()).values(values);- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- match track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert)- .await- {- Ok(value) => Ok(value),- Err(err) => match err {- DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => {- Err(report!(err)).change_context(errors::DatabaseError::UniqueViolation)- }- _ => Err(report!(err)).change_context(errors::DatabaseError::Others),- },- }+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "values": { "debug": debug_values.as_str() },+ });++ execute_generic_insert(+ track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),+ )+ .await.attach_printable_lazy(|| format!("Error while inserting {debug_values}"))}@@ -110,12 +537,21 @@ wherelet debug_values = format!("{values:?}");let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update)- .await- .change_context(errors::DatabaseError::Others)- .attach_printable_lazy(|| format!("Error while updating {debug_values}"))+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "values": { "debug": debug_values.as_str() },+ "predicate": { "type": std::any::type_name::<P>() },+ });++ execute_generic_update(+ track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),+ )+ .await+ .attach_printable_lazy(|| format!("Error while updating {debug_values}"))}pub async fn generic_update_with_results<T, V, P, R>(@@ -132,7 +568,7 @@ where<Filter<T, P> as IntoUpdateTarget>::WhereClause,<V as AsChangeset>::Changeset,>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,// For cloning query (UpdateStatement)<Filter<T, P> as HasTable>::Table: Clone,@@ -143,27 +579,24 @@ wherelet debug_values = format!("{values:?}");let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);-- match track_database_call::<T, _, _>(- query.to_owned().get_results_async(conn),- DatabaseOperation::UpdateWithResults,+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "values": { "debug": debug_values.as_str() },+ "predicate": { "type": std::any::type_name::<P>() },+ });++ execute_generic_update_with_results(+ track_database_call::<T, _, _>(+ query.to_owned().get_results_async(conn),+ DatabaseOperation::UpdateWithResults,+ ),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),).await- {- Ok(result) => {- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());- Ok(result)- }- Err(DieselError::QueryBuilderError(_)) => {- Err(report!(errors::DatabaseError::NoFieldsToUpdate))- .attach_printable_lazy(|| format!("Error while updating {debug_values}"))- }- Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))- .attach_printable_lazy(|| format!("Error while updating {debug_values}")),- Err(error) => Err(error)- .change_context(errors::DatabaseError::Others)- .attach_printable_lazy(|| format!("Error while updating {debug_values}")),- }+ .attach_printable_lazy(|| format!("Error while updating {debug_values}"))}pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>(@@ -180,7 +613,7 @@ where<Filter<T, P> as IntoUpdateTarget>::WhereClause,<V as AsChangeset>::Changeset,>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,// For cloning query (UpdateStatement)<Filter<T, P> as HasTable>::Table: Clone,@@ -218,7 +651,7 @@ where>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,Find<T, Pk>: LimitDsl,Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,Pk: Clone + Debug,// For cloning query (UpdateStatement)@@ -230,27 +663,24 @@ wherelet debug_values = format!("{values:?}");let query = diesel::update(<T as HasTable>::table().find(id.to_owned())).set(values);-- match track_database_call::<T, _, _>(- query.to_owned().get_result_async(conn),- DatabaseOperation::UpdateOne,+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "id": { "debug": format!("{id:?}") },+ "values": { "debug": debug_values.as_str() },+ });++ execute_generic_update_by_id(+ track_database_call::<T, _, _>(+ query.to_owned().get_result_async(conn),+ DatabaseOperation::UpdateOne,+ ),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),).await- {- Ok(result) => {- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());- Ok(result)- }- Err(DieselError::QueryBuilderError(_)) => {- Err(report!(errors::DatabaseError::NoFieldsToUpdate))- .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))- }- Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))- .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),- Err(error) => Err(error)- .change_context(errors::DatabaseError::Others)- .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),- }+ .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))}pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool>@@ -263,22 +693,19 @@ where>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,{let query = diesel::delete(<T as HasTable>::table().filter(predicate));- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete)- .await- .change_context(errors::DatabaseError::Others)- .attach_printable("Error while deleting")- .and_then(|result| match result {- n if n > 0 => {- logger::debug!("{n} records deleted");- Ok(true)- }- 0 => {- Err(report!(errors::DatabaseError::NotFound).attach_printable("No records deleted"))- }- _ => Ok(true), // n is usize, rustc requires this for exhaustive check- })+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "predicate": { "type": std::any::type_name::<P>() },+ });++ execute_generic_delete(+ track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),+ )+ .await}pub async fn generic_delete_one_with_result<T, P, R>(@@ -292,24 +719,25 @@ where<Filter<T, P> as HasTable>::Table,<Filter<T, P> as IntoUpdateTarget>::WhereClause,>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,- R: Send + Clone + 'static,+ R: Send + Clone + 'static + DejaQueryResult,{let query = diesel::delete(<T as HasTable>::table().filter(predicate));- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- track_database_call::<T, _, _>(- query.get_results_async(conn),- DatabaseOperation::DeleteWithResult,+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "predicate": { "type": std::any::type_name::<P>() },+ });++ execute_generic_delete_one_with_result(+ track_database_call::<T, _, _>(+ query.get_results_async(conn),+ DatabaseOperation::DeleteWithResult,+ ),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),).await- .change_context(errors::DatabaseError::Others)- .attach_printable("Error while deleting")- .and_then(|result| {- result.first().cloned().ok_or_else(|| {- report!(errors::DatabaseError::NotFound)- .attach_printable("Object to be deleted does not exist")- })- })}async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>@@ -318,21 +746,22 @@ whereFind<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,Pk: Clone + Debug,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{let query = <T as HasTable>::table().find(id.to_owned());- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- match track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne).await- {- Ok(value) => Ok(value),- Err(err) => match err {- DieselError::NotFound => {- Err(report!(err)).change_context(errors::DatabaseError::NotFound)- }- _ => Err(report!(err)).change_context(errors::DatabaseError::Others),- },- }+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "id": { "debug": format!("{id:?}") },+ });++ execute_generic_find_by_id(+ track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),+ )+ .await.attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}"))}@@ -342,7 +771,7 @@ whereFind<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,Pk: Clone + Debug,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{generic_find_by_id_core::<T, _, _>(conn, id).await}@@ -357,7 +786,7 @@ whereFind<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,Pk: Clone + Debug,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await)}@@ -366,25 +795,29 @@ async fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StwhereT: FilterDsl<P> + HasTable<Table = T> + Table + 'static,Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{let query = <T as HasTable>::table().filter(predicate);- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne)- .await- .map_err(|err| match err {- DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound),- _ => report!(err).change_context(errors::DatabaseError::Others),- })- .attach_printable("Error finding record by predicate")+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "predicate": { "type": std::any::type_name::<P>() },+ });++ execute_generic_find_one(+ track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),+ )+ .await}pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>whereT: FilterDsl<P> + HasTable<Table = T> + Table + 'static,Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{generic_find_one_core::<T, _, _>(conn, predicate).await}@@ -396,7 +829,7 @@ pub async fn generic_find_one_optional<T, P, R>(whereT: FilterDsl<P> + HasTable<Table = T> + Table + 'static,Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await)}@@ -419,7 +852,7 @@ where+ QueryFragment<Pg>+ Send,O: Expression,- R: Send + 'static,+ R: Send + 'static + DejaQueryResult,{let mut query = T::table().into_boxed();query = query@@ -437,12 +870,22 @@ wherequery = query.order(order);}- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)- .await- .change_context(errors::DatabaseError::Others)- .attach_printable("Error filtering records by predicate")+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "predicate": { "type": std::any::type_name::<P>() },+ "limit": limit,+ "offset": offset,+ "order": { "type": std::any::type_name::<O>() },+ });++ execute_generic_filter(+ track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),+ )+ .await}pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize>@@ -456,19 +899,19 @@ where.filter(predicate).select(count_star());- logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());-- let count_i64: i64 =- track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count)- .await- .change_context(errors::DatabaseError::Others)- .attach_printable("Error counting records by predicate")?;-- let count_usize = usize::try_from(count_i64).map_err(|_| {- report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize")- })?;-- Ok(count_usize)+ let sql = debug_query::<Pg, _>(&query).to_string();+ logger::debug!(query = %sql);+ let inputs = serde_json::json!({+ "predicate": { "type": std::any::type_name::<P>() },+ });++ execute_generic_count(+ track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count),+ table_name::<T>(),+ Secret::new(sql),+ Secret::new(inputs),+ )+ .await}fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> {diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rsindex e2a2ed26ac..061763a5b4 100644--- a/crates/diesel_models/src/query/payment_attempt.rs+++ b/crates/diesel_models/src/query/payment_attempt.rs@@ -27,7 +27,7 @@ use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIimpl PaymentAttemptNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentAttempt> {- generics::generic_insert(conn, self).await+ Box::pin(generics::generic_insert(conn, self)).await}pub async fn generate_drainer_insert_query(@@ -45,7 +45,7 @@ impl PaymentAttempt {conn: &PgPooledConn,payment_attempt: PaymentAttemptUpdate,) -> StorageResult<Self> {- match generics::generic_update_with_unique_predicate_get_result::<+ match Box::pin(generics::generic_update_with_unique_predicate_get_result::<<Self as HasTable>::Table,_,_,@@ -56,7 +56,7 @@ impl PaymentAttempt {.eq(self.attempt_id.to_owned()).and(dsl::processor_merchant_id.eq(self.processor_merchant_id.to_owned())),PaymentAttemptUpdateInternal::from(payment_attempt).populate_derived_fields(&self),- )+ )).await{Err(error) => match error.current_context() {diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rsindex 0cadf780a4..f63ffba976 100644--- a/crates/diesel_models/src/query/payment_intent.rs+++ b/crates/diesel_models/src/query/payment_intent.rs@@ -13,7 +13,7 @@ use crate::{impl PaymentIntentNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentIntent> {- generics::generic_insert(conn, self).await+ Box::pin(generics::generic_insert(conn, self)).await}pub async fn generate_drainer_insert_query(@@ -31,11 +31,12 @@ impl PaymentIntent {conn: &PgPooledConn,payment_intent_update: payment_intent::PaymentIntentUpdateInternal,) -> StorageResult<Self> {- match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(- conn,- self.id.to_owned(),- payment_intent_update,- )+ match Box::pin(generics::generic_update_by_id::<+ <Self as HasTable>::Table,+ _,+ _,+ _,+ >(conn, self.id.to_owned(), payment_intent_update)).await{Err(error) => match error.current_context() {diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rsindex 5e1b294f10..01a89478c7 100644--- a/crates/diesel_models/src/role.rs+++ b/crates/diesel_models/src/role.rs@@ -5,6 +5,7 @@ use time::PrimitiveDateTime;use crate::{enums, schema::roles};#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))]pub struct Role {pub role_name: String,diff --git a/crates/diesel_models/src/tokenization.rs b/crates/diesel_models/src/tokenization.rsindex db10577294..e1dab0a9f5 100644--- a/crates/diesel_models/src/tokenization.rs+++ b/crates/diesel_models/src/tokenization.rs@@ -12,6 +12,7 @@ use crate::schema_v2::tokenization;#[cfg(all(feature = "v2", feature = "tokenization_v2"))]#[derive(Clone, Debug, Identifiable, Insertable, Queryable)]+#[cfg_attr(feature = "deja", derive(Serialize, Deserialize))]#[diesel(table_name = tokenization)]pub struct Tokenization {pub id: id_type::GlobalTokenId,diff --git a/crates/diesel_models/src/unified_translations.rs b/crates/diesel_models/src/unified_translations.rsindex b1a8360e19..fd8d0bcf15 100644--- a/crates/diesel_models/src/unified_translations.rs+++ b/crates/diesel_models/src/unified_translations.rs@@ -6,6 +6,7 @@ use time::PrimitiveDateTime;use crate::schema::unified_translations;#[derive(Clone, Debug, Queryable, Selectable, Identifiable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = unified_translations, primary_key(unified_code, unified_message, locale), check_for_backend(diesel::pg::Pg))]pub struct UnifiedTranslations {pub unified_code: String,diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rsindex d28cb773e6..6214a9e130 100644--- a/crates/diesel_models/src/user.rs+++ b/crates/diesel_models/src/user.rs@@ -10,6 +10,7 @@ pub mod sample_data;pub mod theme;#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))]pub struct User {pub user_id: String,diff --git a/crates/diesel_models/src/user/dashboard_metadata.rs b/crates/diesel_models/src/user/dashboard_metadata.rsindex 913f8af595..3bd172b1d4 100644--- a/crates/diesel_models/src/user/dashboard_metadata.rs+++ b/crates/diesel_models/src/user/dashboard_metadata.rs@@ -6,6 +6,7 @@ use time::PrimitiveDateTime;use crate::{enums, schema::dashboard_metadata};#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = dashboard_metadata, check_for_backend(diesel::pg::Pg))]pub struct DashboardMetadata {pub id: i32,diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rsindex 91d5a7639e..d3ee3f5c8b 100644--- a/crates/diesel_models/src/user/theme.rs+++ b/crates/diesel_models/src/user/theme.rs@@ -10,6 +10,7 @@ use time::PrimitiveDateTime;use crate::schema::themes;#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))]pub struct Theme {pub theme_id: String,diff --git a/crates/diesel_models/src/user_authentication_method.rs b/crates/diesel_models/src/user_authentication_method.rsindex 7f3799aa7b..d6b3f74cfe 100644--- a/crates/diesel_models/src/user_authentication_method.rs+++ b/crates/diesel_models/src/user_authentication_method.rs@@ -5,6 +5,7 @@ use time::PrimitiveDateTime;use crate::{enums, schema::user_authentication_methods};#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = user_authentication_methods, check_for_backend(diesel::pg::Pg))]pub struct UserAuthenticationMethod {pub id: String,diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rsindex 08449685b2..5647c8c7f4 100644--- a/crates/diesel_models/src/user_role.rs+++ b/crates/diesel_models/src/user_role.rs@@ -8,6 +8,7 @@ use time::PrimitiveDateTime;use crate::{enums, schema::user_roles};#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Eq)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[diesel(table_name = user_roles, check_for_backend(diesel::pg::Pg))]pub struct UserRole {pub id: i32,diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex 010e3ec8a3..8e116d6d1e 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -20,7 +20,13 @@ superposition = []v1 = ["hyperswitch_interfaces/v1", "common_utils/v1"]v2 = ["hyperswitch_interfaces/v2", "common_utils/v2"]-deja = ["dep:bytes", "dep:deja"]+deja = [+ "dep:bytes",+ "dep:deja",+ "dep:http-body",+ "dep:http-body-util",+ "dep:prost-reflect",+]revenue_recovery = ["dep:prost","dep:router_env",@@ -56,7 +62,7 @@ aws-smithy-runtime-api = { version = "1.7", features = ["client"] }aws-smithy-types = "1.3.1"base64 = "0.22.1"dyn-clone = "1.0.19"-deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }error-stack = "0.4.1"hex = "0.4.3"hyper = "0.14.32"@@ -69,6 +75,7 @@ serde_json = "1.0.140"serde_urlencoded = "0.7.1"vaultrs = { version = "0.7.4", optional = true }prost = { version = "0.14", optional = true }+prost-reflect = { version = "0.16.5", features = ["serde"], optional = true }prost-types = { version = "0.14", optional = true }time = { version = "0.3.41", features = ["serde", "serde-well-known", "std"] }tokio = "1.48.0"@@ -79,6 +86,7 @@ tonic-types = "0.13.1"typed-builder = "0.21.2"hyper-util = { version = "0.1.12", optional = true }http-body-util = { version = "0.1.3", optional = true }+http-body = { version = "1.0.1", optional = true }reqwest = { version = "0.11.27", features = ["rustls-tls"] }http = "0.2.12"url = { version = "2.5.4", features = ["serde"] }@@ -108,5 +116,10 @@ api_models = { version = "0.1.0", path = "../api_models", optional = true }router_env = { version = "0.1.0", path = "../router_env", default-features = false, optional = true }tonic-prost-build = "0.14"+[dev-dependencies]+# Test-only: the deja gRPC transport test drives a real tonic server over a+# TcpListener via `tokio_stream::wrappers::TcpListenerStream` (the `net` feature).+tokio-stream = { version = "0.1.17", features = ["net"] }+[lints]workspace = truediff --git a/crates/external_services/build.rs b/crates/external_services/build.rsindex e5ab9e34ce..3a1da2bc07 100644--- a/crates/external_services/build.rs+++ b/crates/external_services/build.rs@@ -11,6 +11,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {.out_dir(&out_dir).compile_well_known_types(true).extern_path(".google.protobuf.Timestamp", "::prost_types::Timestamp")+ // The deja gRPC boundary decodes this descriptor set at runtime to+ // render request/response messages structurally.+ .file_descriptor_set_path(out_dir.join("deja_recovery_descriptor.bin")).compile_protos(&recovery_proto_files, &[proto_base_path]).expect("Failed to compile revenue-recovery proto files");}@@ -29,6 +32,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {// Compile the .proto file#[allow(clippy::expect_used, clippy::unwrap_in_result)]tonic_prost_build::configure()+ // The deja gRPC boundary decodes this descriptor set at runtime to+ // render request/response messages structurally.+ .file_descriptor_set_path(out_dir.join("deja_dynamic_routing_descriptor.bin")).out_dir(out_dir).compile_protos(&[diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rsindex 77c21e753b..715f89a5be 100644--- a/crates/external_services/src/grpc_client.rs+++ b/crates/external_services/src/grpc_client.rs@@ -10,6 +10,18 @@ pub mod revenue_recovery;/// gRPC based Unified Connector Service Client interface implementationpub mod unified_connector_service;++/// Deja gRPC egress boundary: the transport-layer tower Service wrapper.+/// Installed at transport construction+/// sites so every unary rpc crosses one deja boundary; identity is rank-2+/// span-path (no explicit call-site tag), routing hardcoded Substitute.+#[cfg(feature = "deja")]+pub mod deja_transport;+/// Deja gRPC egress semantics: recorded result envelope, byte-faithful response+/// reconstruction.+#[cfg(feature = "deja")]+pub mod semantic_boundary;+use std::{fmt::Debug, sync::Arc};#[cfg(feature = "dynamic_routing")]@@ -40,10 +52,26 @@ use crate::grpc_client::unified_connector_service::{UnifiedConnectorServiceClient, UnifiedConnectorServiceClientConfig,};-#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]+#[cfg(all(+ any(feature = "dynamic_routing", feature = "revenue_recovery"),+ not(feature = "deja")+))]/// Hyper based Client type for maintaining connection pool for all gRPC servicespub type Client = hyper_util::client::legacy::Client<HttpConnector, Body>;+#[cfg(all(+ any(feature = "dynamic_routing", feature = "revenue_recovery"),+ feature = "deja"+))]+/// Hyper based Client type for maintaining connection pool for all gRPC services.+///+/// Under the `deja` feature the pool is wrapped in the deja gRPC egress boundary+/// at this single definition site — every unary rpc on every service client built+/// over it (dynamic routing, health check, recovery decider, future) is+/// recorded/substituted at the wire level with zero call-site changes.+pub type Client =+ deja_transport::DejaGrpcTransport<hyper_util::client::legacy::Client<HttpConnector, Body>>;+/// Struct contains all the gRPC Clients#[derive(Debug, Clone)]pub struct GrpcClients {@@ -85,6 +113,13 @@ impl GrpcClientSettings {hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()).http2_only(true).build_http();+ // deja: wrap the shared pool in the gRPC egress boundary at its one+ // construction site.+ #[cfg(all(+ any(feature = "dynamic_routing", feature = "revenue_recovery"),+ feature = "deja"+ ))]+ let client = deja_transport::DejaGrpcTransport::new(client);#[cfg(feature = "dynamic_routing")]let dynamic_routing_connection = selfdiff --git a/crates/external_services/src/grpc_client/deja_transport.rs b/crates/external_services/src/grpc_client/deja_transport.rsnew file mode 100644index 0000000000..83ac32fb33--- /dev/null+++ b/crates/external_services/src/grpc_client/deja_transport.rs@@ -0,0 +1,428 @@+//! The deja gRPC egress boundary — a tower `Service` wrapper around the+//! transport under every generated tonic client.+//!+//! The wrapper is installed at the transport CONSTRUCTION sites (the shared+//! hyper pool `Client` type alias and the UCS channels), so every unary rpc —+//! current and future, on any service client built over the wrapped transport+//! — crosses one deja boundary with zero changes to how gRPC client code is+//! written or called.+//!+//! Identity carries NO explicit call-site id: this is a generic transport+//! wrapper, so there is no per-call-site literal to name. It is+//! `CallsiteSource::SyntacticHash` with `scope = "grpc::/package.Service/Method"`+//! — the rpc path is the most version-independent name an egress call has, and+//! it rides in the scope rather than as a rank-1 id — plus the span path as the+//! calling-context disambiguator. Routing is HARDCODED+//! `ReplayStrategy::Substitute` — egress is never re-issued.+//!+//! Substitution replays the recorded wire bytes through tonic's own decoder+//! (see [`super::semantic_boundary`]), so typed `Status` errors, trailers-only+//! shapes, and metadata partitioning reproduce by construction.++use std::{+ future::Future,+ panic::Location,+ pin::Pin,+ task::{Context, Poll},+};++use tonic::{body::Body as TonicBody, codegen::http};++use super::semantic_boundary::{self, BufferedBody, GrpcResultEnvelope};++/// Boxed error type matching the `GrpcService` transport-error bound.+type BoxError = Box<dyn std::error::Error + Send + Sync>;++const BOUNDARY: &str = "grpc";+const COMPONENT: &str = "external_services::grpc_client::deja_transport";+const OPERATION: &str = "unary";++/// The transport wrapper. Generic over the inner tower service so the same+/// type serves the shared hyper pool (dynamic routing / health / recovery)+/// and the UCS `tonic::transport::Channel`s.+#[derive(Debug, Clone)]+pub struct DejaGrpcTransport<S> {+ inner: S,+}++impl<S> DejaGrpcTransport<S> {+ /// Wraps a transport. Call at the construction site, never per request.+ pub fn new(inner: S) -> Self {+ Self { inner }+ }+}++/// Envelope smuggled through `http::Extensions` from the buffering `run`+/// closure to the recording `extract` closure — the same trick the HTTP+/// boundary uses for its response body (`CapturedResponseBody`).+#[derive(Clone)]+struct CapturedEnvelope(GrpcResultEnvelope);++/// A substituted transport error: the recorded display chain of the original+/// failure. Approximate by design (the original error struct is gone); tonic+/// maps it through `Status::from_error` exactly as it would a live failure.+#[derive(Debug)]+pub struct ReplayedTransportError(pub String);++impl std::fmt::Display for ReplayedTransportError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "deja replayed transport error: {}", self.0)+ }+}++impl std::error::Error for ReplayedTransportError {}++impl<S, RB> tonic::codegen::Service<http::Request<TonicBody>> for DejaGrpcTransport<S>+where+ S: tonic::codegen::Service<http::Request<TonicBody>, Response = http::Response<RB>>+ + Clone+ + Send+ + 'static,+ S::Future: Send + 'static,+ S::Error: Into<BoxError>,+ RB: http_body::Body<Data = bytes::Bytes> + Send + 'static,+ RB::Error: Into<BoxError>,+{+ type Response = http::Response<TonicBody>;+ type Error = BoxError;+ type Future = Pin<Box<dyn Future<Output = Result<Self::Response, BoxError>> + Send>>;++ fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {+ self.inner.poll_ready(cx).map_err(Into::into)+ }++ #[track_caller]+ fn call(&mut self, request: http::Request<TonicBody>) -> Self::Future {+ // Standard tower clone-dance: `self.inner` was driven to readiness by+ // poll_ready, so hand THAT instance to the future and keep the fresh+ // clone (which will be polled to readiness before its own use).+ let clone = self.inner.clone();+ let inner = std::mem::replace(&mut self.inner, clone);++ // Boundary engaged only when a deja hook is live (record or replay);+ // otherwise pure passthrough — no buffering, no dispatch, streaming+ // untouched.+ if !is_active() {+ return Box::pin(passthrough(inner, request));+ }+ let caller = Location::caller();+ Box::pin(boundary_call(inner, request, caller))+ }+}++fn is_active() -> bool {+ // Covers BOTH worlds: replay/record via the runtime hook (runtime_mode)+ // and record via the recording hook — substitution must engage in replay,+ // so this must never be a record-only check.+ deja::__private::observation_is_active()+}++async fn passthrough<S, RB>(+ mut inner: S,+ request: http::Request<TonicBody>,+) -> Result<http::Response<TonicBody>, BoxError>+where+ S: tonic::codegen::Service<http::Request<TonicBody>, Response = http::Response<RB>>,+ S::Error: Into<BoxError>,+ RB: http_body::Body<Data = bytes::Bytes> + Send + 'static,+ RB::Error: Into<BoxError>,+{+ let response = inner.call(request).await.map_err(Into::into)?;+ Ok(response.map(TonicBody::new))+}++/// One unary gRPC exchange as one deja boundary crossing.+async fn boundary_call<S, RB>(+ inner: S,+ request: http::Request<TonicBody>,+ caller: &'static Location<'static>,+) -> Result<http::Response<TonicBody>, BoxError>+where+ S: tonic::codegen::Service<http::Request<TonicBody>, Response = http::Response<RB>>+ + Send+ + 'static,+ S::Future: Send + 'static,+ S::Error: Into<BoxError>,+ RB: http_body::Body<Data = bytes::Bytes> + Send + 'static,+ RB::Error: Into<BoxError>,+{+ let (parts, body) = request.into_parts();++ // Unary request: buffer the frames before forwarding — args identity+ // needs the message bytes, and the rebuilt body is what the inner+ // transport actually sends.+ let request_bytes = match http_body_util::BodyExt::collect(body).await {+ Ok(collected) => collected.to_bytes(),+ Err(error) => return Err(error.into()),+ };++ let rpc: String = parts.uri.path().to_owned();+ let authority = parts.uri.authority().map(ToString::to_string);++ // Descriptor-decoded proto3-JSON for the local protos; UCS (unknown+ // schema) falls back to the canonical wire identity inside `grpc_args`.+ #[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]+ let decoded_request =+ semantic_boundary::descriptors::decode_unary_request(&rpc, &request_bytes);+ #[cfg(not(any(feature = "dynamic_routing", feature = "revenue_recovery")))]+ let decoded_request: Option<serde_json::Value> = None;++ let args_value = semantic_boundary::grpc_args(+ &rpc,+ authority.as_deref(),+ &parts.headers,+ &request_bytes,+ decoded_request,+ );+ let correlation = semantic_boundary::correlation(&parts.headers);++ // Identity: rank-2 span-path (from the ambient tracing context) — NO explicit+ // call-site id. rank-1 Explicit is a hand-out tag, not a burden to stamp on+ // call-sites; the rpc path lives in the ARGS (grpc_args), not the identity, so+ // replay matches within a span by occurrence + args — exactly like the+ // db / redis / superposition boundaries. The syntactic hash of "grpc::<path>"+ // is the rank-3 fallback (each in-span call is still disambiguated by+ // occurrence, so distinct rpcs never collapse onto one identity).+ let scope = format!("grpc::{rpc}");+ let identity = deja::__private::CallsiteIdentity {+ version: 1,+ source: deja::__private::CallsiteSource::SyntacticHash,+ id: None,+ scope: Some(scope.clone()),+ occurrence: deja::__private::next_boundary_occurrence(+ correlation.as_deref(),+ deja::__private::CallsiteSource::SyntacticHash,+ Some(&scope),+ ),+ caller_function: Some(COMPONENT.to_string()),+ lexical_path: Some(scope.clone()),+ syntax_hash: Some(deja::__private::stable_callsite_hash(&scope)),+ span_path: deja::__private::current_span_path(),+ };++ // Egress routing is hardcoded: never re-issued on replay.+ let semantics = deja::__private::BoundarySemantics {+ replay_strategy: deja::ReplayStrategy::Substitute,+ kind: Some(BOUNDARY.to_string()),+ declaration: Some(+ deja::BoundaryDeclaration::default().operation(deja::OperationKind::ExternalCall),+ ),+ };+ let spec =+ deja::__private::BoundarySpec::with_semantics(BOUNDARY, COMPONENT, OPERATION, semantics);+ let observation =+ deja::__private::CrossingObservation::with_correlation(spec, identity, caller, correlation);++ let rebuilt_request = http::Request::from_parts(+ parts,+ TonicBody::new(BufferedBody::new(request_bytes, None)),+ );++ deja::__private::dispatch_async(+ observation,+ move || args_value,+ move || run_and_capture(inner, rebuilt_request),+ reconstruct_from_recorded,+ extract_envelope,+ )+ .await+}++/// The `run` thunk: forward to the real transport, buffer the response+/// verbatim (data frames + trailers), and hand tonic a response rebuilt over+/// the SAME buffer the tape captures — byte-identical parity. The envelope+/// rides `http::Extensions` to the extractor.+async fn run_and_capture<S, RB>(+ mut inner: S,+ request: http::Request<TonicBody>,+) -> Result<http::Response<TonicBody>, BoxError>+where+ S: tonic::codegen::Service<http::Request<TonicBody>, Response = http::Response<RB>>,+ S::Error: Into<BoxError>,+ RB: http_body::Body<Data = bytes::Bytes> + Send + 'static,+ RB::Error: Into<BoxError>,+{+ let response = match inner.call(request).await {+ Ok(response) => response,+ Err(error) => return Err(error.into()),+ };+ let (parts, body) = response.into_parts();+ let collected = match http_body_util::BodyExt::collect(body).await {+ Ok(collected) => collected,+ Err(error) => return Err(error.into()),+ };+ let trailers = collected.trailers().cloned();+ let data = collected.to_bytes();++ let envelope = GrpcResultEnvelope::from_response_parts(+ parts.status.as_u16(),+ &parts.headers,+ &data,+ trailers.as_ref(),+ );+ let mut rebuilt =+ http::Response::from_parts(parts, TonicBody::new(BufferedBody::new(data, trailers)));+ rebuilt.extensions_mut().insert(CapturedEnvelope(envelope));+ Ok(rebuilt)+}++/// The `extract` closure: envelope out of the extensions (record path), or a+/// transport-error envelope from the `Err` arm.+fn extract_envelope(+ result: &Result<http::Response<TonicBody>, BoxError>,+) -> (serde_json::Value, bool) {+ let envelope = match result {+ Ok(response) => match response.extensions().get::<CapturedEnvelope>() {+ Some(CapturedEnvelope(envelope)) => envelope.clone(),+ // Unreachable on the record path (run_and_capture always stamps+ // it); recorded loudly rather than silently if it ever happens.+ None => GrpcResultEnvelope::TransportError {+ error: "deja: response envelope was not captured".to_owned(),+ },+ },+ Err(error) => GrpcResultEnvelope::TransportError {+ error: format!("{error}"),+ },+ };+ let is_error = envelope.is_err();+ let value = serde_json::to_value(&envelope).unwrap_or_else(+ |error| serde_json::json!({ "deja_grpc_capture_error": error.to_string() }),+ );+ (value, is_error)+}++/// The `reconstruct` closure: recorded envelope → the identical wire response+/// through tonic's own decoder, or the recorded transport failure.+fn reconstruct_from_recorded(+ recorded: serde_json::Value,+) -> deja::__private::Reconstructed<Result<http::Response<TonicBody>, BoxError>> {+ let Ok(envelope) = serde_json::from_value::<GrpcResultEnvelope>(recorded) else {+ return deja::__private::Reconstructed::Failed;+ };+ match &envelope {+ GrpcResultEnvelope::Response { .. } => {+ match semantic_boundary::reconstruct_response(&envelope) {+ Some(response) => {+ deja::__private::Reconstructed::Value(Ok(response.map(TonicBody::new)))+ }+ None => deja::__private::Reconstructed::Failed,+ }+ }+ GrpcResultEnvelope::TransportError { error } => deja::__private::Reconstructed::Value(Err(+ Box::new(ReplayedTransportError(error.clone())),+ )),+ }+}++#[cfg(all(test, feature = "dynamic_routing"))]+#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]+mod tests {+ use super::{+ super::dynamic_routing::{+ success_rate_client::success_rate::{+ success_rate_calculator_server::{+ SuccessRateCalculator, SuccessRateCalculatorServer,+ },+ CalGlobalSuccessRateRequest, CalGlobalSuccessRateResponse, CalSuccessRateRequest,+ CalSuccessRateResponse, InvalidateWindowsRequest, InvalidateWindowsResponse,+ LabelWithScore, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,+ },+ SuccessRateCalculatorClient,+ },+ *,+ };++ /// Canned scorer: a deterministic Ok and a typed decline.+ pub(crate) struct CannedScorer;++ #[tonic::async_trait]+ impl SuccessRateCalculator for CannedScorer {+ async fn fetch_success_rate(+ &self,+ request: tonic::Request<CalSuccessRateRequest>,+ ) -> Result<tonic::Response<CalSuccessRateResponse>, tonic::Status> {+ let id = request.into_inner().id;+ Ok(tonic::Response::new(CalSuccessRateResponse {+ labels_with_score: vec![LabelWithScore {+ score: 0.75,+ label: format!("stripe:{id}"),+ }],+ routing_approach: 0,+ }))+ }++ async fn update_success_rate_window(+ &self,+ _request: tonic::Request<UpdateSuccessRateWindowRequest>,+ ) -> Result<tonic::Response<UpdateSuccessRateWindowResponse>, tonic::Status> {+ Err(tonic::Status::invalid_argument("window rejected"))+ }++ async fn invalidate_windows(+ &self,+ _request: tonic::Request<InvalidateWindowsRequest>,+ ) -> Result<tonic::Response<InvalidateWindowsResponse>, tonic::Status> {+ Err(tonic::Status::unimplemented("not in this test"))+ }++ async fn fetch_entity_and_global_success_rate(+ &self,+ _request: tonic::Request<CalGlobalSuccessRateRequest>,+ ) -> Result<tonic::Response<CalGlobalSuccessRateResponse>, tonic::Status> {+ Err(tonic::Status::unimplemented("not in this test"))+ }+ }++ /// Inactive-hook passthrough: real tonic server + wrapped hyper pool,+ /// traffic must be untouched in both arms. (The RECORD side needs a+ /// separate process, because the global hook OnceLock latches on first+ /// read and this test must observe the pre-install state.)+ #[tokio::test]+ async fn inactive_wrapper_is_a_pure_passthrough() {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(+ tonic::transport::Server::builder()+ .add_service(SuccessRateCalculatorServer::new(CannedScorer))+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)),+ );++ let pool =+ hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())+ .http2_only(true)+ .build_http();+ let transport = DejaGrpcTransport::new(pool);+ let uri: http::Uri = format!("http://127.0.0.1:{port}").parse().unwrap();+ let mut client = SuccessRateCalculatorClient::with_origin(transport, uri);++ assert!(!is_active(), "no deja hook may be active in the lib tests");+ let response = client+ .fetch_success_rate(tonic::Request::new(CalSuccessRateRequest {+ id: "m1".to_owned(),+ params: "card".to_owned(),+ labels: vec![],+ config: None,+ }))+ .await+ .unwrap()+ .into_inner();+ assert_eq!(response.labels_with_score.len(), 1);+ assert_eq!(+ response.labels_with_score.first().unwrap().label,+ "stripe:m1"+ );++ let status = client+ .update_success_rate_window(UpdateSuccessRateWindowRequest {+ id: "m1".to_owned(),+ params: String::new(),+ labels_with_status: vec![],+ global_labels_with_status: vec![],+ config: None,+ })+ .await+ .unwrap_err();+ assert_eq!(status.code(), tonic::Code::InvalidArgument);+ assert_eq!(status.message(), "window rejected");+ }+}diff --git a/crates/external_services/src/grpc_client/semantic_boundary.rs b/crates/external_services/src/grpc_client/semantic_boundary.rsnew file mode 100644index 0000000000..9f62956884--- /dev/null+++ b/crates/external_services/src/grpc_client/semantic_boundary.rs@@ -0,0 +1,715 @@+//! Deja gRPC egress semantics — the capture/reconstruct half of the gRPC+//! boundary.+//!+//! Mirrors `http_client::semantic_boundary` one layer down: the boundary sits+//! on the tonic *transport* (a tower `Service`), so everything here operates+//! on wire-level values — http/2 response parts, length-prefixed gRPC frames,+//! trailers — and never interprets gRPC framing. Recorded bytes are replayed+//! verbatim through tonic's own decoder, which is what makes substitution+//! byte-faithful: typed `Status` (including `grpc-status-details-bin`),+//! trailers-only error shapes, and compression all reproduce by construction.+//!+//! Lookup identity note: undecoded (descriptor-less) request messages MUST be+//! keyed by [`wire_canon`], never by raw bytes — prost encodes `map<..>`+//! fields in per-process `HashMap` iteration order, so the same logical+//! request produces different bytes across the recording and candidate+//! processes. Responses are never hashed: they replay verbatim.++use base64::Engine;+use tonic::codegen::http;++/// General purpose base64 engine used for wire payload capture.+const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;++/// Correlation for a gRPC egress call: the `x-request-id` request metadata,+/// attached by all three client families (mirrors the HTTP boundary's+/// `X-Request-Id` extractor).+pub fn correlation(headers: &http::HeaderMap) -> Option<String> {+ headers+ .get("x-request-id")+ .and_then(|value| value.to_str().ok())+ .map(ToOwned::to_owned)+}++/// Canonical boundary args for a unary gRPC call.+///+/// `decoded_request` is the descriptor-decoded proto3-JSON of the request+/// message when the rpc's schema is known (local protos); when `None` the+/// args instead carry the [`wire_canon`] form of each request message and an+/// `undecoded: true` marker (UCS — field-level diffs deferred by design D2).+pub fn grpc_args(+ rpc: &str,+ authority: Option<&str>,+ headers: &http::HeaderMap,+ request_body: &[u8],+ decoded_request: Option<serde_json::Value>,+) -> serde_json::Value {+ let mut args = serde_json::Map::new();+ args.insert("rpc".to_owned(), serde_json::Value::from(rpc));+ args.insert("authority".to_owned(), serde_json::Value::from(authority));+ args.insert(+ "metadata".to_owned(),+ serde_json::json!(header_pairs(headers)),+ );+ match decoded_request {+ Some(decoded) => {+ args.insert("request".to_owned(), decoded);+ }+ None => {+ // Canonicalize per message so the identity is stable under+ // prost's map-entry encode-order nondeterminism. A body that does+ // not parse as clean gRPC framing (or carries compressed frames)+ // falls back to canonicalizing the whole body — still+ // deterministic, weaker only in precision.+ let canon: Vec<String> = match unframe_messages(request_body) {+ Some(messages) => messages+ .iter()+ .map(|message| wire_canon::canonical_b64(message))+ .collect(),+ None => vec![wire_canon::canonical_b64(request_body)],+ };+ args.insert("request_canon_b64".to_owned(), serde_json::json!(canon));+ args.insert("undecoded".to_owned(), serde_json::Value::from(true));+ }+ }+ serde_json::Value::Object(args)+}++/// Splits a raw gRPC message-stream body into its length-prefixed messages+/// (`[compressed: u8][len: u32 BE][payload]`*). Returns `None` on malformed+/// framing or any compressed frame (canonicalization cannot see inside+/// compressed bytes; hyperswitch clients never negotiate compression).+pub fn unframe_messages(body: &[u8]) -> Option<Vec<&[u8]>> {+ let mut out = Vec::new();+ let mut rest = body;+ while !rest.is_empty() {+ let (head, tail) = rest.split_at_checked(5)?;+ if *head.first()? != 0 {+ return None;+ }+ let len_bytes: [u8; 4] = head.get(1..5)?.try_into().ok()?;+ let len = usize::try_from(u32::from_be_bytes(len_bytes)).ok()?;+ let (message, remaining) = tail.split_at_checked(len)?;+ out.push(message);+ rest = remaining;+ }+ Some(out)+}++/// Schema-free canonicalization of protobuf wire bytes, used ONLY to derive+/// stable lookup identity for undecoded messages.+///+/// The contract is DETERMINISM, not schema-correctness: both the lookup+/// renderer and the replay hook apply the same procedure to their respective+/// bytes, so any parse heuristic is fine as long as identical payloads make+/// identical decisions. Canonicalization sorts repeated occurrences of the+/// same field number (map entries are repeated messages on the wire), which+/// erases order-sensitivity of genuinely ordered repeated fields FOR THE KEY+/// — an accepted, documented trade-off (order-only changes substitute instead+/// of re-keying).+pub mod wire_canon {+ use base64::Engine;++ /// Nesting cap: beyond this the level is kept verbatim (still+ /// deterministic — depth is a function of the data).+ const MAX_DEPTH: usize = 32;++ /// Canonical form of `bytes`; input that does not parse as protobuf wire+ /// format is returned verbatim.+ pub fn canonical(bytes: &[u8]) -> Vec<u8> {+ canon_level(bytes, 0).unwrap_or_else(|| bytes.to_vec())+ }++ /// Base64 of [`canonical`] — the shape embedded in boundary args.+ pub fn canonical_b64(bytes: &[u8]) -> String {+ super::B64.encode(canonical(bytes))+ }++ fn canon_level(bytes: &[u8], depth: usize) -> Option<Vec<u8>> {+ if depth >= MAX_DEPTH {+ return None;+ }+ let mut items: Vec<(u64, u8, Vec<u8>)> = Vec::new();+ let mut rest = bytes;+ while !rest.is_empty() {+ let (tag, remaining) = varint(rest)?;+ rest = remaining;+ let field = tag >> 3;+ let wire_type = u8::try_from(tag & 7).ok()?;+ if field == 0 {+ return None;+ }+ let payload: Vec<u8> = match wire_type {+ 0 => {+ let (raw, remaining) = varint_raw(rest)?;+ rest = remaining;+ raw.to_vec()+ }+ 1 => take(&mut rest, 8)?.to_vec(),+ 5 => take(&mut rest, 4)?.to_vec(),+ 2 => {+ let (len, remaining) = varint(rest)?;+ rest = remaining;+ let raw = take(&mut rest, usize::try_from(len).ok()?)?;+ // Recurse when the payload itself parses as wire format.+ // The decision depends only on the payload bytes, so it is+ // identical on both sides of a record/replay pair.+ canon_level(raw, depth.checked_add(1)?).unwrap_or_else(|| raw.to_vec())+ }+ // Groups (3/4) are deprecated and unused; anything else is+ // malformed — keep the whole level verbatim.+ _ => return None,+ };+ items.push((field, wire_type, payload));+ }+ items.sort();+ let mut out = Vec::with_capacity(bytes.len());+ for (field, wire_type, payload) in items {+ put_varint(field.checked_shl(3)? | u64::from(wire_type), &mut out);+ if wire_type == 2 {+ put_varint(u64::try_from(payload.len()).ok()?, &mut out);+ }+ out.extend_from_slice(&payload);+ }+ Some(out)+ }++ fn take<'a>(rest: &mut &'a [u8], n: usize) -> Option<&'a [u8]> {+ let (head, tail) = rest.split_at_checked(n)?;+ *rest = tail;+ Some(head)+ }++ /// Decodes a varint, returning (value, rest). Rejects >10-byte runs.+ fn varint(bytes: &[u8]) -> Option<(u64, &[u8])> {+ let (raw, rest) = varint_raw(bytes)?;+ let mut value: u64 = 0;+ for (index, byte) in raw.iter().enumerate() {+ let shift = u32::try_from(index).ok()?.checked_mul(7)?;+ value |= u64::from(byte & 0x7f).checked_shl(shift)?;+ }+ Some((value, rest))+ }++ /// Splits off the raw encoded bytes of one varint (preserved verbatim so+ /// re-emission never normalizes what the producer wrote).+ fn varint_raw(bytes: &[u8]) -> Option<(&[u8], &[u8])> {+ let end = bytes+ .iter()+ .take(10)+ .position(|byte| byte & 0x80 == 0)?+ .checked_add(1)?;+ bytes.split_at_checked(end)+ }++ fn put_varint(mut value: u64, out: &mut Vec<u8>) {+ loop {+ let byte = u8::try_from(value & 0x7f).unwrap_or(0x7f);+ value >>= 7;+ if value == 0 {+ out.push(byte);+ return;+ }+ out.push(byte | 0x80);+ }+ }+}++/// The recorded result of one unary gRPC exchange — everything needed to hand+/// tonic's decoder a byte-identical response on replay.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum GrpcResultEnvelope {+ /// An HTTP/2 response arrived (any grpc-status, including declines —+ /// gRPC errors are just recorded trailers, replayed verbatim).+ Response {+ /// HTTP status (gRPC uses 200 even for declines; transport-mapped+ /// failures may differ).+ http_status: u16,+ /// Response headers, sorted by (name, value). gRPC metadata is ASCII+ /// by spec (binary metadata rides base64 in `-bin` keys); non-UTF-8+ /// values are captured lossily.+ headers: Vec<(String, String)>,+ /// Raw gRPC body frames exactly as received — length prefixes,+ /// compression flags and all. Never parsed, never re-framed.+ body_b64: String,+ /// HTTP/2 trailers; `None` preserves the trailers-only/headers-only+ /// error shape so `Status::metadata()` partitions identically.+ trailers: Option<Vec<(String, String)>>,+ },+ /// The transport itself failed (connect refused, h2 reset, timeout).+ /// Replays approximately: the recorded display chain, not the original+ /// error struct.+ TransportError {+ /// Display chain of the transport error.+ error: String,+ },+}++impl GrpcResultEnvelope {+ /// Captures a buffered response into its recorded envelope.+ pub fn from_response_parts(+ http_status: u16,+ headers: &http::HeaderMap,+ body: &[u8],+ trailers: Option<&http::HeaderMap>,+ ) -> Self {+ Self::Response {+ http_status,+ headers: header_pairs(headers),+ body_b64: B64.encode(body),+ trailers: trailers.map(header_pairs),+ }+ }++ /// Whether this result is an error in gRPC terms: transport failure,+ /// non-zero `grpc-status` (trailers first, then the headers-only shape),+ /// or a missing status on a non-200 response.+ pub fn is_err(&self) -> bool {+ match self {+ Self::TransportError { .. } => true,+ Self::Response {+ http_status,+ headers,+ trailers,+ ..+ } => {+ let grpc_status = trailers+ .as_ref()+ .and_then(|pairs| find_pair(pairs, "grpc-status"))+ .or_else(|| find_pair(headers, "grpc-status"));+ match grpc_status {+ Some(status) => status != "0",+ None => *http_status != 200,+ }+ }+ }+ }+}++fn find_pair<'a>(pairs: &'a [(String, String)], name: &str) -> Option<&'a str> {+ pairs+ .iter()+ .find(|(key, _)| key == name)+ .map(|(_, value)| value.as_str())+}++/// ALL request metadata, sorted by (name, value) so the serialized args are+/// canonical (`args_hash` is order-sensitive).+///+/// Full-fidelity capture BY POLICY: everything the request carried is recorded+/// — including connector auth metadata — exactly as the HTTP boundary records+/// all request headers. Tape protection/redaction is a separate, deferred+/// workstream; the capture layer never drops data. Replay stability holds+/// because the candidate rebuilds requests from SEEDED state, so recorded+/// values reproduce; a metadata change (auth, transport version, anything)+/// re-keys the lookup and surfaces as an honest divergence — same semantics+/// as HTTP.+fn header_pairs(headers: &http::HeaderMap) -> Vec<(String, String)> {+ let mut out: Vec<(String, String)> = headers+ .iter()+ .map(|(name, value)| {+ (+ name.as_str().to_owned(),+ String::from_utf8_lossy(value.as_bytes()).into_owned(),+ )+ })+ .collect();+ out.sort();+ out+}++fn headers_from_pairs(pairs: &[(String, String)]) -> Option<http::HeaderMap> {+ let mut map = http::HeaderMap::with_capacity(pairs.len());+ for (name, value) in pairs {+ map.append(+ http::header::HeaderName::from_bytes(name.as_bytes()).ok()?,+ http::header::HeaderValue::from_str(value).ok()?,+ );+ }+ Some(map)+}++/// Rebuilds the `http::Response` a substituted call returns — tonic's own+/// client stack decodes it exactly as it would a network response. `None`+/// (malformed recorded data, or the transport-error arm which the seam+/// handles separately) maps to a reconstruction failure at the boundary.+pub fn reconstruct_response(envelope: &GrpcResultEnvelope) -> Option<http::Response<BufferedBody>> {+ let GrpcResultEnvelope::Response {+ http_status,+ headers,+ body_b64,+ trailers,+ } = envelope+ else {+ return None;+ };+ let data = B64.decode(body_b64).ok()?;+ let trailer_map = match trailers {+ Some(pairs) => Some(headers_from_pairs(pairs)?),+ None => None,+ };+ let mut response =+ http::Response::new(BufferedBody::new(bytes::Bytes::from(data), trailer_map));+ *response.status_mut() = http::StatusCode::from_u16(*http_status).ok()?;+ *response.headers_mut() = headers_from_pairs(headers)?;+ Some(response)+}++/// A fully buffered http body: one data frame, then optional trailers, then+/// end-of-stream. Serves both sides of the boundary — the record path hands+/// tonic a response rebuilt over the same buffer it taped (byte-identical+/// parity), and the replay path reconstructs from the recorded envelope.+#[derive(Debug)]+pub struct BufferedBody {+ data: Option<bytes::Bytes>,+ trailers: Option<http::HeaderMap>,+}++impl BufferedBody {+ /// A body yielding `data` (skipped when empty) then `trailers`.+ pub fn new(data: bytes::Bytes, trailers: Option<http::HeaderMap>) -> Self {+ Self {+ data: (!data.is_empty()).then_some(data),+ trailers,+ }+ }+}++impl http_body::Body for BufferedBody {+ type Data = bytes::Bytes;+ type Error = std::convert::Infallible;++ fn poll_frame(+ self: std::pin::Pin<&mut Self>,+ _cx: &mut std::task::Context<'_>,+ ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {+ let this = self.get_mut();+ if let Some(data) = this.data.take() {+ return std::task::Poll::Ready(Some(Ok(http_body::Frame::data(data))));+ }+ if let Some(trailers) = this.trailers.take() {+ return std::task::Poll::Ready(Some(Ok(http_body::Frame::trailers(trailers))));+ }+ std::task::Poll::Ready(None)+ }++ fn is_end_stream(&self) -> bool {+ self.data.is_none() && self.trailers.is_none()+ }++ fn size_hint(&self) -> http_body::SizeHint {+ match &self.data {+ Some(data) => {+ http_body::SizeHint::with_exact(u64::try_from(data.len()).unwrap_or(u64::MAX))+ }+ None => http_body::SizeHint::with_exact(0),+ }+ }+}++/// Descriptor-pool decoding for the local protos (dynamic routing, revenue+/// recovery, health) — the readable-JSON projection and field-level diffs.+/// UCS descriptors are deferred by design decision D2; UCS rpcs simply return+/// `None` here and fall back to the wire-canonical identity.+#[cfg(any(feature = "dynamic_routing", feature = "revenue_recovery"))]+pub mod descriptors {+ use std::sync::OnceLock;++ use prost_reflect::{DescriptorPool, DynamicMessage, MessageDescriptor};++ static POOLS: OnceLock<Vec<DescriptorPool>> = OnceLock::new();++ /// One pool per emitted descriptor set (kept separate so shared+ /// well-known files can never collide across sets).+ fn pools() -> &'static [DescriptorPool] {+ POOLS.get_or_init(|| {+ let mut pools = Vec::new();+ #[cfg(feature = "dynamic_routing")]+ if let Ok(pool) = DescriptorPool::decode(+ &include_bytes!(concat!(+ env!("OUT_DIR"),+ "/deja_dynamic_routing_descriptor.bin"+ ))[..],+ ) {+ pools.push(pool);+ }+ #[cfg(feature = "revenue_recovery")]+ if let Ok(pool) = DescriptorPool::decode(+ &include_bytes!(concat!(env!("OUT_DIR"), "/deja_recovery_descriptor.bin"))[..],+ ) {+ pools.push(pool);+ }+ pools+ })+ }++ /// `(input, output)` message descriptors for an rpc path of the form+ /// `/package.Service/Method`, when the schema is known.+ pub fn method_descriptors(rpc: &str) -> Option<(MessageDescriptor, MessageDescriptor)> {+ let (service, method) = rpc.strip_prefix('/')?.split_once('/')?;+ pools().iter().find_map(|pool| {+ let service = pool+ .services()+ .find(|candidate| candidate.full_name() == service)?;+ let method = service+ .methods()+ .find(|candidate| candidate.name() == method)?;+ Some((method.input(), method.output()))+ })+ }++ /// Proto3-JSON projection of one wire message.+ pub fn decode_to_json(+ descriptor: &MessageDescriptor,+ message: &[u8],+ ) -> Option<serde_json::Value> {+ let decoded = DynamicMessage::decode(descriptor.clone(), message).ok()?;+ serde_json::to_value(&decoded).ok()+ }++ /// Decodes a single-message request body (unary) into proto3-JSON using+ /// the rpc's input descriptor. `None` = unknown schema or malformed body;+ /// callers fall back to the wire-canonical identity.+ pub fn decode_unary_request(rpc: &str, request_body: &[u8]) -> Option<serde_json::Value> {+ let (input, _) = method_descriptors(rpc)?;+ let messages = super::unframe_messages(request_body)?;+ let (message, rest) = messages.split_first()?;+ if !rest.is_empty() {+ return None;+ }+ decode_to_json(&input, message)+ }+}++#[cfg(test)]+#[allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]+mod tests {+ use super::*;++ /// Minimal wire-format writer for test fixtures.+ fn field(out: &mut Vec<u8>, number: u64, wire_type: u64, payload: &[u8]) {+ put_test_varint(number << 3 | wire_type, out);+ if wire_type == 2 {+ put_test_varint(u64::try_from(payload.len()).unwrap(), out);+ }+ out.extend_from_slice(payload);+ }++ fn put_test_varint(mut value: u64, out: &mut Vec<u8>) {+ loop {+ let byte = u8::try_from(value & 0x7f).unwrap();+ value >>= 7;+ if value == 0 {+ out.push(byte);+ return;+ }+ out.push(byte | 0x80);+ }+ }++ /// One `map<string, string>` entry: nested message {1: key, 2: value}.+ fn map_entry(key: &str, value: &str) -> Vec<u8> {+ let mut entry = Vec::new();+ field(&mut entry, 1, 2, key.as_bytes());+ field(&mut entry, 2, 2, value.as_bytes());+ entry+ }++ fn frame(message: &[u8]) -> Vec<u8> {+ let mut framed = vec![0u8];+ framed.extend_from_slice(&u32::try_from(message.len()).unwrap().to_be_bytes());+ framed.extend_from_slice(message);+ framed+ }++ #[test]+ fn map_reorder_is_canonically_stable() {+ // message { 1: "id", map<string,string> 2 } with entries in both orders+ let (mut ab, mut ba) = (Vec::new(), Vec::new());+ field(&mut ab, 1, 2, b"payment_123");+ field(&mut ab, 2, 2, &map_entry("alpha", "1"));+ field(&mut ab, 2, 2, &map_entry("beta", "2"));+ field(&mut ba, 1, 2, b"payment_123");+ field(&mut ba, 2, 2, &map_entry("beta", "2"));+ field(&mut ba, 2, 2, &map_entry("alpha", "1"));+ assert_ne!(ab, ba, "fixtures must differ before canonicalization");+ assert_eq!(wire_canon::canonical(&ab), wire_canon::canonical(&ba));+ }++ #[test]+ fn value_changes_change_the_canonical_form() {+ let (mut left, mut right) = (Vec::new(), Vec::new());+ field(&mut left, 2, 2, &map_entry("alpha", "1"));+ field(&mut right, 2, 2, &map_entry("alpha", "CHANGED"));+ assert_ne!(wire_canon::canonical(&left), wire_canon::canonical(&right));+ }++ #[test]+ fn nested_map_reorder_is_canonically_stable() {+ // outer message { 3: inner } where inner carries the reordered map+ let (mut inner_ab, mut inner_ba) = (Vec::new(), Vec::new());+ field(&mut inner_ab, 2, 2, &map_entry("alpha", "1"));+ field(&mut inner_ab, 2, 2, &map_entry("beta", "2"));+ field(&mut inner_ba, 2, 2, &map_entry("beta", "2"));+ field(&mut inner_ba, 2, 2, &map_entry("alpha", "1"));+ let (mut outer_ab, mut outer_ba) = (Vec::new(), Vec::new());+ field(&mut outer_ab, 3, 2, &inner_ab);+ field(&mut outer_ba, 3, 2, &inner_ba);+ assert_eq!(+ wire_canon::canonical(&outer_ab),+ wire_canon::canonical(&outer_ba)+ );+ }++ #[test]+ fn non_protobuf_input_passes_through_verbatim() {+ let text = b"hello world! this is not protobuf";+ assert_eq!(wire_canon::canonical(text), text.to_vec());+ assert_eq!(wire_canon::canonical(&[]), Vec::<u8>::new());+ }++ #[test]+ fn unframe_roundtrip_and_rejections() {+ let message = b"\x0a\x02hi".to_vec();+ let mut body = frame(&message);+ body.extend_from_slice(&frame(b"more"));+ let messages = unframe_messages(&body).unwrap();+ assert_eq!(messages, vec![&message[..], &b"more"[..]]);++ // compressed flag and truncation are both rejected+ let mut compressed = frame(&message);+ compressed[0] = 1;+ assert!(unframe_messages(&compressed).is_none());+ assert!(unframe_messages(&body[..body.len() - 1]).is_none());+ }++ #[test]+ fn args_capture_everything_sorted_full_fidelity() {+ let mut headers = http::HeaderMap::new();+ headers.insert("x-tenant-id", "t1".parse().unwrap());+ headers.insert("x-request-id", "req_9".parse().unwrap());+ headers.insert("x-api-key", "SECRET".parse().unwrap());+ headers.insert("content-type", "application/grpc".parse().unwrap());++ let args = grpc_args(+ "/success_rate.SuccessRateCalculator/FetchSuccessRate",+ Some("dyn-routing:7000"),+ &headers,+ &frame(b"\x0a\x02id"),+ None,+ );+ // Full fidelity: EVERYTHING the request carried is on the tape —+ // auth metadata included (protection is a deferred workstream, and+ // the HTTP boundary records all headers identically). Sorted for a+ // canonical args_hash.+ assert_eq!(+ args["metadata"],+ serde_json::json!([+ ["content-type", "application/grpc"],+ ["x-api-key", "SECRET"],+ ["x-request-id", "req_9"],+ ["x-tenant-id", "t1"]+ ])+ );+ assert_eq!(args["undecoded"], serde_json::json!(true));+ assert_eq!(correlation(&headers).as_deref(), Some("req_9"));+ }++ #[test]+ fn envelope_roundtrips_through_serde() {+ let envelope = GrpcResultEnvelope::Response {+ http_status: 200,+ headers: vec![("content-type".to_owned(), "application/grpc".to_owned())],+ body_b64: B64.encode(frame(b"\x08\x01")),+ trailers: Some(vec![("grpc-status".to_owned(), "0".to_owned())]),+ };+ let json = serde_json::to_value(&envelope).unwrap();+ let back: GrpcResultEnvelope = serde_json::from_value(json).unwrap();+ assert_eq!(envelope, back);+ assert!(!envelope.is_err());+ assert!(GrpcResultEnvelope::TransportError {+ error: "connect refused".to_owned()+ }+ .is_err());+ }++ #[tokio::test]+ async fn buffered_body_emits_data_then_trailers() {+ use http_body_util::BodyExt;++ let mut trailers = http::HeaderMap::new();+ trailers.insert("grpc-status", "0".parse().unwrap());+ let body = BufferedBody::new(bytes::Bytes::from_static(b"payload"), Some(trailers));+ let collected = body.collect().await.unwrap();+ assert_eq!(+ collected.trailers().and_then(|t| t.get("grpc-status")),+ Some(&"0".parse().unwrap())+ );+ assert_eq!(collected.to_bytes().as_ref(), b"payload");+ }++ #[tokio::test]+ async fn recorded_decline_reconstructs_the_same_typed_status() {+ use http_body_util::BodyExt;++ // A recorded decline: grpc-status 3 (InvalidArgument) in trailers.+ let envelope = GrpcResultEnvelope::Response {+ http_status: 200,+ headers: vec![("content-type".to_owned(), "application/grpc".to_owned())],+ body_b64: String::new(),+ trailers: Some(vec![+ ("grpc-message".to_owned(), "card declined".to_owned()),+ ("grpc-status".to_owned(), "3".to_owned()),+ ]),+ };+ assert!(envelope.is_err());++ let response = reconstruct_response(&envelope).unwrap();+ assert_eq!(response.status(), http::StatusCode::OK);+ let collected = response.into_body().collect().await.unwrap();+ let status = tonic::Status::from_header_map(collected.trailers().unwrap()).unwrap();+ assert_eq!(status.code(), tonic::Code::InvalidArgument);+ assert_eq!(status.message(), "card declined");+ }++ #[test]+ fn trailers_only_shape_is_preserved() {+ let mut headers = http::HeaderMap::new();+ headers.insert("grpc-status", "14".parse().unwrap());+ let envelope = GrpcResultEnvelope::from_response_parts(200, &headers, &[], None);+ assert!(envelope.is_err());+ let response = reconstruct_response(&envelope).unwrap();+ // Status stays in the HEADERS — no synthesized trailers frame.+ let status = tonic::Status::from_header_map(response.headers()).unwrap();+ assert_eq!(status.code(), tonic::Code::Unavailable);+ }++ #[cfg(feature = "dynamic_routing")]+ #[test]+ fn descriptor_decode_by_rpc_path() {+ use prost_reflect::prost::Message;++ let rpc = "/success_rate.SuccessRateCalculator/FetchSuccessRate";+ let (input, output) = descriptors::method_descriptors(rpc).unwrap();+ assert_eq!(input.full_name(), "success_rate.CalSuccessRateRequest");+ assert_eq!(output.full_name(), "success_rate.CalSuccessRateResponse");++ // Round-trip a request through the descriptor: set fields dynamically,+ // encode, decode back to proto3-JSON.+ let mut message = prost_reflect::DynamicMessage::new(input.clone());+ message.set_field_by_name("id", prost_reflect::Value::String("m1:gateway".to_owned()));+ message.set_field_by_name(+ "params",+ prost_reflect::Value::String("card&credit".to_owned()),+ );+ let wire = message.encode_to_vec();++ let json = descriptors::decode_unary_request(rpc, &frame(&wire)).unwrap();+ assert_eq!(json["id"], serde_json::json!("m1:gateway"));+ assert_eq!(json["params"], serde_json::json!("card&credit"));++ // Unknown schema (UCS) falls back to None — the wire-canonical path.+ assert!(descriptors::method_descriptors("/types.PaymentService/Authorize").is_none());+ }+}diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex 0731473e0e..572c5eba2a 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -21,33 +21,45 @@ use crate::{/// Result type for Dynamic Routingpub type UnifiedConnectorServiceResult<T> = CustomResult<T, UnifiedConnectorServiceError>;++/// The transport under every UCS service client. Under the `deja` feature it is+/// the gRPC egress boundary wrapper — every unary rpc (payment, refund, …) is+/// recorded/substituted at the wire level with rank-2 span-path identity;+/// otherwise it is the raw tonic channel. Threading this alias through the+/// client fields + their construction keeps the feature-off build byte-identical.+#[cfg(feature = "deja")]+pub type UcsChannel = super::deja_transport::DejaGrpcTransport<tonic::transport::Channel>;+/// The transport under every UCS service client (raw tonic channel; see the+/// `deja`-gated definition above for the recording/substituting variant).+#[cfg(not(feature = "deja"))]+pub type UcsChannel = tonic::transport::Channel;/// Contains the Unified Connector Service client#[derive(Debug, Clone)]pub struct UnifiedConnectorServiceClient {/// The Payment Service Client- pub payment_service_client: payments_grpc::payment_service_client::PaymentServiceClient<tonic::transport::Channel>,+ pub payment_service_client: payments_grpc::payment_service_client::PaymentServiceClient<UcsChannel>,/// The Refund Service Client- pub refund_service_client: payments_grpc::refund_service_client::RefundServiceClient<tonic::transport::Channel>,+ pub refund_service_client: payments_grpc::refund_service_client::RefundServiceClient<UcsChannel>,/// The Event Service Client- pub event_service_client: payments_grpc::event_service_client::EventServiceClient<tonic::transport::Channel>,+ pub event_service_client: payments_grpc::event_service_client::EventServiceClient<UcsChannel>,/// The Recurring Payment Service Client- pub recurring_payment_service_client: payments_grpc::recurring_payment_service_client::RecurringPaymentServiceClient<tonic::transport::Channel>,+ pub recurring_payment_service_client: payments_grpc::recurring_payment_service_client::RecurringPaymentServiceClient<UcsChannel>,/// The Dispute Service Client- pub dispute_service_client: payments_grpc::dispute_service_client::DisputeServiceClient<tonic::transport::Channel>,+ pub dispute_service_client: payments_grpc::dispute_service_client::DisputeServiceClient<UcsChannel>,/// The Payment Method Service Client- pub payment_method_service_client: payments_grpc::payment_method_service_client::PaymentMethodServiceClient<tonic::transport::Channel>,+ pub payment_method_service_client: payments_grpc::payment_method_service_client::PaymentMethodServiceClient<UcsChannel>,/// The Customer Service Client- pub customer_service_client: payments_grpc::customer_service_client::CustomerServiceClient<tonic::transport::Channel>,+ pub customer_service_client: payments_grpc::customer_service_client::CustomerServiceClient<UcsChannel>,/// The Merchant Authentication Service Clientpub merchant_authentication_service_client:- payments_grpc::merchant_authentication_service_client::MerchantAuthenticationServiceClient<tonic::transport::Channel>,+ payments_grpc::merchant_authentication_service_client::MerchantAuthenticationServiceClient<UcsChannel>,/// The Payment Method Authentication Service Clientpub payment_method_authentication_service_client:- payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient<tonic::transport::Channel>,+ payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient<UcsChannel>,/// The Payout Service Client- pub payout_service_client: payments_grpc::payout_service_client::PayoutServiceClient<tonic::transport::Channel>,+ pub payout_service_client: payments_grpc::payout_service_client::PayoutServiceClient<UcsChannel>,/// The Surcharge Service Client- pub surcharge_service_client: payments_grpc::surcharge_service_client::SurchargeServiceClient<tonic::transport::Channel>,+ pub surcharge_service_client: payments_grpc::surcharge_service_client::SurchargeServiceClient<UcsChannel>,}/// Contains the Unified Connector Service Client config@@ -188,7 +200,15 @@ macro_rules! build_grpc_client {let endpoint = tonic::transport::Channel::builder($uri.clone()).timeout($request_timeout.as_duration());match timeout($connection_timeout.as_duration(), endpoint.connect()).await {- Ok(Ok(channel)) => <$client>::new(channel),+ Ok(Ok(channel)) => {+ // deja: wrap the UCS channel in the gRPC egress boundary at its+ // construction site so every unary rpc is recorded/substituted at+ // the wire level (rank-2 identity). Feature-off passes the raw+ // channel unchanged.+ #[cfg(feature = "deja")]+ let channel = $crate::grpc_client::deja_transport::DejaGrpcTransport::new(channel);+ <$client>::new(channel)+ }Ok(Err(err)) => {router_env::logger::error!("Failed to connect to Unified Connector Service for {}: {:?}",@@ -240,7 +260,7 @@ impl UnifiedConnectorServiceClient {let payment_service_client = build_grpc_client!(payments_grpc::payment_service_client::PaymentServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"payment_service_client",uri,@@ -250,7 +270,7 @@ impl UnifiedConnectorServiceClient {let refund_service_client = build_grpc_client!(payments_grpc::refund_service_client::RefundServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"refund_service_client",uri,@@ -260,7 +280,7 @@ impl UnifiedConnectorServiceClient {let event_service_client = build_grpc_client!(payments_grpc::event_service_client::EventServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"event_service_client",uri,@@ -270,7 +290,7 @@ impl UnifiedConnectorServiceClient {let recurring_payment_service_client = build_grpc_client!(payments_grpc::recurring_payment_service_client::RecurringPaymentServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"recurring_payment_service_client",uri,@@ -280,7 +300,7 @@ impl UnifiedConnectorServiceClient {let dispute_service_client = build_grpc_client!(payments_grpc::dispute_service_client::DisputeServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"dispute_service_client",uri,@@ -290,7 +310,7 @@ impl UnifiedConnectorServiceClient {let payment_method_service_client = build_grpc_client!(payments_grpc::payment_method_service_client::PaymentMethodServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"payment_method_service_client",uri,@@ -300,7 +320,7 @@ impl UnifiedConnectorServiceClient {let customer_service_client = build_grpc_client!(payments_grpc::customer_service_client::CustomerServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"customer_service_client",uri,@@ -309,7 +329,7 @@ impl UnifiedConnectorServiceClient {);let merchant_authentication_service_client = build_grpc_client!(- payments_grpc::merchant_authentication_service_client::MerchantAuthenticationServiceClient<tonic::transport::Channel>,+ payments_grpc::merchant_authentication_service_client::MerchantAuthenticationServiceClient<UcsChannel>,"merchant_authentication_service_client",uri,connection_timeout,@@ -317,7 +337,7 @@ impl UnifiedConnectorServiceClient {);let payment_method_authentication_service_client = build_grpc_client!(- payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient<tonic::transport::Channel>,+ payments_grpc::payment_method_authentication_service_client::PaymentMethodAuthenticationServiceClient<UcsChannel>,"payment_method_authentication_service_client",uri,connection_timeout,@@ -326,7 +346,7 @@ impl UnifiedConnectorServiceClient {let payout_service_client = build_grpc_client!(payments_grpc::payout_service_client::PayoutServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"payout_service_client",uri,@@ -336,7 +356,7 @@ impl UnifiedConnectorServiceClient {let surcharge_service_client = build_grpc_client!(payments_grpc::surcharge_service_client::SurchargeServiceClient<- tonic::transport::Channel,+ UcsChannel,>,"surcharge_service_client",uri,diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rsindex cd52b95516..2272f66242 100644--- a/crates/external_services/src/http_client.rs+++ b/crates/external_services/src/http_client.rs@@ -12,6 +12,10 @@ pub mod client;pub mod metrics;/// request modulepub mod request;++#[cfg(feature = "deja")]+mod boundary;+use std::{error::Error, time::Duration};pub use common_utils::request::{ContentType, Method, RequestBuilder};@@ -63,6 +67,21 @@ pub fn serialize_to_xml_bytes<T: serde::Serialize>(}#[allow(missing_docs)]+#[cfg_attr(+ feature = "deja",+ deja::http(outgoing,+ component = "external_services::http_client",+ operation = "send_request",+ correlation = boundary::request_id(&request),+ // The deja handoff: expose the Secret-wrapped payload so the tape+ // records full fidelity (Secret only redacts Debug/log output).+ args = hyperswitch_masking::ExposeInterface::expose(boundary::request_args(&request, option_timeout_secs)),+ // Rebuild the recorded reqwest::Response (status+headers+body) so the+ // outgoing call (e.g. Stripe) is served from the lookup table with no+ // network. A recorded error reconstructs to None -> falls through to live.+ codec = boundary::HttpResponseCodec,+ )+)]#[instrument(skip_all)]pub async fn send_request(client_proxy: &Proxy,@@ -196,8 +215,7 @@ pub async fn send_request(// and written to at the same time the server is deciding to close the connection.// Since hyper already wrote some of the request,// it can’t really retry it automatically on a new connection, since the server may have acted already- match response {- Ok(response) => Ok(response),+ let response = match response {Err(error)if error.current_context() == &HttpClientError::ConnectionClosedIncompleteMessage =>{@@ -220,7 +238,22 @@ pub async fn send_request(}}}- err @ Err(_) => err,+ response => response,+ };++ #[cfg(feature = "deja")]+ {+ match response {+ Ok(response) if boundary::is_active() => {+ boundary::response_with_captured_body(response).await+ }+ response => response,+ }+ }++ #[cfg(not(feature = "deja"))]+ {+ response}}diff --git a/crates/external_services/src/http_client/boundary.rs b/crates/external_services/src/http_client/boundary.rsnew file mode 100644index 0000000000..16dae6ceac--- /dev/null+++ b/crates/external_services/src/http_client/boundary.rs@@ -0,0 +1,236 @@+use common_utils::{+ errors::CustomResult,+ request::{Request, RequestContent},+};+use deja::DejaHook;+use error_stack::ResultExt;+use hyperswitch_interfaces::errors::HttpClientError;+use hyperswitch_masking::{ExposeInterface, Maskable, PeekInterface, Secret};+use reqwest::ResponseBuilderExt;+use serde_json::json;++/// Extension key used to smuggle the captured response body out of the+/// `send_request` function so that the boundary codec can report it without+/// consuming the response stream.+pub(super) struct CapturedResponseBody(pub(super) bytes::Bytes);++pub(super) fn is_active() -> bool {+ deja::global_hook_from_env().is_some_and(|hook| hook.is_active())+}++pub(super) async fn response_with_captured_body(+ response: reqwest::Response,+) -> CustomResult<reqwest::Response, HttpClientError> {+ // Eagerly read the response body so the boundary result extractor can+ // report it without consuming the stream a second time. The body is then+ // cloned: one copy is rebuilt into a new reqwest::Response as a reusable+ // Body, the other is stashed in http::Extensions so `response_result` can+ // read it.+ let status = response.status();+ let headers = response.headers().clone();+ let version = response.version();+ let url = response.url().clone();+ let body_bytes = response+ .bytes()+ .await+ .change_context(HttpClientError::ResponseDecodingFailed)+ .attach_printable("Failed to read response body for boundary capture")?;++ let mut builder = http::Response::builder()+ .status(status)+ .version(version)+ .url(url);+ for (key, value) in &headers {+ builder = builder.header(key, value);+ }+ let mut http_response = builder.body(body_bytes.clone()).map_err(|_| {+ error_stack::report!(HttpClientError::UnexpectedState)+ .attach_printable("Failed to rebuild HTTP response")+ })?;+ http_response+ .extensions_mut()+ .insert(CapturedResponseBody(body_bytes));++ Ok(reqwest::Response::from(http_response))+}++pub(super) fn request_id(request: &Request) -> Option<String> {+ request.headers.iter().find_map(|(key, value)| {+ if key.eq_ignore_ascii_case(common_utils::consts::X_REQUEST_ID) {+ Some(header_value(value))+ } else {+ None+ }+ })+}++pub(super) fn request_args(+ request: &Request,+ timeout_secs: Option<u64>,+) -> Secret<serde_json::Value> {+ // Header storage iterates in non-deterministic (HashMap) order, so the raw+ // sequence differs between record and replay even when the header SET is+ // identical. The args matcher compares serialized JSON arrays+ // order-sensitively, so an unsorted list misses the lookup and the outgoing+ // call falls through to a LIVE network request. Sort by (key, value) to+ // produce a canonical, byte-stable representation. (Computed outside the+ // json! macro, which cannot parse a block containing type annotations.)+ let mut headers: Vec<(String, String)> = request+ .headers+ .iter()+ .map(|(key, value)| (key.to_string(), header_value(value)))+ .collect();+ headers.sort();+ let headers: Vec<serde_json::Value> = headers+ .into_iter()+ .map(|(key, value)| json!({ "key": key, "value": value }))+ .collect();+ Secret::new(json!({+ "method": format!("{:?}", request.method),+ "url": request.url.as_str(),+ "request_id": request_id(request),+ "headers": headers,+ "query_params": request.query_params.clone(),+ "timeout_secs": timeout_secs,+ "request_body": request.body.as_ref().map(request_body),+ "client_tls": {+ "certificate": request.certificate.is_some(),+ "certificate_key": request.certificate_key.is_some(),+ "ca_certificate": request.ca_certificate.is_some(),+ },+ }))+}++// Captured payloads travel as `Secret<serde_json::Value>` between helpers so+// their `Debug` output is redacted (response bodies/headers can carry PII or+// credentials); they are `.expose()`d only at the deja handoff, where the tape+// keeps full fidelity.+fn captured_body_json(response: &reqwest::Response) -> Secret<serde_json::Value> {+ Secret::new(match response.extensions().get::<CapturedResponseBody>() {+ Some(CapturedResponseBody(bytes)) => deja::http::body(bytes),+ None => deja::http::missing_body("response body not captured (missing extension)"),+ })+}++fn response_headers_json(response: &reqwest::Response) -> Secret<serde_json::Value> {+ let mut map = serde_json::Map::new();+ for (key, value) in response.headers() {+ if let Ok(value) = value.to_str() {+ map.insert(+ key.as_str().to_string(),+ serde_json::Value::String(value.to_string()),+ );+ }+ }+ Secret::new(serde_json::Value::Object(map))+}++pub(super) fn response_result(+ result: &CustomResult<reqwest::Response, HttpClientError>,+) -> (Secret<serde_json::Value>, bool) {+ (+ Secret::new(match result {+ Ok(response) => json!({+ "status": response.status().as_u16(),+ "reason": response.status().canonical_reason(),+ "response_headers": response_headers_json(response).expose(),+ "response_body": captured_body_json(response).expose(),+ }),+ Err(error) => json!({+ "error": format!("{error:?}"),+ "response_body": {+ "captured": false,+ },+ }),+ }),+ result.is_err(),+ )+}++pub(super) struct HttpResponseCodec;++impl deja::codec::ReplayCodec for HttpResponseCodec {+ type Value = CustomResult<reqwest::Response, HttpClientError>;++ fn capture(value: &Self::Value) -> (serde_json::Value, bool) {+ let (payload, is_error) = response_result(value);+ // The deja handoff: the tape records the full-fidelity value.+ (payload.expose(), is_error)+ }++ fn reconstruct(recorded: serde_json::Value) -> Option<Self::Value> {+ replay_response(&recorded).map(Ok)+ }+}++/// Replay: reconstruct a `reqwest::Response` from a recorded `response_result`+/// payload (`{status, response_headers, response_body: {raw_bytes: [...]}}`).+///+/// A recorded SUCCESS reconstructs verbatim: connectors read status, headers+/// and body bytes, and all three come from the tape, so that call touches no+/// network.+///+/// A recorded ERROR carries no `status` field and reconstructs to `None`, which+/// the boundary treats as a lookup miss and answers by executing LIVE. Replaying+/// a request whose connector call failed therefore issues a real outbound request+/// to the real endpoint. This is the current Ok-only replay policy: replay is+/// egress-free only for as long as every recorded call succeeded, so it must not+/// be relied on as an egress guarantee.+pub(super) fn replay_response(recorded: &serde_json::Value) -> Option<reqwest::Response> {+ let status_code = u16::try_from(recorded.get("status")?.as_u64()?).ok()?;+ let status = http::StatusCode::from_u16(status_code).ok()?;++ let raw_bytes: Vec<u8> = recorded+ .get("response_body")+ .and_then(|body| body.get("raw_bytes"))+ .and_then(|value| value.as_array())+ .map(|array| array.iter().filter_map(byte_from_json).collect())+ .unwrap_or_default();++ let mut builder = http::Response::builder().status(status);+ if let Some(headers) = recorded.get("response_headers").and_then(|h| h.as_object()) {+ for (name, value) in headers {+ if let Some(value) = value.as_str() {+ builder = builder.header(name.as_str(), value);+ }+ }+ }+ let http_response = builder.body(bytes::Bytes::from(raw_bytes)).ok()?;+ Some(reqwest::Response::from(http_response))+}++fn byte_from_json(value: &serde_json::Value) -> Option<u8> {+ value.as_u64().and_then(|byte| byte.try_into().ok())+}++fn header_value(value: &Maskable<String>) -> String {+ match value {+ Maskable::Masked(value) => value.peek().to_string(),+ Maskable::Normal(value) => value.clone(),+ }+}++fn request_body(body: &RequestContent) -> serde_json::Value {+ match body {+ RequestContent::RawBytes(bytes) => {+ let mut body = deja::http::body(bytes);+ if let serde_json::Value::Object(ref mut object) = body {+ object.insert(+ "kind".to_string(),+ serde_json::Value::String("RawBytesRequestBody".to_string()),+ );+ }+ body+ }+ _ => {+ let value = body.get_inner_value();+ let text = value.peek();+ let kind = format!("{body:?}");+ let mut captured = deja::http::body(text.as_bytes());+ if let serde_json::Value::Object(ref mut object) = captured {+ object.insert("kind".to_string(), serde_json::Value::String(kind));+ }+ captured+ }+ }+}diff --git a/crates/external_services/src/superposition.rs b/crates/external_services/src/superposition.rsindex 4ac7c8622e..5760bbb376 100644--- a/crates/external_services/src/superposition.rs+++ b/crates/external_services/src/superposition.rs@@ -38,6 +38,170 @@ pub use superposition_types::api::{pub use self::types::{ConfigContext, SuperpositionClientConfig, SuperpositionError, ToDocument};use crate::config_metrics;+// ── Deja record/replay boundary for Superposition READS ──────────────────────+// Wraps the read methods so each read is CAPTURED on record and SUBSTITUTED from+// the tape on replay — no live Superposition service is consulted in replay. The+// WHOLE `CustomResult<T, SuperpositionError>` round-trips ("recording threw ⇒+// replay throws"). Identity is rank-2 span-path (no call-site id). A genuine tape+// MISS returns `Err(SuperpositionError)` (via `dispatch_async_or_miss`) so the+// caller's `fetch_db_config` ladder degrades to DB/default and replay progresses,+// instead of the egress fail-stop. Reads are deja's per-request business config;+// writes are deliberately NOT wrapped (they are leaving the OLTP path).+#[cfg(feature = "deja")]+mod deja_boundary {+ use error_stack::report;++ use super::{ConfigContext, CustomResult, SuperpositionError};++ pub(super) const BOUNDARY: &str = "superposition";+ pub(super) const COMPONENT: &str = "SuperpositionClient";++ /// Serialize the whole `CustomResult<T, SuperpositionError>` for the tape:+ /// the `Ok` value losslessly, or the error's current context (which the+ /// caller's recovery branches on). Report attachments do not round-trip.+ pub(super) fn capture<T: serde::Serialize>(+ result: &CustomResult<T, SuperpositionError>,+ ) -> (serde_json::Value, bool) {+ match result {+ Ok(value) => (+ serde_json::json!({+ "result": "Ok",+ "value": serde_json::to_value(value).unwrap_or(serde_json::Value::Null),+ }),+ false,+ ),+ Err(err) => (+ serde_json::json!({+ "result": "Err",+ "error": serde_json::to_value(err.current_context())+ .unwrap_or(serde_json::Value::Null),+ }),+ true,+ ),+ }+ }++ /// Rebuild the typed `CustomResult` from a recorded tape value. A recorded+ /// `Err` replays as `Err(report!(E))` carrying the SAME typed context.+ pub(super) fn reconstruct<T: serde::de::DeserializeOwned>(+ recorded: serde_json::Value,+ ) -> deja::__private::Reconstructed<CustomResult<T, SuperpositionError>> {+ use deja::__private::Reconstructed;+ let Some(object) = recorded.as_object() else {+ return Reconstructed::Failed;+ };+ match object.get("result").and_then(serde_json::Value::as_str) {+ Some("Ok") => match object+ .get("value")+ .cloned()+ .map(serde_json::from_value::<T>)+ {+ Some(Ok(value)) => Reconstructed::Value(Ok(value)),+ _ => Reconstructed::Failed,+ },+ Some("Err") => match object+ .get("error")+ .cloned()+ .map(serde_json::from_value::<SuperpositionError>)+ {+ Some(Ok(error)) => Reconstructed::Value(Err(report!(error))),+ _ => Reconstructed::Failed,+ },+ _ => Reconstructed::Failed,+ }+ }++ /// Serialize a `ConfigContext` (+ targeting key) into the boundary args image+ /// used for replay matching. The config key/method go in alongside.+ pub(super) fn args_image(+ method: &str,+ key: Option<&str>,+ context: Option<&ConfigContext>,+ targeting_key: Option<&String>,+ ) -> serde_json::Value {+ serde_json::json!({+ "method": method,+ "key": key,+ "context": context.map(|c| c.values.clone()),+ "targeting_key": targeting_key,+ })+ }++ /// Run one Superposition read through the deja boundary. `run` performs the+ /// live read; on a substitute HIT it is skipped (tape value served), on a+ /// genuine MISS `on_miss` yields a recoverable `Err`.+ pub(super) async fn read<T, Fut, Run>(+ operation: &'static str,+ args: serde_json::Value,+ caller: &'static core::panic::Location<'static>,+ run: Run,+ ) -> CustomResult<T, SuperpositionError>+ where+ Run: FnOnce() -> Fut,+ Fut: core::future::Future<Output = CustomResult<T, SuperpositionError>>,+ T: serde::Serialize + serde::de::DeserializeOwned,+ {+ // Engage only when a deja hook is live (record or replay); else pure+ // passthrough — no observation, no allocation.+ if !deja::__private::observation_is_active() {+ return run().await;+ }++ let correlation = deja::current_correlation_id();+ let scope = format!("superposition::{operation}");+ // Rank-2 span-path identity: NO explicit call-site id (rank-1 needs a+ // call-site and is banned), so resolution uses the ambient span-path+ // (rank 2), with the syntactic hash of the scope as the rank-3 fallback.+ let identity = deja::__private::CallsiteIdentity {+ version: 1,+ source: deja::__private::CallsiteSource::SyntacticHash,+ id: None,+ scope: Some(scope.clone()),+ occurrence: deja::__private::next_boundary_occurrence(+ correlation.as_deref(),+ deja::__private::CallsiteSource::SyntacticHash,+ Some(&scope),+ ),+ caller_function: Some(operation.to_string()),+ lexical_path: Some(scope.clone()),+ syntax_hash: Some(deja::__private::stable_callsite_hash(&scope)),+ span_path: deja::__private::current_span_path(),+ };++ let semantics = deja::__private::BoundarySemantics {+ replay_strategy: deja::ReplayStrategy::Substitute,+ kind: Some(BOUNDARY.to_string()),+ declaration: Some(+ deja::BoundaryDeclaration::default().operation(deja::OperationKind::ExternalCall),+ ),+ };+ let spec = deja::__private::BoundarySpec::with_semantics(+ BOUNDARY, COMPONENT, operation, semantics,+ );+ let observation = deja::__private::CrossingObservation::with_correlation(+ spec,+ identity,+ caller,+ correlation,+ );++ deja::__private::dispatch_async_or_miss(+ observation,+ move || args,+ run,+ reconstruct::<T>,+ capture::<T>,+ move || {+ Err(report!(SuperpositionError::NotFound(format!(+ "deja replay: no recorded Superposition value for `{operation}` (novel \+ config read); caller falls back to DB/default"+ ))))+ },+ )+ .await+ }+}+/// Convert an `aws_smithy_types::Document` to a `serde_json::Value`.pub fn document_to_value(doc: Document) -> serde_json::Value {match doc {@@ -600,18 +764,50 @@ impl SuperpositionClient {) -> CustomResult<T, SuperpositionError>whereopen_feature::Client: GetValue<T>,+ // Deja captures the whole `CustomResult<T, _>` at the read boundary; the+ // GetValue impls (bool/String/i64/u32/f64/Value) all satisfy these.+ T: serde::Serialize + serde::de::DeserializeOwned,{- let evaluation_context = self.build_evaluation_context(context, targeting_key);- let type_name = std::any::type_name::<T>();-- self.client- .get_value(key, &evaluation_context)+ #[cfg(feature = "deja")]+ {+ let args =+ deja_boundary::args_image("get_config_value", Some(key), context, targeting_key);+ let key = key.to_owned();+ let context = context.cloned();+ let targeting_key = targeting_key.cloned();+ deja_boundary::read(+ "get_config_value",+ args,+ core::panic::Location::caller(),+ move || async move {+ let evaluation_context =+ self.build_evaluation_context(context.as_ref(), targeting_key.as_ref());+ let type_name = std::any::type_name::<T>();+ self.client+ .get_value(&key, &evaluation_context)+ .await+ .map_err(|e| {+ report!(SuperpositionError::ClientError(format!(+ "Failed to get {type_name} value for key '{key}': {e:?}"+ )))+ })+ },+ ).await- .map_err(|e| {- report!(SuperpositionError::ClientError(format!(- "Failed to get {type_name} value for key '{key}': {e:?}"- )))- })+ }+ #[cfg(not(feature = "deja"))]+ {+ let evaluation_context = self.build_evaluation_context(context, targeting_key);+ let type_name = std::any::type_name::<T>();+ self.client+ .get_value(key, &evaluation_context)+ .await+ .map_err(|e| {+ report!(SuperpositionError::ClientError(format!(+ "Failed to get {type_name} value for key '{key}': {e:?}"+ )))+ })+ }}/// Resolve full configuration from Superposition@@ -626,15 +822,43 @@ impl SuperpositionClient {context: Option<&ConfigContext>,targeting_key: Option<&String>,) -> CustomResult<Map<String, serde_json::Value>, SuperpositionError> {- let evaluation_context = self.build_evaluation_context(context, targeting_key);- self.provider- .resolve_all_features(evaluation_context)+ #[cfg(feature = "deja")]+ {+ let args =+ deja_boundary::args_image("resolve_full_config", None, context, targeting_key);+ let context = context.cloned();+ let targeting_key = targeting_key.cloned();+ deja_boundary::read(+ "resolve_full_config",+ args,+ core::panic::Location::caller(),+ move || async move {+ let evaluation_context =+ self.build_evaluation_context(context.as_ref(), targeting_key.as_ref());+ self.provider+ .resolve_all_features(evaluation_context)+ .await+ .map_err(|e| {+ report!(SuperpositionError::ProviderError(format!(+ "Failed to resolve full config: {e:?}"+ )))+ })+ },+ ).await- .map_err(|e| {- report!(SuperpositionError::ProviderError(format!(- "Failed to resolve full config: {e:?}"- )))- })+ }+ #[cfg(not(feature = "deja"))]+ {+ let evaluation_context = self.build_evaluation_context(context, targeting_key);+ self.provider+ .resolve_all_features(evaluation_context)+ .await+ .map_err(|e| {+ report!(SuperpositionError::ProviderError(format!(+ "Failed to resolve full config: {e:?}"+ )))+ })+ }}/// Get cached configuration from Superposition@@ -650,22 +874,61 @@ impl SuperpositionClient {prefix_filter: Option<Vec<String>>,dimension_filter: Option<Map<String, serde_json::Value>>,) -> CustomResult<superposition_types::Config, SuperpositionError> {- use superposition_provider::data_source::SuperpositionDataSource;- let response = self- .provider- .fetch_filtered_config(dimension_filter, prefix_filter, None)+ #[cfg(feature = "deja")]+ {+ let args = serde_json::json!({+ "method": "get_cached_config",+ "prefix_filter": prefix_filter.clone(),+ "dimension_filter": dimension_filter.clone(),+ });+ deja_boundary::read(+ "get_cached_config",+ args,+ core::panic::Location::caller(),+ move || async move {+ use superposition_provider::data_source::SuperpositionDataSource;+ let response = self+ .provider+ .fetch_filtered_config(dimension_filter, prefix_filter, None)+ .await+ .map_err(|e| {+ report!(SuperpositionError::ProviderError(format!(+ "Failed to get cached config: {e:?}"+ )))+ })?;+ match response {+ superposition_provider::data_source::FetchResponse::Data(data) => {+ Ok(data.data)+ }+ superposition_provider::data_source::FetchResponse::NotModified => {+ Err(report!(SuperpositionError::ProviderError(+ "Config not modified but no data available".to_string()+ )))+ }+ }+ },+ ).await- .map_err(|e| {- report!(SuperpositionError::ProviderError(format!(- "Failed to get cached config: {e:?}"- )))- })?;- match response {- superposition_provider::data_source::FetchResponse::Data(data) => Ok(data.data),- superposition_provider::data_source::FetchResponse::NotModified => {- Err(report!(SuperpositionError::ProviderError(- "Config not modified but no data available".to_string()- )))+ }+ #[cfg(not(feature = "deja"))]+ {+ use superposition_provider::data_source::SuperpositionDataSource;+ let response = self+ .provider+ .fetch_filtered_config(dimension_filter, prefix_filter, None)+ .await+ .map_err(|e| {+ report!(SuperpositionError::ProviderError(format!(+ "Failed to get cached config: {e:?}"+ )))+ })?;+ match response {+ superposition_provider::data_source::FetchResponse::Data(data) => Ok(data.data),+ superposition_provider::data_source::FetchResponse::NotModified => {+ Err(report!(SuperpositionError::ProviderError(+ "Config not modified but no data available".to_string()+ )))+ }}}}@@ -750,8 +1013,15 @@ pub trait WritableConfig {/// Each config type implements this trait to define how its value should be/// retrieved from Superposition.pub trait Config {- /// The output type of this configuration- type Output: Default + Clone;+ /// The output type of this configuration.+ ///+ /// `Serialize + DeserializeOwned` are required because `get_config_value`+ /// (which `fetch` calls) captures the whole `CustomResult<Output, _>` at the+ /// deja read boundary. Declaring the bound on the associated type propagates+ /// it to `fetch` and to every generic `C: Config` caller (e.g. router's+ /// `fetch_db_config`) without scattering per-call-site where-clauses. All+ /// real Output types (bool/String/i64/u32/f64/serde_json::Value) satisfy it.+ type Output: Default + Clone + serde::Serialize + serde::de::DeserializeOwned;/// The type used as the targeting key for experiment traffic splittingtype TargetingKey: TargetingKey + Send + Sync;diff --git a/crates/external_services/src/superposition/types.rs b/crates/external_services/src/superposition/types.rsindex 5534d7c92e..970e3ed101 100644--- a/crates/external_services/src/superposition/types.rs+++ b/crates/external_services/src/superposition/types.rs@@ -103,6 +103,11 @@ impl Default for SuperpositionClientConfig {/// Errors that can occur when using Superposition#[derive(Debug, thiserror::Error)]+// Deja records the WHOLE `CustomResult<T, SuperpositionError>` at the read+// boundary ("recording threw ⇒ replay throws"), so the error must round-trip.+// Every variant is `Variant(String)` → trivially (de)serializable. Feature-gated+// so the release build (deja off) keeps the error type dependency-lean.+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]pub enum SuperpositionError {/// Error initializing the Superposition client#[error("Failed to initialize Superposition client: {0}")]diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rsindex 4d76517a62..5e49dd865d 100644--- a/crates/hyperswitch_domain_models/src/type_encryption.rs+++ b/crates/hyperswitch_domain_models/src/type_encryption.rs@@ -1309,6 +1309,8 @@ pub enum CryptoOutput<T: Clone, S: hyperswitch_masking::Strategy<T>> {BatchOperation(FxHashMap<String, crypto::Encryptable<Secret<T, S>>>),}+// deja: intentionally NOT a boundary — see `docs/design/deja-non-boundaries.md`.+//// Do not remove the `skip_all` as the key would be logged otherwise#[instrument(skip_all, fields(table = table_name))]pub async fn crypto_operation<T: Clone + Send, S: hyperswitch_masking::Strategy<T>>(diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.tomlindex 81aae32952..3a36cbe45a 100644--- a/crates/redis_interface/Cargo.toml+++ b/crates/redis_interface/Cargo.toml@@ -35,7 +35,7 @@ fred = { version = "8.0.6", optional = true, features = [# First party cratescommon_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }-deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false, features = ["error-stack"] }router_env = { version = "0.1.0", path = "../router_env", optional = true }[dev-dependencies]diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rsindex 10cd6223c3..f230c51e6f 100644--- a/crates/redis_interface/src/errors.rs+++ b/crates/redis_interface/src/errors.rs@@ -1,5 +1,10 @@//! Errors specific to this custom redis interface+// Deja replay reconstructs a recorded redis error as the SAME typed context the+// recording threw ("recording threw ⇒ replay throws"); the serde derives give+// the variants a lossless wire form (variant-name string; `InvalidConfiguration`+// carries its String payload).+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]#[derive(Debug, thiserror::Error, PartialEq)]pub enum RedisError {#[error("Invalid Redis configuration: {0}")]diff --git a/crates/redis_interface/src/metrics.rs b/crates/redis_interface/src/metrics.rsindex 5284593cd8..f4f37c2da1 100644--- a/crates/redis_interface/src/metrics.rs+++ b/crates/redis_interface/src/metrics.rs@@ -15,6 +15,7 @@ pub(crate) enum RedisOperation {SetKey,SetKeyWithoutModifyingTtl,SetKeyWithExpiry,+ #[cfg(not(feature = "deja"))]SerializeAndSetKeyWithExpiry,SetMultipleKeysIfNotExist,SetKeyIfNotExistsWithExpiry,diff --git a/crates/redis_interface/src/module/fred/commands.rs b/crates/redis_interface/src/module/fred/commands.rsindex 9b093f0e54..15a248756b 100644--- a/crates/redis_interface/src/module/fred/commands.rs+++ b/crates/redis_interface/src/module/fred/commands.rs@@ -31,15 +31,112 @@ use crate::{},};+// Deja: serde-native proxy mirror of `fred::types::RedisValue`.+//+// The concrete proxy lets replay substitute generic Redis reads without adding+// serde bounds to public `FromRedis` APIs.+#[cfg(feature = "deja")]+#[derive(serde::Serialize, serde::Deserialize)]+enum DejaRedisValue {+ Null,+ Boolean(bool),+ Integer(i64),+ Double(f64),+ String(String),+ Bytes(Vec<u8>),+ Array(Vec<Self>),+ Map(Vec<(Self, Self)>),+ Queued,+}++#[cfg(feature = "deja")]+impl From<RedisValue> for DejaRedisValue {+ fn from(v: RedisValue) -> Self {+ use fred::types::RedisValue as R;+ match v {+ R::Null => Self::Null,+ R::Boolean(b) => Self::Boolean(b),+ R::Integer(i) => Self::Integer(i),+ R::Double(d) => Self::Double(d),+ R::String(s) => Self::String(s.to_string()),+ R::Bytes(b) => Self::Bytes(b.to_vec()),+ R::Queued => Self::Queued,+ R::Array(a) => Self::Array(a.into_iter().map(Self::from).collect()),+ R::Map(m) => Self::Map(+ m.inner()+ .into_iter()+ .map(|(k, val)| (Self::from(R::from(k)), Self::from(val)))+ .collect(),+ ),+ }+ }+}++#[cfg(feature = "deja")]+impl TryFrom<DejaRedisValue> for RedisValue {+ type Error = fred::error::RedisError;++ fn try_from(v: DejaRedisValue) -> Result<Self, Self::Error> {+ match v {+ DejaRedisValue::Null => Ok(Self::Null),+ DejaRedisValue::Boolean(b) => Ok(Self::Boolean(b)),+ DejaRedisValue::Integer(i) => Ok(Self::Integer(i)),+ DejaRedisValue::Double(d) => Ok(Self::Double(d)),+ DejaRedisValue::String(s) => Ok(Self::String(s.into())),+ DejaRedisValue::Bytes(b) => Ok(Self::Bytes(b.into())),+ DejaRedisValue::Queued => Ok(Self::Queued),+ DejaRedisValue::Array(a) => Ok(Self::Array(+ a.into_iter()+ .map(Self::try_from)+ .collect::<Result<Vec<_>, _>>()?,+ )),+ DejaRedisValue::Map(m) => {+ let pairs = m+ .into_iter()+ .map(|(k, val)| Ok((Self::try_from(k)?, Self::try_from(val)?)))+ .collect::<Result<Vec<_>, Self::Error>>()?;+ pairs.try_into().map(Self::Map)+ }+ }+ }+}+impl super::RedisConnectionPool {pub fn add_prefix(&self, key: &str) -> String {- if self.key_prefix.is_empty() {+ let physical = if self.key_prefix.is_empty() {key.to_string()} else {format!("{}:{}", self.key_prefix, key)+ };+ // Deja replay isolation: during REPLAY, namespace every physical key+ // by the active correlation so each test case's store is isolated — no+ // cross-case collisions and no read-modify-write double-apply, which is+ // what makes it safe to Execute stateful redis ops against the seeded+ // store. The harness seeds each correlation under the same+ // `{correlation}:{physical}` namespace. Inert during record and when no+ // correlation is in scope, so recorded keys and normal operation are+ // unchanged (and for Substitute ops the real command never runs anyway).+ #[cfg(feature = "deja")]+ if let Some(corr) = deja::replay_key_namespace() {+ return format!("{corr}:{physical}");}+ physical}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SET",+ "has_ttl": true,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError>where@@ -60,6 +157,19 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::SetFailed)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key_without_modifying_ttl",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SET_KEEP_TTL",+ })+ },+ )+ )]pub async fn set_key_without_modifying_ttl<V>(&self,key: &RedisKey,@@ -83,6 +193,18 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::SetFailed)}+ #[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_multiple_keys_if_not_exist",+ args = {+ serde_json::json!({+ "command": "MSETNX",+ })+ },+ )+ )]pub async fn set_multiple_keys_if_not_exist<K, V>(&self,key_value_pairs: &[(K, V)],@@ -172,33 +294,61 @@ impl super::RedisConnectionPool {.encode_to_vec().change_context(errors::RedisError::JsonSerializationFailed)?;- track_redis_call(- RedisOperation::SerializeAndSetKeyWithExpiry,- self.pool.set(- key.tenant_aware_key(self),- serialized.as_slice(),- Some(Expiration::EX(seconds)),- None,- false,- ),- )- .await- .change_context(errors::RedisError::SetExFailed)+ #[cfg(feature = "deja")]+ {+ self.set_key_with_expiry(key, serialized.as_slice(), seconds)+ .await+ }++ #[cfg(not(feature = "deja"))]+ {+ track_redis_call(+ RedisOperation::SerializeAndSetKeyWithExpiry,+ self.pool.set(+ key.tenant_aware_key(self),+ serialized.as_slice(),+ Some(Expiration::EX(seconds)),+ None,+ false,+ ),+ )+ .await+ .change_context(errors::RedisError::SetExFailed)+ }}+ // Deja hermetic boundary for GET.+ //+ // The boundary lives on this inner method, which fetches the RAW redis reply+ // (`fred::types::RedisValue`) and mirrors it into the serde-native+ // `DejaRedisValue`. Because the recorded/replayed type is concrete and+ // serde-native, the typed `ResultCodec` works without leaking a serde bound+ // onto the public `get_key<V>`.+ #[cfg(feature = "deja")]#[instrument(level = "DEBUG", skip(self))]- pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>- where- V: FromRedis + Unpin + Send + 'static,- {+ #[deja::redis(+ operation = "get_key",+ codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ state_read = key.tenant_aware_key(self),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "GET",+ })+ },+ )]+ async fn get_key_raw(+ &self,+ key: &RedisKey,+ ) -> CustomResult<DejaRedisValue, errors::RedisError> {match track_redis_call(RedisOperation::GetKey,- self.pool.get(key.tenant_aware_key(self)),+ self.pool.get::<RedisValue, _>(key.tenant_aware_key(self)),).await.change_context(errors::RedisError::GetFailed){- Ok(v) => Ok(v),+ Ok(v) => Ok(DejaRedisValue::from(v)),Err(_err) => {#[cfg(not(feature = "multitenancy_fallback"))]{@@ -209,10 +359,55 @@ impl super::RedisConnectionPool {{track_redis_call(RedisOperation::GetKey,- self.pool.get(key.tenant_unaware_key(self)),+ self.pool.get::<RedisValue, _>(key.tenant_unaware_key(self)),).await.change_context(errors::RedisError::GetFailed)+ .map(DejaRedisValue::from)+ }+ }+ }+ }++ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>+ where+ V: FromRedis + Unpin + Send + 'static,+ {+ #[cfg(feature = "deja")]+ {+ let raw = self.get_key_raw(key).await?;+ let value: RedisValue = raw.try_into().map_err(|err: fred::error::RedisError| {+ report!(err).change_context(errors::RedisError::GetFailed)+ })?;+ V::from_value(value).change_context(errors::RedisError::GetFailed)+ }++ #[cfg(not(feature = "deja"))]+ {+ match track_redis_call(+ RedisOperation::GetKey,+ self.pool.get(key.tenant_aware_key(self)),+ )+ .await+ .change_context(errors::RedisError::GetFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }++ #[cfg(feature = "multitenancy_fallback")]+ {+ track_redis_call(+ RedisOperation::GetKey,+ self.pool.get(key.tenant_unaware_key(self)),+ )+ .await+ .change_context(errors::RedisError::GetFailed)+ }}}}@@ -287,6 +482,29 @@ impl super::RedisConnectionPool {}}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "get_multiple_keys",+ read_set = keys.iter().map(|key| key.tenant_aware_key(self)).collect::<Vec<_>>(),+ args = {+ serde_json::json!({+ "key_count": keys.len(),+ "keys": keys.iter().map(|key| key.as_str()).collect::<Vec<_>>(),+ "command": "MGET",+ })+ },+ result = {+ (+ match &__deja_result {+ Ok(_) => serde_json::json!({"ok": true}),+ Err(e) => serde_json::json!({"ok": false, "error": format!("{:?}", e)}),+ },+ __deja_result.is_err(),+ )+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn get_multiple_keys<V>(&self,@@ -320,6 +538,19 @@ impl super::RedisConnectionPool {}}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "exists",+ codec = deja::codec::ResultCodec::<bool, errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "EXISTS",+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError>where@@ -401,6 +632,19 @@ impl super::RedisConnectionPool {Ok(results)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "delete_key",+ codec = deja::codec::ResultCodec::<DelReply, errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "DEL",+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> {match track_redis_call(@@ -430,6 +674,8 @@ impl super::RedisConnectionPool {}}+ // deja: NO boundary — the inner delete_key calls carry record/replay; an outer+ // boundary would nest and omit them. See `docs/design/deja-non-boundaries.md`.#[instrument(level = "DEBUG", skip(self))]pub async fn delete_multiple_keys(&self,@@ -444,6 +690,20 @@ impl super::RedisConnectionPool {Ok(del_result)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key_with_expiry",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SETEX",+ "ttl_seconds": seconds,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_key_with_expiry<V>(&self,@@ -469,6 +729,25 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::SetExFailed)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key_if_not_exists_with_expiry",+ codec = deja::codec::ResultCodec::<SetnxReply, errors::RedisError>,+ // Declare the key we WRITE so the seed plan's pristine rule masks a+ // later read-back of it (e.g. the lock GET after this SETNX). Without+ // this the read-back is seeded as "present", and the replayed Execute+ // SETNX then sees the lock held → never acquires → retry storm.+ state_write = key.tenant_aware_key(self),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SETNX",+ "ttl_seconds": seconds,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_key_if_not_exists_with_expiry<V>(&self,@@ -496,6 +775,20 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::SetFailed)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_expiry",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "EXPIRE",+ "ttl_seconds": seconds,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_expiry(&self,@@ -510,6 +803,20 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::SetExpiryFailed)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_expire_at",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "EXPIREAT",+ "timestamp": timestamp,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_expire_at(&self,@@ -524,6 +831,19 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::SetExpiryFailed)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "get_ttl",+ codec = deja::codec::ResultCodec::<i64, errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "TTL",+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> {track_redis_call(@@ -534,6 +854,20 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::GetFailed)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_hash_fields",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "HSET",+ "ttl_seconds": ttl,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_hash_fields<F, V>(&self,@@ -561,13 +895,54 @@ impl super::RedisConnectionPool {.await.change_context(errors::RedisError::SetHashFailed);// setting expiry for the key- output- .async_and_then(|_| {- self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into()))- })- .await+ #[cfg(not(feature = "deja"))]+ {+ output+ .async_and_then(|_| {+ self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into()))+ })+ .await+ }+ // Deja: set expiry via a RAW `pool.expire`, NOT the instrumented+ // `set_expiry`. This method already carries its own `set_hash_fields`+ // Ok-only codec boundary; nesting the instrumented `set_expiry` under it+ // would orphan the inner EXPIRE event on replay (the outer no-op+ // substitution skips it → "omitted" divergence). Inlining keeps+ // HSET+EXPIRE as one recorded write that round-trips cleanly.+ #[cfg(feature = "deja")]+ {+ output+ .async_and_then(|_| async {+ let _: () = track_redis_call(+ RedisOperation::SetExpiry,+ self.pool.expire(+ key.tenant_aware_key(self),+ ttl.unwrap_or(self.config.default_hash_ttl.into()),+ ),+ )+ .await+ .change_context(errors::RedisError::SetExpiryFailed)?;+ Ok(())+ })+ .await+ }}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_hash_field_if_not_exist",+ codec = deja::codec::ResultCodec::<HsetnxReply, errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "HSETNX",+ "field": field,+ "ttl_seconds": ttl,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_hash_field_if_not_exist<V>(&self,@@ -587,13 +962,37 @@ impl super::RedisConnectionPool {.await.change_context(errors::RedisError::SetHashFieldFailed);- output- .async_and_then(|inner| async {- self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into())- .await?;- Ok(inner)- })- .await+ #[cfg(not(feature = "deja"))]+ {+ output+ .async_and_then(|inner| async {+ self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into())+ .await?;+ Ok(inner)+ })+ .await+ }+ // Deja: raw `pool.expire` (not the instrumented `set_expiry`) for the same+ // reason as `set_hash_fields`: this method's own `set_hash_field_if_not_exist`+ // Ok-only boundary would skip a nested instrumented EXPIRE on replay,+ // orphaning its recorded event.+ #[cfg(feature = "deja")]+ {+ output+ .async_and_then(|inner| async {+ let _: () = track_redis_call(+ RedisOperation::SetExpiry,+ self.pool.expire(+ key.tenant_aware_key(self),+ ttl.unwrap_or(self.config.default_hash_ttl).into(),+ ),+ )+ .await+ .change_context(errors::RedisError::SetExpiryFailed)?;+ Ok(inner)+ })+ .await+ }}#[instrument(level = "DEBUG", skip(self))]@@ -636,6 +1035,20 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "increment_fields_in_hash",+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "HINCRBY",+ "field_count": fields_to_increment.len(),+ })+ },+ )+ )]pub async fn increment_fields_in_hash<T>(&self,key: &RedisKey,@@ -661,6 +1074,19 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "hscan",+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "HSCAN",+ "pattern": pattern,+ })+ },+ )+ )]pub async fn hscan(&self,key: &RedisKey,@@ -696,6 +1122,18 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "scan",+ args = {+ serde_json::json!({+ "pattern": pattern.as_str(),+ "command": "SCAN",+ })+ },+ )+ )]pub async fn scan(&self,pattern: &RedisKey,@@ -751,32 +1189,52 @@ impl super::RedisConnectionPool {.collect())}+ // Deja hermetic boundary for HGET — same shape as `get_key_raw`: the boundary+ // lives on this inner method which fetches the RAW reply and mirrors it into+ // the serde-native `DejaRedisValue`, so the typed `ResultCodec` substitutes the field read+ // WITHOUT leaking a serde bound onto the public `get_hash_field<V>`. A+ // record-only `result={"ok":bool}` capture would record NO value, leaving+ // replay nothing to reconstruct `V` from — the read would fall through to+ // live redis.+ #[cfg(feature = "deja")]#[instrument(level = "DEBUG", skip(self))]- pub async fn get_hash_field<V>(+ #[deja::redis(+ operation = "get_hash_field",+ codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ state_read = format!("{}:{}", key.tenant_aware_key(self), field),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "HGET",+ "field": field,+ })+ },+ )]+ async fn get_hash_field_raw(&self,key: &RedisKey,field: &str,- ) -> CustomResult<V, errors::RedisError>- where- V: FromRedis + Unpin + Send + 'static,- {+ ) -> CustomResult<DejaRedisValue, errors::RedisError> {match track_redis_call(RedisOperation::GetHashField,- self.pool.hget(key.tenant_aware_key(self), field),+ self.pool+ .hget::<RedisValue, _, _>(key.tenant_aware_key(self), field),).await.change_context(errors::RedisError::GetHashFieldFailed){- Ok(v) => Ok(v),+ Ok(v) => Ok(DejaRedisValue::from(v)),Err(_err) => {#[cfg(feature = "multitenancy_fallback")]{track_redis_call(RedisOperation::GetHashField,- self.pool.hget(key.tenant_unaware_key(self), field),+ self.pool+ .hget::<RedisValue, _, _>(key.tenant_unaware_key(self), field),).await.change_context(errors::RedisError::GetHashFieldFailed)+ .map(DejaRedisValue::from)}#[cfg(not(feature = "multitenancy_fallback"))]@@ -788,27 +1246,90 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]- pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>+ pub async fn get_hash_field<V>(+ &self,+ key: &RedisKey,+ field: &str,+ ) -> CustomResult<V, errors::RedisError>whereV: FromRedis + Unpin + Send + 'static,{+ #[cfg(feature = "deja")]+ {+ let raw = self.get_hash_field_raw(key, field).await?;+ let value: RedisValue = raw.try_into().map_err(|err: fred::error::RedisError| {+ report!(err).change_context(errors::RedisError::GetHashFieldFailed)+ })?;+ V::from_value(value).change_context(errors::RedisError::GetHashFieldFailed)+ }++ #[cfg(not(feature = "deja"))]+ {+ match track_redis_call(+ RedisOperation::GetHashField,+ self.pool.hget(key.tenant_aware_key(self), field),+ )+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(feature = "multitenancy_fallback")]+ {+ track_redis_call(+ RedisOperation::GetHashField,+ self.pool.hget(key.tenant_unaware_key(self), field),+ )+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ }++ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }+ }+ }+ }+ }++ #[cfg(feature = "deja")]+ #[instrument(level = "DEBUG", skip(self))]+ #[deja::redis(+ operation = "get_hash_fields",+ codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ state_read = key.tenant_aware_key(self),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "HGETALL",+ })+ },+ )]+ async fn get_hash_fields_raw(+ &self,+ key: &RedisKey,+ ) -> CustomResult<DejaRedisValue, errors::RedisError> {match track_redis_call(RedisOperation::GetHashFields,- self.pool.hgetall(key.tenant_aware_key(self)),+ self.pool+ .hgetall::<RedisValue, _>(key.tenant_aware_key(self)),).await.change_context(errors::RedisError::GetHashFieldFailed){- Ok(v) => Ok(v),+ Ok(v) => Ok(DejaRedisValue::from(v)),Err(_err) => {#[cfg(feature = "multitenancy_fallback")]{track_redis_call(RedisOperation::GetHashFields,- self.pool.hgetall(key.tenant_unaware_key(self)),+ self.pool+ .hgetall::<RedisValue, _>(key.tenant_unaware_key(self)),).await.change_context(errors::RedisError::GetHashFieldFailed)+ .map(DejaRedisValue::from)}#[cfg(not(feature = "multitenancy_fallback"))]@@ -819,6 +1340,50 @@ impl super::RedisConnectionPool {}}+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>+ where+ V: FromRedis + Unpin + Send + 'static,+ {+ #[cfg(feature = "deja")]+ {+ let raw = self.get_hash_fields_raw(key).await?;+ let value: RedisValue = raw.try_into().map_err(|err: fred::error::RedisError| {+ report!(err).change_context(errors::RedisError::GetHashFieldFailed)+ })?;+ V::from_value(value).change_context(errors::RedisError::GetHashFieldFailed)+ }++ #[cfg(not(feature = "deja"))]+ {+ match track_redis_call(+ RedisOperation::GetHashFields,+ self.pool.hgetall(key.tenant_aware_key(self)),+ )+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(feature = "multitenancy_fallback")]+ {+ track_redis_call(+ RedisOperation::GetHashFields,+ self.pool.hgetall(key.tenant_unaware_key(self)),+ )+ .await+ .change_context(errors::RedisError::GetHashFieldFailed)+ }++ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }+ }+ }+ }+ }+#[instrument(level = "DEBUG", skip(self))]pub async fn get_hash_field_and_deserialize<V>(&self,@@ -857,6 +1422,21 @@ impl super::RedisConnectionPool {.change_context(errors::RedisError::DeleteHashFieldFailed)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "sadd",+ codec = deja::codec::ResultCodec::<SaddReply, errors::RedisError>,+ state_write = key.tenant_aware_key(self),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SADD",+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn sadd<V>(&self,@@ -876,6 +1456,19 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "stream_append_entry",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XADD",+ })+ },+ )+ )]pub async fn stream_append_entry<F, V>(&self,stream: &RedisKey,@@ -912,6 +1505,19 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "stream_delete_entries",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XDEL",+ })+ },+ )+ )]pub async fn stream_delete_entries(&self,stream: &RedisKey,@@ -927,6 +1533,19 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "stream_trim_entries",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XTRIM",+ })+ },+ )+ )]pub async fn stream_trim_entries(&self,stream: &RedisKey,@@ -944,6 +1563,20 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "stream_acknowledge_entries",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XACK",+ "group": group,+ })+ },+ )+ )]pub async fn stream_acknowledge_entries(&self,stream: &RedisKey,@@ -961,6 +1594,18 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "stream_get_length",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XLEN",+ })+ },+ )+ )]pub async fn stream_get_length(&self,stream: &RedisKey,@@ -979,6 +1624,17 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "stream_read_entries",+ args = {+ serde_json::json!({+ "command": "XREAD",+ })+ },+ )+ )]pub async fn stream_read_entries(&self,streams: &[RedisKey],@@ -1030,6 +1686,17 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "stream_read_with_options",+ args = {+ serde_json::json!({+ "command": if group.is_some() { "XREADGROUP" } else { "XREAD" },+ })+ },+ )+ )]pub async fn stream_read_with_options(&self,streams: &[RedisKey],@@ -1102,6 +1769,19 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "append_elements_to_list",+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "RPUSH",+ })+ },+ )+ )]pub async fn append_elements_to_list<V>(&self,key: &RedisKey,@@ -1120,6 +1800,20 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "get_list_elements",+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "LRANGE",+ "start": start,+ "stop": stop,+ })+ },+ )+ )]pub async fn get_list_elements(&self,key: &RedisKey,@@ -1135,6 +1829,18 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "get_list_length",+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "LLEN",+ })+ },+ )+ )]pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> {track_redis_call(RedisOperation::GetListLength,@@ -1145,6 +1851,20 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "lpop_list_elements",+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "LPOP",+ "count": count,+ })+ },+ )+ )]pub async fn lpop_list_elements(&self,key: &RedisKey,@@ -1161,6 +1881,20 @@ impl super::RedisConnectionPool {// Consumer Group API#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "consumer_group_create",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XGROUP_CREATE",+ "group": group,+ })+ },+ )+ )]pub async fn consumer_group_create(&self,stream: &RedisKey,@@ -1185,6 +1919,20 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "consumer_group_destroy",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XGROUP_DESTROY",+ "group": group,+ })+ },+ )+ )]pub async fn consumer_group_destroy(&self,stream: &RedisKey,@@ -1202,6 +1950,21 @@ impl super::RedisConnectionPool {// the number of pending messages that the consumer had before it was deleted#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "consumer_group_delete_consumer",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XGROUP_DELCONSUMER",+ "group": group,+ "consumer": consumer,+ })+ },+ )+ )]pub async fn consumer_group_delete_consumer(&self,stream: &RedisKey,@@ -1218,6 +1981,20 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "consumer_group_set_last_id",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XGROUP_SETID",+ "group": group,+ })+ },+ )+ )]pub async fn consumer_group_set_last_id(&self,stream: &RedisKey,@@ -1236,6 +2013,33 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "consumer_group_set_message_owner",+ args = {+ serde_json::json!({+ "key": stream.as_str(),+ "command": "XCLAIM",+ "group": group,+ "consumer": consumer,+ })+ },+ // Generic `R: FromRedis` is NOT `Debug`, so the default `result_debug`+ // capture would not compile. Record only the ok/err verdict (record-only+ // leaf — no replay reconstruction needed).+ result = {+ (+ match &__deja_result {+ Ok(_) => serde_json::json!({"ok": true}),+ Err(e) => serde_json::json!({"ok": false, "error": format!("{:?}", e)}),+ },+ __deja_result.is_err(),+ )+ },+ )+ )]pub async fn consumer_group_set_message_owner<R>(&self,stream: &RedisKey,@@ -1268,6 +2072,31 @@ impl super::RedisConnectionPool {}#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "evaluate_redis_script",+ args = {+ serde_json::json!({+ "command": "EVAL",+ "key_count": key.len(),+ })+ },+ // Generic `T` is NOT `Debug`, so the default `result_debug` capture+ // would not compile. Record only the ok/err verdict (record-only leaf —+ // an EVAL result is never reconstructed without an explicit override).+ result = {+ (+ match &__deja_result {+ Ok(_) => serde_json::json!({"ok": true}),+ Err(e) => serde_json::json!({"ok": false, "error": format!("{:?}", e)}),+ },+ __deja_result.is_err(),+ )+ },+ )+ )]pub async fn evaluate_redis_script<V, T>(&self,lua_script: &'static str,@@ -1318,6 +2147,32 @@ impl super::RedisConnectionPool {/// Sets a value in Redis if not already present, and returns the value (either existing or newly set)./// This operation is atomic using Redis transactions.#[instrument(level = "DEBUG", skip(self))]+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key_if_not_exists_and_get_value",+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SETNX_GET",+ "ttl_seconds": ttl,+ })+ },+ // `SetGetReply<V>` carries a generic `V` with no `Debug` bound, so the+ // default `result_debug` capture would not compile. Record only the+ // ok/err verdict (record-only leaf — no replay reconstruction needed;+ // an RMW transaction always re-executes live on replay).+ result = {+ (+ match &__deja_result {+ Ok(_) => serde_json::json!({"ok": true}),+ Err(e) => serde_json::json!({"ok": false, "error": format!("{:?}", e)}),+ },+ __deja_result.is_err(),+ )+ },+ )+ )]pub async fn set_key_if_not_exists_and_get_value<V>(&self,key: &RedisKey,diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rsindex 3f927138a3..b64f81052b 100644--- a/crates/redis_interface/src/module/redis_rs/commands.rs+++ b/crates/redis_interface/src/module/redis_rs/commands.rs@@ -32,17 +32,202 @@ use crate::{},};+#[cfg(feature = "deja")]+#[derive(serde::Serialize, serde::Deserialize)]+enum DejaRedisValue {+ Null,+ Int(i64),+ BulkString(Vec<u8>),+ Array(Vec<Self>),+ SimpleString(String),+ Okay,+ Map(Vec<(Self, Self)>),+ Attribute {+ data: Box<Self>,+ attributes: Vec<(Self, Self)>,+ },+ Set(Vec<Self>),+ Double(f64),+ Boolean(bool),+ VerbatimString {+ format: String,+ text: String,+ },+ Push {+ kind: String,+ data: Vec<Self>,+ },+ UnsupportedSuccessfulValue {+ variant: String,+ },+}++#[cfg(feature = "deja")]+impl From<redis::Value> for DejaRedisValue {+ fn from(value: redis::Value) -> Self {+ match value {+ redis::Value::Nil => Self::Null,+ redis::Value::Int(value) => Self::Int(value),+ redis::Value::BulkString(value) => Self::BulkString(value),+ redis::Value::Array(values) => {+ Self::Array(values.into_iter().map(Self::from).collect())+ }+ redis::Value::SimpleString(value) => Self::SimpleString(value),+ redis::Value::Okay => Self::Okay,+ redis::Value::Map(values) => Self::Map(+ values+ .into_iter()+ .map(|(key, value)| (Self::from(key), Self::from(value)))+ .collect(),+ ),+ redis::Value::Attribute { data, attributes } => Self::Attribute {+ data: Box::new(Self::from(*data)),+ attributes: attributes+ .into_iter()+ .map(|(key, value)| (Self::from(key), Self::from(value)))+ .collect(),+ },+ redis::Value::Set(values) => Self::Set(values.into_iter().map(Self::from).collect()),+ redis::Value::Double(value) => Self::Double(value),+ redis::Value::Boolean(value) => Self::Boolean(value),+ redis::Value::VerbatimString { format, text } => Self::VerbatimString {+ format: format.to_string(),+ text,+ },+ redis::Value::Push { kind, data } => Self::Push {+ kind: kind.to_string(),+ data: data.into_iter().map(Self::from).collect(),+ },+ redis::Value::BigNumber(_) => Self::UnsupportedSuccessfulValue {+ variant: "BigNumber".to_string(),+ },+ redis::Value::ServerError(error) => Self::UnsupportedSuccessfulValue {+ variant: match error.details() {+ Some(details) => format!("ServerError({}: {details})", error.code()),+ None => format!("ServerError({})", error.code()),+ },+ },+ _ => Self::UnsupportedSuccessfulValue {+ variant: "unknown non-exhaustive redis::Value variant".to_string(),+ },+ }+ }+}++#[cfg(feature = "deja")]+impl DejaRedisValue {+ fn into_supported_redis_value(self) -> Result<redis::Value, redis::RedisError> {+ match self {+ Self::Null => Ok(redis::Value::Nil),+ Self::Int(value) => Ok(redis::Value::Int(value)),+ Self::BulkString(value) => Ok(redis::Value::BulkString(value)),+ Self::Array(values) => Ok(redis::Value::Array(+ values+ .into_iter()+ .map(Self::into_supported_redis_value)+ .collect::<Result<Vec<_>, _>>()?,+ )),+ Self::SimpleString(value) => Ok(redis::Value::SimpleString(value)),+ Self::Okay => Ok(redis::Value::Okay),+ Self::Map(values) => Ok(redis::Value::Map(+ values+ .into_iter()+ .map(|(key, value)| {+ Ok((+ key.into_supported_redis_value()?,+ value.into_supported_redis_value()?,+ ))+ })+ .collect::<Result<Vec<_>, redis::RedisError>>()?,+ )),+ Self::Attribute { data, attributes } => Ok(redis::Value::Attribute {+ data: Box::new(data.into_supported_redis_value()?),+ attributes: attributes+ .into_iter()+ .map(|(key, value)| {+ Ok((+ key.into_supported_redis_value()?,+ value.into_supported_redis_value()?,+ ))+ })+ .collect::<Result<Vec<_>, redis::RedisError>>()?,+ }),+ Self::Set(values) => Ok(redis::Value::Set(+ values+ .into_iter()+ .map(Self::into_supported_redis_value)+ .collect::<Result<Vec<_>, _>>()?,+ )),+ Self::Double(value) => Ok(redis::Value::Double(value)),+ Self::Boolean(value) => Ok(redis::Value::Boolean(value)),+ Self::VerbatimString { format, text } => Ok(redis::Value::VerbatimString {+ format: match format.as_str() {+ "mkd" => redis::VerbatimFormat::Markdown,+ "txt" => redis::VerbatimFormat::Text,+ other => redis::VerbatimFormat::Unknown(other.to_string()),+ },+ text,+ }),+ Self::Push { kind, data } => Ok(redis::Value::Push {+ kind: match kind.as_str() {+ "disconnection" => redis::PushKind::Disconnection,+ "invalidate" => redis::PushKind::Invalidate,+ "message" => redis::PushKind::Message,+ "pmessage" => redis::PushKind::PMessage,+ "smessage" => redis::PushKind::SMessage,+ "unsubscribe" => redis::PushKind::Unsubscribe,+ "punsubscribe" => redis::PushKind::PUnsubscribe,+ "sunsubscribe" => redis::PushKind::SUnsubscribe,+ "subscribe" => redis::PushKind::Subscribe,+ "psubscribe" => redis::PushKind::PSubscribe,+ "ssubscribe" => redis::PushKind::SSubscribe,+ other => redis::PushKind::Other(other.to_string()),+ },+ data: data+ .into_iter()+ .map(Self::into_supported_redis_value)+ .collect::<Result<Vec<_>, _>>()?,+ }),+ Self::UnsupportedSuccessfulValue { variant } => Err((+ redis::ErrorKind::UnexpectedReturnType,+ "unsupported Redis value variant recorded by Deja replay",+ variant,+ )+ .into()),+ }+ }+}+impl super::RedisConnectionPool {pub fn add_prefix(&self, key: &str) -> String {- if self.key_prefix.is_empty() {+ let physical = if self.key_prefix.is_empty() {key.to_string()} else {format!("{}:{}", self.key_prefix, key)+ };+ #[cfg(feature = "deja")]+ if let Some(corr) = deja::replay_key_namespace() {+ return format!("{corr}:{physical}");}+ physical}// ─── Key Commands ────────────────────────────────────────────────────────+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SET",+ "has_ttl": true,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError>where@@ -60,6 +245,19 @@ impl super::RedisConnectionPool {Ok(())}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key_without_modifying_ttl",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SET_KEEP_TTL",+ })+ },+ )+ )]pub async fn set_key_without_modifying_ttl<V>(&self,key: &RedisKey,@@ -160,33 +358,54 @@ impl super::RedisConnectionPool {.encode_to_vec().change_context(errors::RedisError::JsonSerializationFailed)?;- let mut conn = self.pool.clone();- let options = SetOptions::default().with_expiration(SetExpiry::EX(- u64::try_from(seconds).change_context(errors::RedisError::SetExFailed)?,- ));- let _: Option<String> = track_redis_call(- RedisOperation::SerializeAndSetKeyWithExpiry,- conn.set_options(key.tenant_aware_key(self), serialized.as_slice(), options),- )- .await- .change_context(errors::RedisError::SetExFailed)?;- Ok(())+ #[cfg(feature = "deja")]+ {+ self.set_key_with_expiry(key, serialized.as_slice(), seconds)+ .await+ }++ #[cfg(not(feature = "deja"))]+ {+ let mut conn = self.pool.clone();+ let options = SetOptions::default().with_expiration(SetExpiry::EX(+ u64::try_from(seconds).change_context(errors::RedisError::SetExFailed)?,+ ));+ let _: Option<String> = track_redis_call(+ RedisOperation::SerializeAndSetKeyWithExpiry,+ conn.set_options(key.tenant_aware_key(self), serialized.as_slice(), options),+ )+ .await+ .change_context(errors::RedisError::SetExFailed)?;+ Ok(())+ }}+ #[cfg(feature = "deja")]#[instrument(level = "DEBUG", skip(self))]- pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>- where- V: FromRedisValue + Send + 'static,- {+ #[deja::redis(+ operation = "get_key",+ codec = deja::codec::ResultCodec::<DejaRedisValue, errors::RedisError>,+ state_read = key.tenant_aware_key(self),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "GET",+ })+ },+ )]+ async fn get_key_raw(+ &self,+ key: &RedisKey,+ ) -> CustomResult<DejaRedisValue, errors::RedisError> {let mut conn = self.pool.clone();match track_redis_call(RedisOperation::GetKey,- conn.get::<_, V>(key.tenant_aware_key(self)),+ conn.get::<_, redis::Value>(key.tenant_aware_key(self)),).await.change_context(errors::RedisError::GetFailed){- Ok(v) => Ok(v),+ Ok(value) => Ok(DejaRedisValue::from(value)),Err(_err) => {#[cfg(not(feature = "multitenancy_fallback"))]{@@ -197,15 +416,63 @@ impl super::RedisConnectionPool {{track_redis_call(RedisOperation::GetKey,- conn.get::<_, V>(key.tenant_unaware_key(self)),+ conn.get::<_, redis::Value>(key.tenant_unaware_key(self)),).await+ .map(DejaRedisValue::from).change_context(errors::RedisError::GetFailed)}}}}+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>+ where+ V: FromRedisValue + Send + 'static,+ {+ #[cfg(feature = "deja")]+ {+ let raw_value = self+ .get_key_raw(key)+ .await?+ .into_supported_redis_value()+ .map_err(|err| report!(err).change_context(errors::RedisError::GetFailed))?;+ return V::from_redis_value(raw_value)+ .map_err(|err| report!(err).change_context(errors::RedisError::GetFailed));+ }++ #[cfg(not(feature = "deja"))]+ {+ let mut conn = self.pool.clone();+ match track_redis_call(+ RedisOperation::GetKey,+ conn.get::<_, V>(key.tenant_aware_key(self)),+ )+ .await+ .change_context(errors::RedisError::GetFailed)+ {+ Ok(v) => Ok(v),+ Err(_err) => {+ #[cfg(not(feature = "multitenancy_fallback"))]+ {+ Err(_err)+ }++ #[cfg(feature = "multitenancy_fallback")]+ {+ track_redis_call(+ RedisOperation::GetKey,+ conn.get::<_, V>(key.tenant_unaware_key(self)),+ )+ .await+ .change_context(errors::RedisError::GetFailed)+ }+ }+ }+ }+ }+#[instrument(level = "DEBUG", skip(self))]async fn get_multiple_keys_with_mget<V>(&self,@@ -278,6 +545,29 @@ impl super::RedisConnectionPool {}}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "get_multiple_keys",+ read_set = keys.iter().map(|key| key.tenant_aware_key(self)).collect::<Vec<_>>(),+ args = {+ serde_json::json!({+ "key_count": keys.len(),+ "keys": keys.iter().map(|key| key.as_str()).collect::<Vec<_>>(),+ "command": "MGET",+ })+ },+ result = {+ (+ match &__deja_result {+ Ok(_) => serde_json::json!({"ok": true}),+ Err(e) => serde_json::json!({"ok": false, "error": format!("{:?}", e)}),+ },+ __deja_result.is_err(),+ )+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn get_multiple_keys<V>(&self,@@ -391,6 +681,19 @@ impl super::RedisConnectionPool {Ok(results)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "delete_key",+ codec = deja::codec::ResultCodec::<DelReply, errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "DEL",+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> {let mut conn = self.pool.clone();@@ -448,6 +751,20 @@ impl super::RedisConnectionPool {Ok(del_result)}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key_with_expiry",+ codec = deja::codec::ResultCodec::<(), errors::RedisError>,+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SETEX",+ "ttl_seconds": seconds,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_key_with_expiry<V>(&self,@@ -471,6 +788,21 @@ impl super::RedisConnectionPool {Ok(())}+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ operation = "set_key_if_not_exists_with_expiry",+ codec = deja::codec::ResultCodec::<SetnxReply, errors::RedisError>,+ state_write = key.tenant_aware_key(self),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SETNX",+ "ttl_seconds": seconds,+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn set_key_if_not_exists_with_expiry<V>(&self,@@ -920,6 +1252,21 @@ impl super::RedisConnectionPool {// ─── Set Commands ────────────────────────────────────────────────────────+ #[cfg_attr(+ feature = "deja",+ deja::redis(+ replay = Substitute,+ operation = "sadd",+ codec = deja::codec::ResultCodec::<SaddReply, errors::RedisError>,+ state_write = key.tenant_aware_key(self),+ args = {+ serde_json::json!({+ "key": key.as_str(),+ "command": "SADD",+ })+ },+ )+ )]#[instrument(level = "DEBUG", skip(self))]pub async fn sadd<V>(&self,diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rsindex 4807b97ee1..4312681cce 100644--- a/crates/redis_interface/src/types.rs+++ b/crates/redis_interface/src/types.rs@@ -161,24 +161,28 @@ impl RedisEntryId {// ─── Reply type enums ────────────────────────────────────────────────────────#[derive(Debug, Eq, PartialEq)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]pub enum SetnxReply {KeySet,KeyNotSet, // Existing key}#[derive(Debug, Eq, PartialEq)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]pub enum HsetnxReply {KeySet,KeyNotSet, // Existing key}#[derive(Debug, Eq, PartialEq)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]pub enum MsetnxReply {KeysSet,KeysNotSet, // At least one existing key}#[derive(Debug, Eq, PartialEq)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]pub enum DelReply {KeyDeleted,KeyNotDeleted, // Key not found@@ -196,6 +200,7 @@ impl DelReply {/// Reply from SADD command#[derive(Debug, Eq, PartialEq)]+#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]pub enum SaddReply {/// Returned when atleast 1 value was inserted to Set/// i64 value represent the total number of values that were inserted.@@ -355,6 +360,11 @@ impl std::error::Error for StreamTrimThresholdError {}pub struct RedisKey(String);impl RedisKey {+ #[cfg(feature = "deja")]+ pub fn as_str(&self) -> &str {+ self.0.as_str()+ }+pub fn tenant_aware_key(&self, pool: &crate::RedisConnectionPool) -> String {pool.add_prefix(&self.0)}diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex e91dc58db7..5e188fe909 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -21,7 +21,7 @@ encryption_service = ["keymanager_create", "hyperswitch_domain_models/encryptionkm_forward_x_request_id = ["common_utils/km_forward_x_request_id"]frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"]stripe = []-release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service", "dynamic_routing", "payout_retry"]+release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service", "dynamic_routing", "payout_retry", "deja"]oltp = ["storage_impl/oltp"]kv_store = ["scheduler/kv_store"]accounts_cache = ["storage_impl/accounts_cache"]@@ -36,7 +36,7 @@ v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domaindynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"]revenue_recovery = ["api_models/revenue_recovery", "hyperswitch_interfaces/revenue_recovery", "hyperswitch_domain_models/revenue_recovery", "hyperswitch_connectors/revenue_recovery", "external_services/revenue_recovery", "dep:prost-types"]tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2", "storage_impl/tokenization_v2"]-deja = ["dep:deja", "dep:deja-core", "v1", "common_utils/deja", "router_env/deja", "external_services/deja", "diesel_models/deja", "redis_interface/deja", "hyperswitch_domain_models/deja", "storage_impl/deja"]+deja = ["dep:deja", "dep:deja-core", "common_utils/deja", "router_env/deja", "external_services/deja", "diesel_models/deja", "redis_interface/deja", "hyperswitch_domain_models/deja", "storage_impl/deja"]# Partial Auth# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.# This is named as partial-auth because the router will still try to authenticate if the `x-merchant-id` header is not present.@@ -126,8 +126,8 @@ cards = { version = "0.1.0", path = "../cards" }common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager"] }common_types = { version = "0.1.0", path = "../common_types" }-deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }-deja-core = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true }+deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true }connector_configs = { version = "0.1.0", path = "../connector_configs" }currency_conversion = { version = "0.1.0", path = "../currency_conversion" }diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store", "tokenization_v2"], default-features = false }diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rsindex 62086b4abf..8b9df53c4d 100644--- a/crates/router/src/bin/router.rs+++ b/crates/router/src/bin/router.rs@@ -24,6 +24,19 @@ async fn main() -> ApplicationResult<()> {println!("Starting router (Version: {})", router_env::git_tag!());}+ #[cfg(feature = "deja")]+ let deja_install_report = {+ // An empty deja broker list inherits the analytics Kafka brokers+ // (shared cluster provisioning, separate producer client).+ let analytics_brokers = match &conf.events.source {+ router::events::EventsSource::Kafka { kafka } => Some(kafka.brokers()),+ _ => None,+ };+ router::deja_boot::install(&conf.deja, analytics_brokers).map_err(|message| {+ error_stack::report!(ApplicationError::ConfigurationError).attach_printable(message)+ })?+ };+let _guard = router_env::setup(&conf.log,router_env::service_name!(),@@ -39,6 +52,15 @@ async fn main() -> ApplicationResult<()> {logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log);+ #[cfg(feature = "deja")]+ router_env::tracing::info!(+ target: "deja",+ mode = deja_install_report.mode,+ run_id = ?deja_install_report.run_id,+ detail = ?deja_install_report.detail,+ "deja runtime hook initialized"+ );+// Spawn a thread for collecting metrics at fixed intervalsmetrics::bg_metrics_collector::spawn_metrics_collector(conf.log.telemetry.bg_metrics_collection_interval_in_secs,diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rsindex c87650635c..5d289b058e 100644--- a/crates/router/src/bin/scheduler.rs+++ b/crates/router/src/bin/scheduler.rs@@ -34,6 +34,23 @@ async fn main() -> CustomResult<(), ProcessTrackerError> {#[allow(clippy::expect_used)]let conf = Settings::with_config_path(cmd_line.config_path).expect("Unable to construct application configuration");++ // Install the Deja runtime hook BEFORE AppState construction: state setup+ // opens redis/DB pools whose instrumented calls would otherwise resolve —+ // and permanently latch — the hook ahead of the configured install.+ #[cfg(feature = "deja")]+ let deja_install_report = {+ // An empty deja broker list inherits the analytics Kafka brokers+ // (shared cluster provisioning, separate producer client).+ let analytics_brokers = match &conf.events.source {+ router::events::EventsSource::Kafka { kafka } => Some(kafka.brokers()),+ _ => None,+ };+ router::deja_boot::install(&conf.deja, analytics_brokers).map_err(|message| {+ error_stack::report!(ProcessTrackerError::ConfigurationError).attach_printable(message)+ })?+ };+let api_client = Box::new(services::ProxyClient::new(&conf.proxy).change_context(ProcessTrackerError::ConfigurationError)?,@@ -81,6 +98,15 @@ async fn main() -> CustomResult<(), ProcessTrackerError> {],);+ #[cfg(feature = "deja")]+ router_env::tracing::info!(+ target: "deja",+ mode = deja_install_report.mode,+ run_id = ?deja_install_report.run_id,+ detail = ?deja_install_report.detail,+ "deja runtime hook initialized"+ );+#[allow(clippy::expect_used)]let web_server = Box::pin(start_web_server(state.clone(),diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 828ad590c0..1d2da25a07 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -253,19 +253,11 @@ impl DejaSettings {#[derive(Debug, Deserialize, Clone, Default)]#[serde(default)]pub struct DejaRecordingSettings {- pub graph: DejaGraphMode,+ // Execution-graph capture is coupled to the runtime mode (the graph layer+ // rides the installed Record/Replay hook), so there is no `graph` dial here.pub kafka: DejaRecordingKafkaSettings,}-#[cfg(feature = "deja")]-#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq, Default)]-#[serde(rename_all = "snake_case")]-pub enum DejaGraphMode {- #[default]- Disabled,- Enabled,-}-#[cfg(feature = "deja")]#[derive(Debug, Deserialize, Clone)]#[serde(default)]@@ -317,11 +309,13 @@ pub struct DejaReplaySettings {pub observed_sink: Option<String>,}+/// Per-request recording-sampler settings. The sampler is active exactly when+/// `deja.mode = "record"` — there is no separate on/off switch; `fail_closed`+/// governs what happens when the sampling source cannot answer.#[cfg(feature = "deja")]#[derive(Debug, Deserialize, Clone)]#[serde(default)]pub struct DejaSamplerSettings {- pub enabled: bool,pub record_key: Option<String>,pub timeout_ms: u64,pub fail_closed: bool,@@ -331,7 +325,6 @@ pub struct DejaSamplerSettings {impl Default for DejaSamplerSettings {fn default() -> Self {Self {- enabled: false,record_key: None,timeout_ms: 25,fail_closed: true,diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rsindex 818dab4411..b3e095260f 100644--- a/crates/router/src/connection.rs+++ b/crates/router/src/connection.rs@@ -22,6 +22,32 @@ pub async fn redis_connection(.expect("Failed to create Redis Connection Pool")}+// Deja replay (R1): the minimal replay DB routing hook. On a just-leased pg+// connection during replay, route it to the active correlation's schema so+// per-test-case reads/writes stay isolated. The correlation is read from the+// STORE (`get_request_id`, a reliable request-scoped value set at ingress) — NOT+// the ambient thread-local, which is bled at checkout when connection acquisition+// resumes off the request's correlation span. Leases are per-op, so this fires on+// every pg op and overwrites any stale search_path a reused connection carries.+// No-op outside replay / when the store carries no request id. The `SET` SQL is+// built by the library (`deja::replay_search_path_sql_for`).+#[cfg(feature = "deja")]+async fn deja_route_replay_schema<T: storage_impl::DatabaseStore>(+ conn: &mut PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ store: &T,+) {+ use async_bb8_diesel::AsyncConnection;+ if !deja::replay_is_active() {+ return;+ }+ if let Some(corr) = store.get_request_id().as_deref() {+ let sql = deja::replay_search_path_sql_for(corr);+ let _ = conn+ .run(move |c| diesel::connection::SimpleConnection::batch_execute(c, &sql))+ .await;+ }+}+pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(store: &T,) -> errors::CustomResult<@@ -43,9 +69,14 @@ pub async fn pg_connection_read<T: storage_impl::DatabaseStore>())]let pool = store.get_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(storage_errors::StorageError::DatabaseConnectionError)+ .change_context(storage_errors::StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(@@ -69,9 +100,14 @@ pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>())]let pool = store.get_accounts_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(storage_errors::StorageError::DatabaseConnectionError)+ .change_context(storage_errors::StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn pg_connection_write<T: storage_impl::DatabaseStore>(@@ -83,9 +119,14 @@ pub async fn pg_connection_write<T: storage_impl::DatabaseStore>(// Since all writes should happen to master DB only choose master DB.let pool = store.get_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(storage_errors::StorageError::DatabaseConnectionError)+ .change_context(storage_errors::StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>(@@ -97,7 +138,12 @@ pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>(// Since all writes should happen to master DB only choose master DB.let pool = store.get_accounts_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(storage_errors::StorageError::DatabaseConnectionError)+ .change_context(storage_errors::StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 87f6d7a494..009b7ffbf1 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -64,7 +64,18 @@ use crate::{utils,};+// deja: the publishable key embeds a random UUIDv4 and is persisted on the+// merchant row + returned in the response, so it must replay to the recorded+// string for byte-exact self-replay.#[inline]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "router::admin",+ operation = "create_merchant_publishable_key",+ codec = SerdeCodec,+ )+)]pub fn create_merchant_publishable_key() -> String {format!("pk_{}_{}",diff --git a/crates/router/src/core/api_locking.rs b/crates/router/src/core/api_locking.rsindex 0713fdf611..6c79620ee3 100644--- a/crates/router/src/core/api_locking.rs+++ b/crates/router/src/core/api_locking.rs@@ -52,6 +52,8 @@ impl LockingInput {}impl LockAction {+ // deja: NO boundary — the lock outcome replays from the recorded redis reply.+ // See `docs/design/deja-non-boundaries.md`.#[instrument(skip_all)]pub async fn perform_locking_action<A>(self,@@ -168,6 +170,8 @@ impl LockAction {}}+ // deja: NO boundary — the release is the inner redis delete_key.+ // See `docs/design/deja-non-boundaries.md`.#[instrument(skip_all)]pub async fn free_lock_action<A>(self,diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex c50fd8487b..61713347d1 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -2109,12 +2109,12 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forpayment_data.payment_attempt.authentication_id = Some(auth_create_resp.authentication_id.clone());- let elig_resp = crate::core::unified_authentication_service::authentication_eligibility_core(+ let elig_resp = Box::pin(crate::core::unified_authentication_service::authentication_eligibility_core(state.clone(),platform.clone(),eligibility_req,auth_create_resp.authentication_id.clone(),- ).await?+ )).await?.get_json_body().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get json body from authentication eligibility response")?;diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex 64253ae414..f12a7608f5 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -163,6 +163,7 @@ pub trait StorageInterface:fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState);}+#[cfg(feature = "deja")]#[async_trait::async_trait]pub trait GlobalStorageInterface:Send@@ -173,11 +174,46 @@ pub trait GlobalStorageInterface:+ user_key_store::UserKeyStoreInterface+ role::RoleInterface+ RedisConnInterface+ + RequestIdStore+ 'static{fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>;}+#[cfg(not(feature = "deja"))]+#[async_trait::async_trait]+pub trait GlobalStorageInterface:+ Send+ + Sync+ + dyn_clone::DynClone+ + user::UserInterface+ + user_role::UserRoleInterface+ + user_key_store::UserKeyStoreInterface+ + role::RoleInterface+ + RedisConnInterface+ + 'static+{+ fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>;+}++#[cfg(feature = "deja")]+#[async_trait::async_trait]+pub trait AccountsStorageInterface:+ Send+ + Sync+ + dyn_clone::DynClone+ + OrganizationInterface+ + merchant_account::MerchantAccountInterface<Error = StorageError>+ + business_profile::ProfileInterface<Error = StorageError>+ + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>+ + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>+ + dashboard_metadata::DashboardMetadataInterface+ + RequestIdStore+ + 'static+{+}++#[cfg(not(feature = "deja"))]#[async_trait::async_trait]pub trait AccountsStorageInterface:Send@@ -306,6 +342,12 @@ impl RequestIdStore for MockDb {}impl RequestIdStore for Store {fn add_request_id(&mut self, request_id: String) {+ // During deja replay, also stamp the inner RouterStore in KV builds because+ // PostgresOnly-delegated operations route through it.+ #[cfg(all(feature = "kv_store", feature = "deja"))]+ {+ self.router_store.request_id = Some(request_id.clone());+ }self.request_id = Some(request_id.clone());self.update_key_manager_request_id(request_id);}diff --git a/crates/router/src/deja_boot.rs b/crates/router/src/deja_boot.rsnew file mode 100644index 0000000000..f3b797beb2--- /dev/null+++ b/crates/router/src/deja_boot.rs@@ -0,0 +1,288 @@+//! Boot-time composition of the typed Deja runtime hook.+//!+//! The router owns the transport wiring: typed router settings select disabled,+//! Kafka recording, or lookup-table replay, and this module eagerly installs the+//! process-wide runtime hook before any boundary or logger layer can observe the+//! default environment-derived state.++use std::{path::PathBuf, sync::Arc};++use crate::{+ configs::settings::{DejaMode, DejaReplaySettings, DejaSettings},+ services::kafka::deja_record_sink::{+ HyperswitchKafkaRecordSink, HyperswitchKafkaRecordSinkConfig,+ },+};++#[derive(Debug, Clone)]+pub struct InstallReport {+ pub mode: &'static str,+ pub run_id: Option<String>,+ pub detail: Option<String>,+}++fn non_empty(value: Option<&str>) -> Option<&str> {+ value.map(str::trim).filter(|value| !value.is_empty())+}++fn fallback_run_id() -> String {+ let now_ns = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or(std::time::Duration::ZERO)+ .as_nanos();+ format!("run-{now_ns}")+}++fn configured_run_id(settings: &DejaSettings) -> String {+ settings+ .effective_run_id()+ .map(str::to_owned)+ .unwrap_or_else(fallback_run_id)+}++fn configured_value(value: Option<&str>) -> Option<String> {+ non_empty(value).map(str::to_owned)+}++fn env_value_named(name: &str) -> Option<String> {+ let name = non_empty(Some(name))?;+ configured_value(std::env::var(name).ok().as_deref())+}++fn fallback_instance_id() -> String {+ let now_ns = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or(std::time::Duration::ZERO)+ .as_nanos();+ format!("pi-{}-{now_ns}", std::process::id())+}++fn resolved_instance_id(settings: &DejaSettings) -> String {+ configured_value(settings.identity.instance_id.as_deref())+ .or_else(|| env_value_named(&settings.identity.pod_name_env))+ .unwrap_or_else(fallback_instance_id)+}++fn resolved_code_sha(settings: &DejaSettings) -> Option<String> {+ configured_value(settings.identity.code_sha.as_deref())+ .or_else(|| env_value_named(&settings.identity.git_sha_env))+ .or_else(|| option_env!("VERGEN_GIT_SHA").map(str::to_owned))+ .or_else(|| Some("unknown".to_owned()))+}++fn writer_config(settings: &DejaSettings) -> deja::WriterConfig {+ let writer = &settings.writer;+ deja::WriterConfig {+ queue_capacity: writer.queue_capacity.max(1),+ batch_size: writer.batch_size.max(1),+ flush_interval: std::time::Duration::from_millis(writer.flush_interval_ms.max(1)),+ flush_timeout: std::time::Duration::from_millis(writer.shutdown_flush_ms.max(1)),+ flush_after_records: (writer.flush_after_records > 0).then_some(writer.flush_after_records),+ policy: deja::SinkPolicy::FailOpen,+ }+}++fn disabled_report(detail: Option<String>) -> InstallReport {+ InstallReport {+ mode: "disabled",+ run_id: None,+ detail,+ }+}++#[allow(clippy::print_stderr)] // The logger may not be initialized yet.+fn print_configuration_error(error: &str) {+ eprintln!("deja configuration error: {error}; runtime hook disabled");+}++fn try_install_hook(+ hook: deja::RuntimeHook,+ report: InstallReport,+) -> Result<InstallReport, String> {+ deja::set_global_runtime_hook(Some(hook))+ .map_err(|error| error.to_owned())+ .map(|()| report)+}++#[allow(clippy::print_stderr)] // The logger may not be initialized yet.+fn install_hook(hook: deja::RuntimeHook, report: InstallReport) -> InstallReport {+ match try_install_hook(hook, report) {+ Ok(report) => report,+ Err(error) => {+ eprintln!(+ "deja configuration error: {error}; requested runtime hook was not installed"+ );+ disabled_report(Some(error))+ }+ }+}++fn install_disabled(detail: Option<String>) -> InstallReport {+ if let Some(error) = detail.as_deref() {+ print_configuration_error(error);+ }+ install_hook(+ deja::RuntimeHook::Disabled(deja::DisabledHook),+ disabled_report(detail),+ )+}++fn install_record(settings: &DejaSettings, inherited_brokers: Option<&[String]>) -> InstallReport {+ let kafka = &settings.recording.kafka;+ let Some(topic) = kafka.effective_topic() else {+ return install_disabled(Some(+ "record mode requires deja.recording.kafka.topic".to_owned(),+ ));+ };++ // Broker resolution: an explicit deja broker list wins; an empty list+ // inherits the deployment's analytics Kafka brokers, so both producers+ // share cluster provisioning while remaining separate clients.+ let brokers: &[String] = if kafka.brokers.is_empty() {+ inherited_brokers.unwrap_or_default()+ } else {+ kafka.brokers.as_slice()+ };+ if brokers.is_empty() || brokers.iter().any(|broker| broker.trim().is_empty()) {+ return install_disabled(Some(+ "record mode requires Kafka brokers: set deja.recording.kafka.brokers, or \+ configure [events.kafka] brokers for the recording sink to inherit"+ .to_owned(),+ ));+ }++ let run_id = configured_run_id(settings);+ let sink = match HyperswitchKafkaRecordSink::new(HyperswitchKafkaRecordSinkConfig {+ brokers,+ topic,+ recording_run_id: &run_id,+ instance_id: resolved_instance_id(settings),+ code_sha: resolved_code_sha(settings),+ client_id: kafka.client_id.as_deref(),+ acks: &kafka.acks,+ enable_idempotence: kafka.idempotence,+ compression: kafka.compression.as_deref(),+ linger_ms: kafka.linger,+ message_timeout_ms: kafka.message_timeout.unwrap_or(30_000),+ queue_buffering_max_messages: kafka.queue_buffering_max_messages,+ }) {+ Ok(sink) => sink,+ Err(error) => {+ return install_disabled(Some(format!(+ "failed to create Deja Kafka producer for topic '{topic}': {error}"+ )));+ }+ };++ let hook = Arc::new(deja::RecordingHook::with_sink(+ sink,+ run_id.clone(),+ writer_config(settings),+ ));+ install_hook(+ deja::RuntimeHook::Recording(hook),+ InstallReport {+ mode: "record",+ run_id: Some(run_id),+ detail: Some(format!("Kafka topic '{topic}'")),+ },+ )+}++/// Resolve the lookup-table path from `deja.replay.{source, lookup_dir}` with+/// ONE rule and no shape-guessing:+/// - absolute `source` → that file, `lookup_dir` ignored+/// - relative `source` → a file name under `lookup_dir` (required)+/// - `lookup_dir` alone → `<lookup_dir>/<run_id>.jsonl` (`run_id` required)+///+/// Anything else is a configuration error.+fn replay_lookup_path(+ settings: &DejaSettings,+ replay: &DejaReplaySettings,+) -> Result<PathBuf, String> {+ let lookup_dir = replay+ .lookup_dir+ .as_deref()+ .filter(|dir| !dir.as_os_str().is_empty());+ match (non_empty(replay.source.as_deref()), lookup_dir) {+ (Some(source), _) if PathBuf::from(&source).is_absolute() => Ok(PathBuf::from(source)),+ (Some(source), Some(lookup_dir)) => Ok(lookup_dir.join(source)),+ (Some(source), None) => Err(format!(+ "deja.replay.source '{source}' is relative; set deja.replay.lookup_dir or make it absolute"+ )),+ (None, Some(lookup_dir)) => match settings.effective_run_id() {+ Some(run_id) => Ok(lookup_dir.join(format!("{run_id}.jsonl"))),+ None => Err(+ "deja.replay.lookup_dir without deja.replay.source requires deja.run_id"+ .to_owned(),+ ),+ },+ (None, None) => {+ Err("replay mode requires deja.replay.source or deja.replay.lookup_dir".to_owned())+ }+ }+}++fn install_replay(settings: &DejaSettings) -> Result<InstallReport, String> {+ let lookup_path = replay_lookup_path(settings, &settings.replay)?;++ let observed_sink = non_empty(settings.replay.observed_sink.as_deref());+ let hook = match observed_sink {+ Some(path) => match deja::FileObservedSink::create(path) {+ Ok(sink) => deja::LookupTableHook::from_source(+ deja::LocalFileLookupSource::new(lookup_path.clone()),+ sink,+ ),+ Err(error) => {+ return Err(format!(+ "failed to open replay observed sink '{path}': {error}"+ ));+ }+ },+ None => deja::LookupTableHook::from_source(+ deja::LocalFileLookupSource::new(lookup_path.clone()),+ deja::InMemoryObservedSink::new(),+ ),+ };++ let hook = hook.map_err(|error| {+ format!(+ "failed to load replay lookup table '{}': {error}",+ lookup_path.display()+ )+ })?;+ let entries = hook.entry_count();++ try_install_hook(+ deja::RuntimeHook::LookupReplay(hook),+ InstallReport {+ mode: "replay",+ run_id: settings.effective_run_id().map(str::to_owned),+ detail: Some(format!(+ "lookup table '{}' with {entries} entries",+ lookup_path.display()+ )),+ },+ )+ .map_err(|error| format!("failed to install replay runtime hook: {error}"))+}++/// Compose and install the process-wide Deja runtime hook from typed settings.+///+/// A hook is installed for every configured mode. Record misconfiguration never+/// aborts router boot and never leaves the process to lazily infer a mode later:+/// invalid record configuration installs a disabled hook with a clear pre-logger+/// error. Replay misconfiguration is fail-loud and aborts boot with the replay+/// error before logger setup.+pub fn install(+ settings: &DejaSettings,+ inherited_brokers: Option<&[String]>,+) -> Result<InstallReport, String> {+ // Graph capture is coupled to the mode (the graph layer rides the installed+ // Record/Replay hook), so there is no separate graph dial to declare here.+ match &settings.mode {+ DejaMode::Disabled => Ok(install_disabled(None)),+ DejaMode::Record => Ok(install_record(settings, inherited_brokers)),+ DejaMode::Replay => install_replay(settings),+ }+}diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex 7a1293bf8e..298990bc18 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -7,6 +7,8 @@ pub mod consts;pub mod core;pub mod cors;pub mod db;+#[cfg(feature = "deja")]+pub mod deja_boot;pub mod env;pub mod locale;pub(crate) mod macros;@@ -39,6 +41,70 @@ pub use self::env::logger;pub(crate) use self::macros::*;use crate::{configs::settings, core::errors};+#[cfg(feature = "deja")]+struct SuperpositionDejaRecordingSampler {+ superposition_service: std::sync::Arc<external_services::superposition::SuperpositionClient>,+ superposition_enabled: bool,+ record_key: String,+ timeout_ms: u64,+ /// Decision when the sampling source cannot answer (superposition+ /// disabled, lookup error, or timeout): `true` → don't record+ /// (production-safe default), `false` → record (demo/dev rigs that must+ /// never silently produce an empty tape).+ fail_closed: bool,+}++#[cfg(feature = "deja")]+impl router_env::request_id::RequestRecordingSampler for SuperpositionDejaRecordingSampler {+ fn should_record(+ &self,+ facts: router_env::request_id::RequestRecordingFacts,+ ) -> router_env::request_id::RequestRecordingSamplerFuture<'_> {+ // No sampling source to consult: the configured failure default+ // decides, exactly as it does for lookup errors and timeouts below.+ let failure_default = !self.fail_closed;+ if !self.superposition_enabled {+ return Box::pin(async move { failure_default });+ }++ let superposition_service = std::sync::Arc::clone(&self.superposition_service);+ let record_key = self.record_key.clone();+ let timeout_ms = self.timeout_ms.max(1);+ Box::pin(async move {+ let context = external_services::superposition::ConfigContext::new()+ .with("method", &facts.method)+ .with("path", &facts.path);+ let lookup = superposition_service.get_config_value::<bool>(+ &record_key,+ Some(&context),+ Some(&facts.request_id),+ );++ match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), lookup).await {+ Ok(Ok(decision)) => decision,+ Ok(Err(error)) => {+ router_env::logger::warn!(+ error = ?error,+ request_id = %facts.request_id,+ failure_default,+ "Failed to resolve Deja recording sampler decision; using configured failure default"+ );+ failure_default+ }+ Err(_elapsed) => {+ router_env::logger::warn!(+ timeout_ms,+ request_id = %facts.request_id,+ failure_default,+ "Timed out resolving Deja recording sampler decision; using configured failure default"+ );+ failure_default+ }+ }+ })+ }+}+#[cfg(feature = "mimalloc")]#[global_allocator]static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;@@ -124,10 +190,38 @@ pub fn mk_app(InitError = (),>,> {+ // The recording sampler exists exactly when the process records: record+ // mode always consults the sampling source per request, every other mode+ // has nothing to sample.+ #[cfg(feature = "deja")]+ let deja_recording_sampler: Option<+ std::sync::Arc<dyn router_env::request_id::RequestRecordingSampler>,+ > = matches!(state.conf.deja.mode, settings::DejaMode::Record).then(|| {+ let sampler: std::sync::Arc<dyn router_env::request_id::RequestRecordingSampler> =+ std::sync::Arc::new(SuperpositionDejaRecordingSampler {+ superposition_service: state.superposition_service.clone(),+ superposition_enabled: state.conf.superposition.get_inner().validate().is_ok(),+ record_key: state+ .conf+ .deja+ .sampler+ .record_key+ .as_deref()+ .filter(|record_key| !record_key.is_empty())+ .unwrap_or("deja_record")+ .to_owned(),+ timeout_ms: state.conf.deja.sampler.timeout_ms,+ fail_closed: state.conf.deja.sampler.fail_closed,+ });+ sampler+ });+let mut server_app = get_application_builder(request_body_limit,state.conf.cors.clone(),state.conf.trace_header.clone(),+ #[cfg(feature = "deja")]+ deja_recording_sampler,);#[cfg(feature = "dummy_connector")]@@ -394,6 +488,9 @@ pub fn get_application_builder(request_body_limit: usize,cors: settings::CorsSettings,trace_header: settings::TraceHeaderConfig,+ #[cfg(feature = "deja")] deja_recording_sampler: Option<+ std::sync::Arc<dyn router_env::request_id::RequestRecordingSampler>,+ >,) -> actix_web::App<impl ServiceFactory<ServiceRequest,@@ -408,6 +505,28 @@ pub fn get_application_builder(.content_type_required(true).error_handler(utils::error_parser::custom_json_error_handler);+ let request_identifier = router_env::RequestIdentifier::new(&trace_header.header_name)+ .use_incoming_id({+ #[cfg(feature = "deja")]+ {+ if deja::replay_is_active() {+ router_env::IdReuse::UseIncoming+ } else {+ trace_header.id_reuse_strategy+ }+ }+ #[cfg(not(feature = "deja"))]+ {+ trace_header.id_reuse_strategy+ }+ });++ #[cfg(feature = "deja")]+ let request_identifier = match deja_recording_sampler {+ Some(sampler) => request_identifier.with_recording_sampler(sampler),+ None => request_identifier,+ };+actix_web::App::new().app_data(json_cfg).wrap(ErrorHandlers::new().handler(@@ -428,8 +547,5 @@ pub fn get_application_builder(.wrap(router_env::tracing_actix_web::TracingLogger::<router_env::CustomRootSpanBuilder,>::new())- .wrap(- router_env::RequestIdentifier::new(&trace_header.header_name)- .use_incoming_id(trace_header.id_reuse_strategy),- )+ .wrap(request_identifier)}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 992fc4730a..d01ddb6fd4 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -157,6 +157,11 @@ impl scheduler::SchedulerSessionState for SessionState {fn add_request_id(&mut self, request_id: RequestId) {self.api_client.add_request_id(request_id.clone());self.store.add_request_id(request_id.to_string());+ #[cfg(feature = "deja")]+ {+ self.accounts_store.add_request_id(request_id.to_string());+ self.global_store.add_request_id(request_id.to_string());+ }self.request_id.replace(request_id);}}@@ -247,6 +252,11 @@ impl SessionStateInfo for SessionState {fn add_request_id(&mut self, request_id: RequestId) {self.api_client.add_request_id(request_id.clone());self.store.add_request_id(request_id.to_string());+ #[cfg(feature = "deja")]+ {+ self.accounts_store.add_request_id(request_id.to_string());+ self.global_store.add_request_id(request_id.to_string());+ }self.request_id.replace(request_id);}diff --git a/crates/router/src/services.rs b/crates/router/src/services.rsindex 1a07be00e8..27ee0c26cd 100644--- a/crates/router/src/services.rs+++ b/crates/router/src/services.rs@@ -125,7 +125,19 @@ pub async fn get_cache_store(RouterStore::<StoreType>::cache_store(&config.redis, shut_down_signal).await}+// deja: the per-merchant data-encryption key (DEK) is random. It is stored+// (master-key-encrypted) in merchant_key_store AND used to encrypt the merchant's+// own columns, so it must replay to the recorded value or the substituted DB rows+// and the response body diverge. Ok-only: the ring error type is non-serializable.#[inline]+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "router::services",+ operation = "generate_aes256_key",+ codec = ResultOkCodec,+ )+)]pub fn generate_aes256_key() -> errors::CustomResult<[u8; 32], common_utils::errors::CryptoError> {use ring::rand::SecureRandom;diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rsindex 263a6dac71..41f0eba3de 100644--- a/crates/router/src/services/jwt.rs+++ b/crates/router/src/services/jwt.rs@@ -5,6 +5,14 @@ use jsonwebtoken::{encode, EncodingKey, Header};use crate::{configs::Settings, core::errors::UserErrors};+// deja: JWT expiry uses a raw SystemTime::now() that bypasses the instrumented+// date_time::now boundary, so the `exp` claim (and thus the whole signed token)+// diverges on replay. Record/replay the absolute expiry (Ok-only) to reproduce+// byte-identical JWTs.+#[cfg_attr(+ feature = "deja",+ deja::id(component = "router::jwt", operation = "generate_exp", codec = ResultOkCodec,)+)]pub fn generate_exp(exp_duration: std::time::Duration,) -> CustomResult<std::time::Duration, UserErrors> {diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rsindex 49fe3852ef..12f5b20116 100644--- a/crates/router/src/services/kafka.rs+++ b/crates/router/src/services/kafka.rs@@ -17,6 +17,8 @@ use diesel_models::fraud_check::FraudCheck;use crate::{events::EventType, services::kafka::fraud_check_event::KafkaFraudCheckEvent};mod authentication;mod authentication_event;+#[cfg(feature = "deja")]+pub mod deja_record_sink;mod dispute;mod dispute_event;mod fraud_check;@@ -166,7 +168,29 @@ pub struct KafkaSettings {external_service_call_topic: String,}+/// Base rdkafka client configuration for this deployment's Kafka cluster.+///+/// Cluster-level settings (bootstrap servers, and any future deployment-wide+/// security options) live here so every producer in the process points at the+/// same provisioned cluster. The analytics producer uses it as-is; the Deja+/// recording sink layers its own delivery-guarantee overrides on top while+/// remaining a separate client with its own queue and delivery thread.+pub(crate) fn base_client_config(brokers: &[String]) -> rdkafka::ClientConfig {+ let mut config = rdkafka::ClientConfig::new();+ config.set("bootstrap.servers", brokers.join(","));+ config+}+impl KafkaSettings {+ /// Brokers of the provisioned Kafka cluster this deployment's analytics+ /// events use. The Deja recording sink inherits these when+ /// `deja.recording.kafka.brokers` is left empty, so both producers share+ /// cluster provisioning without sharing a client.+ #[cfg(feature = "deja")]+ pub fn brokers(&self) -> &[String] {+ &self.brokers+ }+pub fn validate(&self) -> Result<(), crate::core::errors::ApplicationError> {use common_utils::ext_traits::ConfigExt;@@ -327,10 +351,8 @@ impl KafkaProducer {pub async fn create(conf: &KafkaSettings) -> MQResult<Self> {Ok(Self {producer: Arc::new(RdKafkaProducer(- ThreadedProducer::from_config(- rdkafka::ClientConfig::new().set("bootstrap.servers", conf.brokers.join(",")),- )- .change_context(KafkaError::InitializationError)?,+ ThreadedProducer::from_config(&base_client_config(&conf.brokers))+ .change_context(KafkaError::InitializationError)?,)),fraud_check_analytics_topic: conf.fraud_check_analytics_topic.clone(),diff --git a/crates/router/src/services/kafka/deja_record_sink.rs b/crates/router/src/services/kafka/deja_record_sink.rsnew file mode 100644index 0000000000..9dd219a6bb--- /dev/null+++ b/crates/router/src/services/kafka/deja_record_sink.rs@@ -0,0 +1,642 @@+//! Deja recording sink: Kafka is THE record transport (no JSONL primary).+//!+//! The `deja-record` crate intentionally has no Kafka dependency: it defines+//! the `RecordSink<DejaRecord>` trait; this module supplies the transport.+//! The sink owns a DEDICATED `rdkafka` producer — deliberately not the shared+//! analytics producer, though both are built from the same deployment-wide+//! base client config so they share cluster provisioning — hardened for+//! durability:+//!+//! acks=all + enable.idempotence → no acked-then-lost, no broker-side dupes+//! bounded buffering → backpressure surfaces as enqueue errors+//! instead of unbounded memory+//! flush = short poll → cadence flushes never park the writer+//! behind a slow broker; only the eof+//! marker drains fully, so end-of-run+//! means delivered+//!+//! Envelopes, all on the ONE topic: boundary events land as+//! `deja.artifact_record/v2`; execution-graph nodes land as+//! `deja.graph_node/v1`. Both carry producer identity (`instance_id`),+//! capture window (`capture.mode`/`session_id`), and code provenance+//! (`code.sha` from typed Deja identity settings, `code.deja_version`).+//! Loss accounting rides the same topic as `deja_sink_marker` envelopes+//! (checkpoint / eof / dropped), emitted by the writer through+//! `write_marker` — the compactor skips them when building sessions;+//! auditors read them to verify delivery.+//!+//! Partition key: `correlation_id` when present, otherwise+//! `{recording_run_id}:{global_sequence}` so background-task events still+//! land deterministically.+//! Headers: `global_sequence`, `request_sequence`, `recording_run_id`,+//! `boundary`, `method_name` — sufficient for a Vector consumer to route+//! and structure without parsing the payload.+//!+//! Delivery semantics: enqueue errors surface as `io::Error` to the async+//! writer, which accounts the affected batch as dropped (with a `dropped`+//! marker) and keeps going; only a sustained failure streak disables+//! recording. Request threads are never failed by instrumentation.++use std::{io, time::Duration};++use rdkafka::{+ config::FromClientConfig,+ message::{Header, OwnedHeaders},+ producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer},+};+use serde::Serialize;++const SCHEMA_VERSION: u32 = 2;+const ARTIFACT_TYPE: &str = "deja_artifact_record";+const GRAPH_SCHEMA_VERSION: u32 = 1;+const GRAPH_ARTIFACT_TYPE: &str = "deja_graph_node";+const MARKER_ARTIFACT_TYPE: &str = "deja_sink_marker";+/// Cadence flushes are a short bounded poll: the threaded producer delivers on+/// its own background thread, so waiting out a long drain here only parks the+/// writer thread behind a slow broker.+const CADENCE_FLUSH_POLL: Duration = Duration::from_millis(50);+/// End-of-run drain: the eof marker means "everything before this landed", so+/// shutdown waits for real delivery.+const EOF_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);++#[derive(Serialize)]+struct Capture<'a> {+ mode: &'static str,+ session_id: &'a str,+}++#[derive(Serialize)]+struct Code<'a> {+ sha: Option<&'a str>,+ deja_version: &'static str,+}++#[derive(Serialize)]+struct Envelope<'a> {+ schema_version: u32,+ artifact_type: &'static str,+ instance_id: &'a str,+ recording_run_id: &'a str,+ correlation_id: Option<&'a str>,+ event_time_ns: u64,+ capture: Capture<'a>,+ code: Code<'a>,+ event: &'a deja::BoundaryEvent,+}++/// Graph-node envelope (`deja.graph_node/v1`): same stream, same session+/// identity as the artifact envelope, the execution-graph node as payload.+/// Nested under `node` — the node carries its own `recording_run_id` /+/// `global_sequence`, so flattening would collide with the envelope's.+#[derive(Serialize)]+struct GraphEnvelope<'a> {+ schema_version: u32,+ artifact_type: &'static str,+ instance_id: &'a str,+ recording_run_id: &'a str,+ capture: Capture<'a>,+ code: Code<'a>,+ node: &'a deja_core::ExecutionGraphNode,+}++/// Marker envelope: same stream, same session identity, no event payload.+#[derive(Serialize)]+struct MarkerEnvelope<'a> {+ schema_version: u32,+ artifact_type: &'static str,+ instance_id: &'a str,+ recording_run_id: &'a str,+ capture: Capture<'a>,+ code: Code<'a>,+ marker: MarkerBody<'a>,+}++#[derive(Serialize)]+struct MarkerBody<'a> {+ kind: &'static str,+ #[serde(flatten)]+ payload: &'a serde_json::Value,+}++pub struct HyperswitchKafkaRecordSinkConfig<'a> {+ pub brokers: &'a [String],+ pub topic: &'a str,+ pub recording_run_id: &'a str,+ pub instance_id: String,+ pub code_sha: Option<String>,+ pub client_id: Option<&'a str>,+ pub acks: &'a str,+ pub enable_idempotence: bool,+ pub compression: Option<&'a str>,+ pub linger_ms: Option<u64>,+ pub message_timeout_ms: u64,+ pub queue_buffering_max_messages: usize,+}++/// `RecordSink<deja::DejaRecord>` implementation over a deja-owned,+/// durability-hardened Kafka producer.+pub struct HyperswitchKafkaRecordSink {+ producer: ThreadedProducer<DefaultProducerContext>,+ topic: String,+ recording_run_id: String,+ /// Typed producer identity resolved during Deja boot; distinguishes+ /// producers when several instances feed one session.+ instance_id: String,+ /// Typed code identity resolved during Deja boot; `None` when unavailable.+ code_sha: Option<String>,+}++impl HyperswitchKafkaRecordSink {+ /// Build the sink with its own hardened producer from the broker list of+ /// Hyperswitch's events config (the brokers are shared; the producer and+ /// its delivery guarantees are not).+ pub fn new(config: HyperswitchKafkaRecordSinkConfig<'_>) -> io::Result<Self> {+ // Start from the deployment-wide base client config (shared cluster+ // provisioning), then layer the recording sink's delivery guarantees+ // on top — a separate client with its own queue and delivery thread.+ let mut producer_config = super::base_client_config(config.brokers);+ producer_config+ .set("acks", config.acks)+ .set(+ "enable.idempotence",+ if config.enable_idempotence {+ "true"+ } else {+ "false"+ },+ )+ .set("message.timeout.ms", config.message_timeout_ms.to_string())+ // Bounded buffering: a dead broker turns into enqueue errors+ // (counted + ledgered by the writer), not unbounded memory.+ .set(+ "queue.buffering.max.messages",+ config.queue_buffering_max_messages.to_string(),+ )+ .set("queue.buffering.max.kbytes", "262144");++ if let Some(client_id) = config.client_id.filter(|value| !value.is_empty()) {+ producer_config.set("client.id", client_id);+ }+ if let Some(compression) = config.compression.filter(|value| !value.is_empty()) {+ producer_config.set("compression.type", compression);+ }+ if let Some(linger_ms) = config.linger_ms {+ producer_config.set("linger.ms", linger_ms.to_string());+ }++ let producer = ThreadedProducer::from_config(&producer_config)+ .map_err(|e| io::Error::other(format!("deja kafka producer: {e}")))?;+ Ok(Self {+ producer,+ topic: config.topic.to_owned(),+ recording_run_id: config.recording_run_id.to_owned(),+ instance_id: config.instance_id,+ code_sha: config.code_sha,+ })+ }++ fn send(&self, key: &str, payload: &[u8], headers: OwnedHeaders) -> io::Result<()> {+ self.producer+ .send(+ BaseRecord::to(&self.topic)+ .key(key)+ .payload(payload)+ .headers(headers),+ )+ .map_err(|(error, _record)| io::Error::other(format!("kafka send: {error}")))+ }++ fn write_boundary_event(&self, event: &deja::BoundaryEvent) -> io::Result<()> {+ let envelope = Envelope {+ schema_version: SCHEMA_VERSION,+ artifact_type: ARTIFACT_TYPE,+ instance_id: &self.instance_id,+ recording_run_id: &self.recording_run_id,+ correlation_id: event.correlation_id.as_deref(),+ event_time_ns: event.timestamp_ns,+ capture: Capture {+ // Session capture is the only mode today; a windowed+ // capture mode is a planned extension.+ mode: "session",+ session_id: &self.recording_run_id,+ },+ code: Code {+ sha: self.code_sha.as_deref(),+ deja_version: deja::PKG_VERSION,+ },+ event,+ };+ let payload = serde_json::to_vec(&envelope).map_err(io::Error::other)?;++ let key = match &event.correlation_id {+ Some(cid) => cid.clone(),+ None => format!("{}:{}", self.recording_run_id, event.global_sequence),+ };++ let global_seq = event.global_sequence.to_string();+ let request_seq = event.request_sequence.to_string();+ let headers = OwnedHeaders::new()+ .insert(Header {+ key: "global_sequence",+ value: Some(global_seq.as_str()),+ })+ .insert(Header {+ key: "request_sequence",+ value: Some(request_seq.as_str()),+ })+ .insert(Header {+ key: "recording_run_id",+ value: Some(self.recording_run_id.as_str()),+ })+ .insert(Header {+ key: "boundary",+ value: Some(event.boundary.as_str()),+ })+ .insert(Header {+ key: "method_name",+ value: Some(event.method_name.as_str()),+ });++ self.send(&key, &payload, headers)+ }++ fn write_graph_node(&self, node: &deja_core::ExecutionGraphNode) -> io::Result<()> {+ let envelope = GraphEnvelope {+ schema_version: GRAPH_SCHEMA_VERSION,+ artifact_type: GRAPH_ARTIFACT_TYPE,+ instance_id: &self.instance_id,+ recording_run_id: &self.recording_run_id,+ capture: Capture {+ mode: "session",+ session_id: &self.recording_run_id,+ },+ code: Code {+ sha: self.code_sha.as_deref(),+ deja_version: deja::PKG_VERSION,+ },+ node,+ };+ let payload = serde_json::to_vec(&envelope).map_err(io::Error::other)?;++ // Partition alongside the request's boundary events when the span+ // carries the request id; background spans key on stream identity.+ let key = match node.request_id() {+ Some(request_id) => request_id.to_owned(),+ None => format!("{}:{}", self.recording_run_id, node.global_sequence),+ };++ let global_seq = node.global_sequence.to_string();+ let headers = OwnedHeaders::new()+ .insert(Header {+ key: "global_sequence",+ value: Some(global_seq.as_str()),+ })+ .insert(Header {+ key: "recording_run_id",+ value: Some(self.recording_run_id.as_str()),+ })+ .insert(Header {+ key: "span_name",+ value: Some(node.span_name.as_str()),+ });++ self.send(&key, &payload, headers)+ }+}++impl deja::RecordSink<deja::DejaRecord> for HyperswitchKafkaRecordSink {+ fn write_batch(&mut self, records: &[deja::DejaRecord]) -> io::Result<()> {+ for record in records {+ match record {+ deja::DejaRecord::BoundaryEvent(event) => self.write_boundary_event(event)?,+ deja::DejaRecord::GraphNode(node) => self.write_graph_node(node)?,+ // Record mode never produces observations; skip instead of+ // failing the writer if the library contract is breached.+ deja::DejaRecord::Observed(_) => {+ debug_assert!(false, "observed record reached the record-mode Kafka sink");+ }+ }+ }+ Ok(())+ }++ fn flush(&mut self) -> io::Result<()> {+ // Cadence flush: a short bounded poll. Delivery happens continuously on+ // the producer's own background thread; a long synchronous drain here+ // would park the writer thread behind a slow broker, backing up the+ // record channel into the request path. Messages still in flight when+ // the poll expires are NOT a sink failure — enqueue errors in+ // write_batch are where saturation and broker loss actually surface.+ match self.producer.flush(CADENCE_FLUSH_POLL) {+ Ok(()) => Ok(()),+ Err(rdkafka::error::KafkaError::Flush(+ rdkafka::types::RDKafkaErrorCode::OperationTimedOut,+ )) => Ok(()),+ Err(e) => Err(io::Error::other(format!("kafka flush: {e}"))),+ }+ }++ fn write_marker(+ &mut self,+ kind: deja::MarkerKind,+ payload: &serde_json::Value,+ ) -> io::Result<()> {+ let envelope = MarkerEnvelope {+ schema_version: SCHEMA_VERSION,+ artifact_type: MARKER_ARTIFACT_TYPE,+ instance_id: &self.instance_id,+ recording_run_id: &self.recording_run_id,+ capture: Capture {+ mode: "session",+ session_id: &self.recording_run_id,+ },+ code: Code {+ sha: self.code_sha.as_deref(),+ deja_version: deja::PKG_VERSION,+ },+ marker: MarkerBody {+ kind: kind.as_str(),+ payload,+ },+ };+ let bytes = serde_json::to_vec(&envelope).map_err(io::Error::other)?;+ let key = format!("{}:marker", self.recording_run_id);+ let headers = OwnedHeaders::new()+ .insert(Header {+ key: "recording_run_id",+ value: Some(self.recording_run_id.as_str()),+ })+ .insert(Header {+ key: "marker_kind",+ value: Some(kind.as_str()),+ });+ self.send(&key, &bytes, headers)?;+ // The eof marker bounds delivery audits — drain for real so "eof+ // landed" means everything before it landed too.+ if matches!(kind, deja::MarkerKind::Eof) {+ let _ = self.producer.flush(EOF_FLUSH_TIMEOUT);+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn envelope_serializes_artifact_record_v2_shape() {+ let event = deja::BoundaryEvent {+ global_sequence: 7,+ request_sequence: 2,+ correlation_id: Some("c-123".to_string()),+ timestamp_ns: 1_000_000_000,+ recording_run_id: Some("run-abc".to_string()),+ graph_node_id: None,+ tracing_span_id: None,+ task_id: None,+ parent_task_id: None,+ task_bucket: None,+ bucket_id: None,+ fork_seq: None,+ boundary: "redis".to_string(),+ trait_name: "RedisConnectionInterface".to_string(),+ method_name: "get_key".to_string(),+ call_file: "x.rs".to_string(),+ call_line: 10,+ call_column: 5,+ receiver: None,+ request: serde_json::Value::Null,+ args: serde_json::json!({"key": "foo"}),+ response: serde_json::Value::Null,+ result: serde_json::json!("bar"),+ is_error: false,+ duration_us: 42,+ event_schema_version: deja::CURRENT_EVENT_SCHEMA_VERSION,+ callsite_identity: None,+ provenance: deja::Provenance::default(),+ fidelity: deja::Fidelity::default(),+ result_image: None,+ pre_image: None,+ read_set: Vec::new(),+ write_set: Vec::new(),+ value_digest: None,+ entropy_source: None,+ replay_strategy: deja::ReplayStrategy::Execute,+ kind: Some("redis".to_string()),+ declaration: Some(deja::BoundaryDeclaration::default().effect(deja::EffectKind::Redis)),+ raw_draw: None,+ end_timestamp_ns: Some(1_000_000_042),+ };+ let envelope = Envelope {+ schema_version: 2,+ artifact_type: "deja_artifact_record",+ instance_id: "router-testhost-1",+ recording_run_id: "run-abc",+ correlation_id: event.correlation_id.as_deref(),+ event_time_ns: event.timestamp_ns,+ capture: Capture {+ mode: "session",+ session_id: "run-abc",+ },+ code: Code {+ sha: Some("deadbeef"),+ deja_version: deja::PKG_VERSION,+ },+ event: &event,+ };+ let value: serde_json::Value =+ serde_json::from_slice(&serde_json::to_vec(&envelope).unwrap()).unwrap();+ assert_eq!(+ value.pointer("/schema_version"),+ Some(&serde_json::json!(2))+ );+ assert_eq!(+ value.pointer("/artifact_type"),+ Some(&serde_json::json!("deja_artifact_record"))+ );+ assert_eq!(+ value.pointer("/instance_id"),+ Some(&serde_json::json!("router-testhost-1"))+ );+ assert_eq!(+ value.pointer("/recording_run_id"),+ Some(&serde_json::json!("run-abc"))+ );+ assert_eq!(+ value.pointer("/correlation_id"),+ Some(&serde_json::json!("c-123"))+ );+ assert_eq!(+ value.pointer("/event_time_ns"),+ Some(&serde_json::json!(1_000_000_000u64))+ );+ assert_eq!(+ value.pointer("/capture/mode"),+ Some(&serde_json::json!("session"))+ );+ assert_eq!(+ value.pointer("/capture/session_id"),+ Some(&serde_json::json!("run-abc"))+ );+ assert_eq!(+ value.pointer("/code/sha"),+ Some(&serde_json::json!("deadbeef"))+ );+ assert_eq!(+ value.pointer("/code/deja_version"),+ Some(&serde_json::json!(deja::PKG_VERSION))+ );+ assert_eq!(+ value.pointer("/event/boundary"),+ Some(&serde_json::json!("redis"))+ );+ assert_eq!(+ value.pointer("/event/method_name"),+ Some(&serde_json::json!("get_key"))+ );+ assert_eq!(+ value.pointer("/event/global_sequence"),+ Some(&serde_json::json!(7))+ );+ // The sink unwraps `DejaRecord` before enveloping: the payload is the+ // plain event, never the internally tagged record.+ assert!(value.pointer("/event/record_kind").is_none());+ }++ #[test]+ fn graph_envelope_serializes_graph_node_v1_shape() {+ let node = deja_core::ExecutionGraphNode {+ node_id: 7,+ global_sequence: 42,+ parent_id: Some(3),+ causal_parent_ids: vec![1],+ sequence: 5,+ recording_run_id: Some("run-abc".to_string()),+ span_name: "payment.request".to_string(),+ target: "router".to_string(),+ level: "INFO".to_string(),+ fields: [("request_id".to_string(), serde_json::json!("c-123"))]+ .into_iter()+ .collect(),+ started_ns: 1_000_000_000,+ closed_ns: Some(1_000_000_042),+ };+ let envelope = GraphEnvelope {+ schema_version: 1,+ artifact_type: "deja_graph_node",+ instance_id: "router-testhost-1",+ recording_run_id: "run-abc",+ capture: Capture {+ mode: "session",+ session_id: "run-abc",+ },+ code: Code {+ sha: Some("deadbeef"),+ deja_version: deja::PKG_VERSION,+ },+ node: &node,+ };+ let value: serde_json::Value =+ serde_json::from_slice(&serde_json::to_vec(&envelope).unwrap()).unwrap();+ assert_eq!(+ value.pointer("/schema_version"),+ Some(&serde_json::json!(1))+ );+ assert_eq!(+ value.pointer("/artifact_type"),+ Some(&serde_json::json!("deja_graph_node"))+ );+ assert_eq!(+ value.pointer("/instance_id"),+ Some(&serde_json::json!("router-testhost-1"))+ );+ assert_eq!(+ value.pointer("/recording_run_id"),+ Some(&serde_json::json!("run-abc"))+ );+ assert_eq!(+ value.pointer("/capture/mode"),+ Some(&serde_json::json!("session"))+ );+ assert_eq!(+ value.pointer("/capture/session_id"),+ Some(&serde_json::json!("run-abc"))+ );+ assert_eq!(+ value.pointer("/code/sha"),+ Some(&serde_json::json!("deadbeef"))+ );+ assert_eq!(+ value.pointer("/code/deja_version"),+ Some(&serde_json::json!(deja::PKG_VERSION))+ );+ assert_eq!(value.pointer("/node/node_id"), Some(&serde_json::json!(7)));+ assert_eq!(+ value.pointer("/node/global_sequence"),+ Some(&serde_json::json!(42))+ );+ assert_eq!(+ value.pointer("/node/span_name"),+ Some(&serde_json::json!("payment.request"))+ );+ assert_eq!(+ value.pointer("/node/fields/request_id"),+ Some(&serde_json::json!("c-123"))+ );+ assert_eq!(+ value.pointer("/node/closed_ns"),+ Some(&serde_json::json!(1_000_000_042u64))+ );+ assert!(value.pointer("/node/record_kind").is_none());+ // No event payload on graph envelopes — the compactor routes by type.+ assert!(value.get("event").is_none());+ }++ #[test]+ fn marker_envelope_serializes_sink_marker_shape() {+ let payload = serde_json::json!({ "last_seq": 206, "records_written": 207 });+ let envelope = MarkerEnvelope {+ schema_version: 2,+ artifact_type: "deja_sink_marker",+ instance_id: "router-testhost-1",+ recording_run_id: "run-abc",+ capture: Capture {+ mode: "session",+ session_id: "run-abc",+ },+ code: Code {+ sha: Some("deadbeef"),+ deja_version: deja::PKG_VERSION,+ },+ marker: MarkerBody {+ kind: "eof",+ payload: &payload,+ },+ };+ let value: serde_json::Value =+ serde_json::from_slice(&serde_json::to_vec(&envelope).unwrap()).unwrap();+ assert_eq!(+ value.pointer("/artifact_type"),+ Some(&serde_json::json!("deja_sink_marker"))+ );+ assert_eq!(+ value.pointer("/marker/kind"),+ Some(&serde_json::json!("eof"))+ );+ assert_eq!(+ value.pointer("/marker/last_seq"),+ Some(&serde_json::json!(206))+ );+ assert_eq!(+ value.pointer("/code/sha"),+ Some(&serde_json::json!("deadbeef"))+ );+ assert_eq!(+ value.pointer("/code/deja_version"),+ Some(&serde_json::json!(deja::PKG_VERSION))+ );+ // No event payload on markers — the compactor skips them by type.+ assert!(value.get("event").is_none());+ }+}diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rsindex 906adec917..f32f2d60c8 100644--- a/crates/router/src/types/domain/user.rs+++ b/crates/router/src/types/domain/user.rs@@ -993,6 +993,17 @@ impl NewUser {}}+// deja: the signup user_id is a raw random UUIDv4. Wrapped in an annotated helper+// so it replays to the recorded value — otherwise the `users` INSERT diverges and+// runs live (collides with the record-phase user, rolling signup back).+#[cfg_attr(+ feature = "deja",+ deja::id(component = "router::user", operation = "generate_user_id", codec = SerdeCodec,)+)]+fn generate_user_id() -> String {+ uuid::Uuid::new_v4().to_string()+}+impl TryFrom<NewUser> for storage_user::UserNew {type Error = error_stack::Report<UserErrors>;@@ -1005,7 +1016,7 @@ impl TryFrom<NewUser> for storage_user::UserNew {let now = common_utils::date_time::now();Ok(Self {- user_id: uuid::Uuid::new_v4().to_string(),+ user_id: generate_user_id(),name: value.get_name(),email: value.get_email().into_inner(),password: hashed_password,diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex f9dc7464dd..bb31555b5f 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -116,7 +116,15 @@ pub mod error_parser {}}+// deja: a nanoid-based random id distinct from common_utils::generate_id. Used+// for merchant fingerprint secrets and other persisted ids, so it must replay to+// the recorded value or the substituted INSERT args diverge (and a live insert+// collides with the record-phase row).#[inline]+#[cfg_attr(+ feature = "deja",+ deja::id(component = "router::utils", operation = "generate_id", codec = SerdeCodec,)+)]pub fn generate_id(length: usize, prefix: &str) -> String {format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS))}diff --git a/crates/router/src/utils/user/password.rs b/crates/router/src/utils/user/password.rsindex 36c1536fc0..9912b395c5 100644--- a/crates/router/src/utils/user/password.rs+++ b/crates/router/src/utils/user/password.rs@@ -15,13 +15,34 @@ use crate::core::errors::UserErrors;pub fn generate_password_hash(password: Secret<String>,) -> CustomResult<Secret<String>, UserErrors> {+ generate_password_hash_inner(password).map(Secret::new)+}++// deja: the Argon2 salt is random (OsRng), so the hash is non-deterministic. On+// replay the recorded user row never matches (the `users` INSERT then executes+// LIVE, collides with the record-phase user, and signup rolls everything back ->+// HE_00). Record/replay the hash string so the user row is reproducible. The+// annotated fn returns a PLAIN String (not Secret) on purpose: masking::Secret+// serializes lossily to "***", which would record/replay a useless masked value;+// the plain String records the real hash losslessly. The `password` arg still+// masks to "***" in the recorded args — that's fine, it's consistent across+// record/replay and avoids leaking the secret. Uses the Ok-only codec for the Result.+#[cfg_attr(+ feature = "deja",+ deja::id(+ component = "router::user::password",+ operation = "generate_password_hash",+ codec = ResultOkCodec,+ )+)]+fn generate_password_hash_inner(password: Secret<String>) -> CustomResult<String, UserErrors> {let salt = SaltString::generate(&mut OsRng);let argon2 = Argon2::default();let password_hash = argon2.hash_password(password.expose().as_bytes(), &salt).change_context(UserErrors::InternalServerError)?;- Ok(Secret::new(password_hash.to_string()))+ Ok(password_hash.to_string())}pub fn is_correct_password(diff --git a/crates/router/tests/deja_boot_fail_loud.rs b/crates/router/tests/deja_boot_fail_loud.rsnew file mode 100644index 0000000000..9de332cae1--- /dev/null+++ b/crates/router/tests/deja_boot_fail_loud.rs@@ -0,0 +1,50 @@+#![cfg(feature = "deja")]++use router::configs::settings::{DejaMode, DejaSettings};++fn settings_for(mode: DejaMode) -> DejaSettings {+ DejaSettings {+ mode,+ ..DejaSettings::default()+ }+}++#[test]+fn replay_mode_without_source_or_lookup_dir_fails_loudly() {+ let err = router::deja_boot::install(&settings_for(DejaMode::Replay), None)+ .expect_err("replay mode without source or lookup_dir must abort boot");++ assert!(+ err.contains("deja.replay.source") && err.contains("deja.replay.lookup_dir"),+ "error should mention the missing replay source/lookup_dir, got: {err}"+ );+}++#[test]+fn replay_mode_with_missing_lookup_source_fails_loudly() {+ let missing_source =+ "/__hyperswitch_w3_deja_replay_lookup_table_must_not_exist__/missing.lookup.json";+ let mut settings = settings_for(DejaMode::Replay);+ settings.replay.source = Some(missing_source.to_owned());++ let err = router::deja_boot::install(&settings, None)+ .expect_err("replay mode with a missing lookup table source must abort boot");++ assert!(+ err.contains("failed to load replay lookup table") && err.contains(missing_source),+ "error should mention lookup-table load failure for {missing_source}, got: {err}"+ );+}++#[test]+fn record_mode_without_kafka_topic_fails_open_with_disabled_report() {+ let report = router::deja_boot::install(&settings_for(DejaMode::Record), None)+ .expect("record-mode Kafka topic misconfiguration should fail open");++ assert_eq!(report.mode, "disabled");+ assert_eq!(report.run_id, None);+ assert_eq!(+ report.detail.as_deref(),+ Some("record mode requires deja.recording.kafka.topic")+ );+}diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.tomlindex 7f6451838c..2fa3478954 100644--- a/crates/router_env/Cargo.toml+++ b/crates/router_env/Cargo.toml@@ -10,10 +10,14 @@ license.workspace = true[dependencies]cargo_metadata = "0.18.1"config = { version = "0.14.1", features = ["toml"] }-deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }-deja-core = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true }+deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }+deja-core = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true }error-stack = "0.4.1"gethostname = "0.4.3"+# Optional (deja-only): types the captured request/response payloads as `Secret`+# so bodies/headers are redacted in Debug/logs. Feature-off it is absent, so the+# default build is byte-identical.+hyperswitch_masking = { version = "0.0.1", optional = true }opentelemetry = { version = "0.27.1", default-features = false, features = ["internal-logs", "metrics", "trace"] }opentelemetry-aws = { version = "0.15.0", default-features = false, features = ["internal-logs", "trace"] }opentelemetry-otlp = { version = "0.27.0", default-features = false, features = ["grpc-tonic", "metrics", "trace"] }@@ -49,7 +53,7 @@ actix_web = ["dep:actix-web", "tracing-actix-web", "dep:uuid"]log_custom_entries_to_extra = []log_extra_implicit_fields = []log_active_span_json = []-deja = ["dep:bytes", "dep:deja", "dep:deja-core"]+deja = ["dep:bytes", "dep:deja", "dep:deja-core", "dep:hyperswitch_masking"]payouts = [][lints]diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rsindex 7447c8787e..bcf3f14a07 100644--- a/crates/router_env/src/logger/setup.rs+++ b/crates/router_env/src/logger/setup.rs@@ -64,8 +64,12 @@ pub fn setup(let subscriber = tracing_subscriber::registry().with(traces_layer)- .with(StorageSubscription)- .with(file_writer);+ .with(StorageSubscription);+ // Both deja layers are added only under the feature, so a feature-off+ // subscriber carries exactly the layers above and nothing else.+ #[cfg(feature = "deja")]+ let subscriber = subscriber.with(deja_layer()).with(deja_correlation_layer());+ let subscriber = subscriber.with(file_writer);// Setup console loggingif config.console.enabled {@@ -119,6 +123,62 @@ pub fn setup(})}+#[cfg(feature = "deja")]+struct RuntimeHookGraphSink(std::sync::Arc<deja::RuntimeHook>);++#[cfg(feature = "deja")]+impl deja::GraphNodeSink for RuntimeHookGraphSink {+ fn graph_node(&self, node: deja_core::ExecutionGraphNode) {+ match self.0.as_ref() {+ deja::RuntimeHook::Recording(hook) => {+ deja::GraphNodeSink::graph_node(hook.as_ref(), node)+ }+ deja::RuntimeHook::LookupReplay(hook) => deja::GraphNodeSink::graph_node(hook, node),+ _ => {}+ }+ }+}++#[cfg(feature = "deja")]+fn deja_layer() -> Option<deja::ExecutionGraphLayer> {+ // Coupled to the runtime mode, exactly like `deja_correlation_layer`: the+ // graph rides whichever Record/Replay hook is installed, or it is absent.+ // No separate on/off knob (that default-off dial silently dropped graph+ // nodes); a recording IS a graph recording.+ let hook = deja::installed_runtime_hook()?;+ match hook.as_ref() {+ deja::RuntimeHook::Recording(_) | deja::RuntimeHook::LookupReplay(_) => Some(+ deja::ExecutionGraphLayer::new(std::sync::Arc::new(RuntimeHookGraphSink(hook))),+ ),+ _ => None,+ }+}++/// Correlation-propagation layer: mirrors the ingress `request_id` span field into+/// deja-context so boundary events fired from spawned tasks (which escape the+/// middleware's `scope_correlation` future wrapper but carry the span via+/// `.in_current_span()`) inherit the request correlation instead of recording+/// uncorrelated. Only installed while recording or replaying — in normal+/// operation it is `None`, adding zero per-span overhead.+#[cfg(feature = "deja")]+fn deja_correlation_layer() -> Option<deja::DejaCorrelationLayer> {+ // MUST use `process_runtime_mode`, not `runtime_mode`. This runs once at+ // tracing setup (process start), before any request has pushed a recording+ // decision. `runtime_mode` reads the per-request-gated `mode()`, which is+ // `Disabled` for a record hook until a decision exists — so gating on it+ // here would leave the correlation layer uninstalled, and boundary events+ // from spawned tasks would never inherit the request correlation (their+ // per-boundary gate then resolves no decision and records nothing). Same+ // circular-dependency shape as the ingress predicates; `process_runtime_mode`+ // reflects the boot-time configuration and peeks the installed hook. This+ // mirrors `deja_layer` above, which keys off the installed hook variant.+ if deja::process_runtime_mode().consumes_args() {+ Some(deja::DejaCorrelationLayer::new())+ } else {+ None+ }+}+fn get_opentelemetry_exporter_config(config: &config::LogTelemetry,) -> opentelemetry_otlp::ExportConfig {diff --git a/crates/router_env/src/request_id.rs b/crates/router_env/src/request_id.rsindex 8400d8d8e6..c536b06509 100644--- a/crates/router_env/src/request_id.rs+++ b/crates/router_env/src/request_id.rs@@ -36,6 +36,8 @@ use std::{task::{Context, Poll},};+#[cfg(feature = "deja")]+use actix_web::body::EitherBody;use actix_web::{dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},error::ResponseError,@@ -43,8 +45,456 @@ use actix_web::{Error as ActixError, FromRequest, HttpMessage, HttpRequest,};use error_stack::{report, ResultExt};+#[cfg(feature = "deja")]+use tracing::Instrument;use uuid::Uuid;+#[cfg(feature = "deja")]+pub(crate) mod boundary {+ use std::{+ fmt,+ future::Future,+ panic::Location,+ pin::Pin,+ sync::{Arc, OnceLock},+ task::{Context, Poll},+ };++ use actix_web::{+ body::{BodySize, MessageBody},+ dev::{Payload, ServiceRequest, ServiceResponse},+ http::header::{HeaderMap, CONTENT_LENGTH, CONTENT_TYPE},+ Error as ActixError,+ };+ use bytes::Bytes;+ use deja::DejaHook;+ use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};+ use serde_json::json;++ static HOOK: OnceLock<Option<Arc<deja::RuntimeHook>>> = OnceLock::new();++ fn hook() -> Option<&'static Arc<deja::RuntimeHook>> {+ HOOK.get_or_init(deja::global_runtime_hook_from_env)+ .as_ref()+ }++ /// PROCESS-level "is deja on?" for the ingress middleware.+ ///+ /// This MUST read `process_mode`, not `mode`. `mode` on a recorder ANDs in+ /// the per-correlation sampling decision, and the ingress middleware is the+ /// thing that PUSHES that decision — gating ingress on `mode` is circular+ /// (no request is ever recorded because the decision is never set because+ /// the block that sets it is gated on the decision). `process_mode` reflects+ /// only the boot-time configuration, so it is stable before any decision+ /// exists.+ pub(super) fn process_is_active() -> bool {+ hook()+ .map(Arc::as_ref)+ .is_some_and(|hook| !hook.process_mode().is_disabled())+ }++ /// PROCESS-level "is this a record candidate?" for the ingress middleware.+ /// Reads `process_mode` for the same reason as [`process_is_active`].+ pub(super) fn process_is_record_mode() -> bool {+ hook()+ .map(Arc::as_ref)+ .is_some_and(|hook| hook.process_mode().is_record())+ }++ pub(super) fn record_id_generation(+ method_name: &'static str,+ caller: &'static Location<'static>,+ request: Secret<serde_json::Value>,+ response: Secret<serde_json::Value>,+ ) {+ let Some(hook) = hook() else {+ return;+ };+ if !hook.capture_verdict().should_capture() {+ return;+ }+ // Expose only at the deja recording boundary — `EventBuilder` takes a raw+ // `serde_json::Value`. The payloads stay `Secret` everywhere else so they+ // are redacted in Debug/logs.+ let event = deja::EventBuilder::start(+ hook.as_ref(),+ "id_generation",+ "router_env::request_id",+ method_name,+ caller,+ request.expose(),+ );+ event.finish(hook.as_ref(), response.expose(), false);+ }++ /// Replay substitution for id generation.+ ///+ /// In replay mode the active hook is a lookup-table hook; this returns the+ /// recorded id for this call site so the candidate reproduces the recorded+ /// run byte-for-byte instead of minting a fresh uuid. The hook emits an+ /// `ObservedCall` either way (hit or miss) for the divergence scorer.+ ///+ /// Returns `None` when recording (so the caller generates live) or on a+ /// replay miss (the scored divergence; the caller then generates live too).+ /// The recorded result shape mirrors `record_id_generation`'s `response`:+ /// `{"generated_value": "<id>"}`.+ pub(super) fn replay_id_generation(+ method_name: &'static str,+ caller: &'static Location<'static>,+ request: &Secret<serde_json::Value>,+ ) -> Option<String> {+ let hook = hook()?;+ if !hook.is_active() {+ return None;+ }+ let recorded = hook.try_replay_with_context(deja::ReplayLookup {+ boundary: "id_generation",+ trait_name: "router_env::request_id",+ method_name,+ args: request.peek(),+ callsite_identity: None,+ caller_location: Some(caller),+ })?;+ recorded+ .get("generated_value")+ .and_then(serde_json::Value::as_str)+ .map(ToOwned::to_owned)+ }++ // `headers` and `request_body` can carry auth tokens / cardholder data / PII,+ // so they are `Secret`: the derived `Debug` redacts them, and the raw value is+ // exposed only at the deja recording boundary (`args`).+ #[derive(Debug)]+ pub(super) struct IncomingHttpRecord {+ method: String,+ path: String,+ query: String,+ request_id: String,+ headers: Secret<serde_json::Value>,+ content_type: Option<String>,+ content_length: Option<u64>,+ request_body: Secret<serde_json::Value>,+ }++ impl IncomingHttpRecord {+ fn args(&self) -> serde_json::Value {+ json!({+ "method": self.method.as_str(),+ "path": self.path.as_str(),+ "query": self.query.as_str(),+ "request_id": self.request_id.as_str(),+ "headers": self.headers.peek().clone(),+ "content_type": self.content_type.as_deref(),+ "content_length": self.content_length,+ "request_body": self.request_body.peek().clone(),+ })+ }+ }++ pub(super) async fn capture_incoming_request(+ mut request: ServiceRequest,+ request_id: &str,+ ) -> (ServiceRequest, IncomingHttpRecord) {+ let method = request.method().as_str().to_string();+ let path = request.path().to_string();+ let query = request.query_string().to_string();+ let headers = headers_json(request.headers());+ let content_type = request+ .headers()+ .get(CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .map(str::to_string);+ let content_length = request+ .headers()+ .get(CONTENT_LENGTH)+ .and_then(|value| value.to_str().ok())+ .and_then(|value| value.parse::<u64>().ok());++ let request_body = match request.extract::<Bytes>().await {+ Ok(bytes) => {+ let body = body_json(&bytes);+ request.set_payload(Payload::from(bytes));+ body+ }+ Err(error) => json!({+ "captured": false,+ "error": error.to_string(),+ }),+ };++ let record = IncomingHttpRecord {+ method,+ path,+ query,+ request_id: request_id.to_string(),+ headers: Secret::new(headers),+ content_type,+ content_length,+ request_body: Secret::new(request_body),+ };+ (request, record)+ }++ fn headers_json(headers: &HeaderMap) -> serde_json::Value {+ deja::http::headers(headers.iter().map(|(name, value)| {+ let value = value+ .to_str()+ .map(str::to_string)+ .unwrap_or_else(|_| format!("{value:?}"));+ (name.as_str().to_string(), value)+ }))+ }++ fn body_json(bytes: &Bytes) -> serde_json::Value {+ deja::http::body(bytes)+ }++ // -----------------------------------------------------------------------+ // RecordingBody — wraps an Actix body to buffer chunks and finalize the+ // boundary event only after the full body has been streamed.+ // -----------------------------------------------------------------------+ pub struct RecordingBody<B> {+ inner: Pin<Box<B>>,+ finalizer: Option<deja::LazyEventFinalizer>,+ expected_body_bytes: Option<u64>,+ captured_body_bytes: u64,+ }++ impl<B> fmt::Debug for RecordingBody<B> {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("RecordingBody")+ .field("has_finalizer", &self.finalizer.is_some())+ .finish_non_exhaustive()+ }+ }++ impl<B> RecordingBody<B> {+ fn new(body: B, finalizer: deja::LazyEventFinalizer) -> Self+ where+ B: MessageBody,+ {+ let expected_body_bytes = match body.size() {+ BodySize::Sized(0) => {+ let _ = finalizer.finalize();+ return Self {+ inner: Box::pin(body),+ finalizer: None,+ expected_body_bytes: Some(0),+ captured_body_bytes: 0,+ };+ }+ BodySize::Sized(bytes) => Some(bytes),+ BodySize::None | BodySize::Stream => None,+ };++ Self {+ inner: Box::pin(body),+ finalizer: Some(finalizer),+ expected_body_bytes,+ captured_body_bytes: 0,+ }+ }++ pub(super) fn passthrough(body: B) -> Self {+ Self {+ inner: Box::pin(body),+ finalizer: None,+ expected_body_bytes: None,+ captured_body_bytes: 0,+ }+ }++ #[cfg(test)]+ pub(super) fn for_test_with_finalizer(body: B, finalizer: deja::LazyEventFinalizer) -> Self+ where+ B: MessageBody,+ {+ Self::new(body, finalizer)+ }+ }++ // Pin<Box<B>> is always Unpin, so RecordingBody is always Unpin regardless of B.+ impl<B> Unpin for RecordingBody<B> {}++ impl<B: MessageBody> MessageBody for RecordingBody<B> {+ type Error = B::Error;++ fn size(&self) -> BodySize {+ self.inner.size()+ }++ fn poll_next(+ self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ ) -> Poll<Option<Result<Bytes, Self::Error>>> {+ // Safe because RecordingBody<B> is Unpin.+ let this = Pin::get_mut(self);++ match this.inner.as_mut().poll_next(cx) {+ Poll::Ready(None) => {+ // Emit the finalizer sentinel (a timing marker for the+ // divergence scorer). No joining: detached work runs freely+ // and is judged via lineage + canonicalization.+ if let Some(finalizer) = this.finalizer.take() {+ let _ = finalizer.finalize();+ }+ Poll::Ready(None)+ }+ Poll::Ready(Some(Ok(chunk))) => {+ if let Some(finalizer) = this.finalizer.as_mut() {+ finalizer.capture_chunk(&chunk);+ }+ this.captured_body_bytes = this+ .captured_body_bytes+ .saturating_add(u64::try_from(chunk.len()).unwrap_or(u64::MAX));+ if this+ .expected_body_bytes+ .is_some_and(|expected| this.captured_body_bytes >= expected)+ {+ if let Some(finalizer) = this.finalizer.take() {+ let _ = finalizer.finalize();+ }+ }+ Poll::Ready(Some(Ok(chunk)))+ }+ other => other,+ }+ }+ }++ // -----------------------------------------------------------------------+ // RecordedIncomingFuture — polls the inner service, then swaps the+ // response body for a RecordingBody so the event finalizes lazily.+ // -----------------------------------------------------------------------+ pub(super) fn recorded_incoming<F, B>(+ future: F,+ record: IncomingHttpRecord,+ ) -> RecordedIncomingFuture<B>+ where+ F: Future<Output = Result<ServiceResponse<B>, ActixError>> + 'static,+ B: 'static,+ {+ RecordedIncomingFuture {+ inner: Box::pin(future),+ record: Some(record),+ event: None,+ caller: Location::caller(),+ }+ }++ pub(super) struct RecordedIncomingFuture<B> {+ inner: Pin<Box<dyn Future<Output = Result<ServiceResponse<B>, ActixError>> + 'static>>,+ record: Option<IncomingHttpRecord>,+ event: Option<deja::EventBuilder>,+ caller: &'static Location<'static>,+ }++ impl<B: MessageBody + 'static> Future for RecordedIncomingFuture<B> {+ type Output = Result<ServiceResponse<RecordingBody<B>>, ActixError>;++ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {+ if self.event.is_none() {+ if let (Some(hook), Some(record)) = (hook(), self.record.as_ref()) {+ if hook.capture_verdict().should_capture() {+ let args = record.args();+ self.event = Some(+ deja::EventBuilder::start(+ hook.as_ref(),+ "http_incoming",+ "RequestIdMiddleware",+ "call",+ self.caller,+ args,+ )+ .with_semantics(deja::BoundarySemantics {+ replay_strategy: deja::ReplayStrategy::Substitute,+ kind: None,+ declaration: Some(+ deja::BoundaryDeclaration::default().reply_canon(+ deja::CanonRef::new(+ "project:!created_at,!last_synced,!modified_at",+ ),+ ),+ ),+ }),+ );+ }+ }+ }++ let result = match self.inner.as_mut().poll(cx) {+ Poll::Pending => return Poll::Pending,+ Poll::Ready(result) => result,+ };++ match result {+ Ok(response) => {+ let partial = if let Some(record) = self.record.take() {+ partial_result_json(&record, &response)+ } else {+ json!({})+ };++ let event = self.event.take();+ let finalizer = if let (Some(event), Some(hook)) = (event, hook()) {+ let hook_clone: Arc<deja::RuntimeHook> = Arc::clone(hook);+ let hook_dyn: Arc<dyn DejaHook> = hook_clone;+ Some(deja::LazyEventFinalizer::new(+ event, hook_dyn, partial, false,+ ))+ } else {+ None+ };++ let mapped = response.map_body(|_head, body| {+ if let Some(finalizer) = finalizer {+ RecordingBody::new(body, finalizer)+ } else {+ RecordingBody::passthrough(body)+ }+ });++ Poll::Ready(Ok(mapped))+ }+ Err(error) => {+ if let (Some(hook), Some(event), Some(record)) =+ (hook(), self.event.take(), self.record.take())+ {+ event.finish(hook.as_ref(), error_result_json(&record, &error), true);+ }+ Poll::Ready(Err(error))+ }+ }+ }+ }++ fn partial_result_json<B>(+ record: &IncomingHttpRecord,+ response: &ServiceResponse<B>,+ ) -> serde_json::Value {+ json!({+ "method": record.method.as_str(),+ "path": record.path.as_str(),+ "query": record.query.as_str(),+ "request_id": record.request_id.as_str(),+ "status": response.status().as_u16(),+ })+ }++ fn error_result_json(record: &IncomingHttpRecord, error: &ActixError) -> serde_json::Value {+ let status = error.as_response_error().status_code();+ json!({+ "method": record.method.as_str(),+ "path": record.path.as_str(),+ "query": record.query.as_str(),+ "request_id": record.request_id.as_str(),+ "status": status.as_u16(),+ "error": error.to_string(),+ })+ }+}+/// Custom result type for request ID operations.pub type RequestIdResult<T> = Result<T, error_stack::Report<RequestIdError>>;@@ -85,16 +535,69 @@ pub enum IdReuse {}/// Generate a new UUID v7 request ID.+#[cfg_attr(feature = "deja", track_caller)]fn generate_uuid_v7() -> String {- Uuid::now_v7().to_string()+ #[cfg(feature = "deja")]+ {+ // Only INTERNAL generations — fired inside a correlated request, so+ // `current_correlation_id()` is `Some` — are instrumented as entropy seams+ // (recorded + substituted so a mid-request sub-id reproduces byte-exact).+ //+ // The TOP-LEVEL bootstrap request-id is minted in the ingress middleware+ // BEFORE the correlation scope exists (`current_correlation_id() == None`).+ // It is not a standalone seam: it IS the `http_incoming` boundary's+ // identity, captured there and anchored on replay via the injected+ // x-request-id header (the candidate reuses it instead of regenerating).+ // Recording it separately only produced omitted-on-replay noise, so we fold+ // it into `http_incoming` by generating it live without recording.+ if deja::__private::current_correlation_id().is_some() {+ let caller = std::panic::Location::caller();+ let request =+ hyperswitch_masking::Secret::new(serde_json::json!({ "source": "uuid_v7" }));++ // REPLAY: serve the recorded id for this call site (correlated, so it+ // matches robustly). A miss falls through to live generation.+ if let Some(recorded) =+ boundary::replay_id_generation("generate_uuid_v7", caller, &request)+ {+ return recorded;+ }++ // RECORD (or replay miss): generate live and record the value.+ let generated_value = Uuid::now_v7().to_string();+ boundary::record_id_generation(+ "generate_uuid_v7",+ caller,+ request,+ hyperswitch_masking::Secret::new(+ serde_json::json!({ "generated_value": generated_value.clone() }),+ ),+ );+ return generated_value;+ }++ // Bootstrap / uncorrelated: generate live; identity folds into http_incoming.+ Uuid::now_v7().to_string()+ }++ #[cfg(not(feature = "deja"))]+ {+ Uuid::now_v7().to_string()+ }}/// Request ID middleware that takes a configurable header name/// and determines how to handle incoming request IDs.-#[derive(Clone, Debug)]+#[derive(Clone)]+// Feature-off the `recording_sampler` field is absent, so the struct derives+// Debug exactly as before; feature-on it holds a non-Debug trait object and+// uses the manual impl below.+#[cfg_attr(not(feature = "deja"), derive(Debug))]pub struct RequestIdentifier {header_name: String,use_incoming_id: IdReuse,+ #[cfg(feature = "deja")]+ recording_sampler: Option<Arc<dyn RequestRecordingSampler>>,}/// Request ID value that can be extracted in route handlers.@@ -103,12 +606,62 @@ pub struct RequestIdentifier {#[derive(Clone, PartialEq, Eq, Debug, Hash)]pub struct RequestId(Arc<str>);+/// Trusted ingress facts used to resolve Deja request recording sampling.+#[cfg(feature = "deja")]+#[derive(Clone, Debug)]+pub struct RequestRecordingFacts {+ /// Correlation/request identifier used as the OpenFeature targeting key.+ pub request_id: String,+ /// HTTP method observed at ingress.+ pub method: String,+ /// HTTP path observed at ingress.+ pub path: String,+}++/// Future returned by a Deja request recording sampler.+#[cfg(feature = "deja")]+pub type RequestRecordingSamplerFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;++/// Resolves whether a Deja record-mode request should allocate recording events.+#[cfg(feature = "deja")]+pub trait RequestRecordingSampler: Send + Sync {+ /// Return `true` to record this request, or `false` to sample it out.+ fn should_record(&self, facts: RequestRecordingFacts) -> RequestRecordingSamplerFuture<'_>;+}++#[cfg(feature = "deja")]+impl fmt::Debug for RequestIdentifier {+ fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("RequestIdentifier")+ .field("header_name", &self.header_name)+ .field("use_incoming_id", &self.use_incoming_id)+ .finish_non_exhaustive()+ }+}++#[cfg(feature = "deja")]+impl<S> fmt::Debug for RequestIdMiddleware<S> {+ fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("RequestIdMiddleware")+ .field("header_name", &self.header_name)+ .field("use_incoming_id", &self.use_incoming_id)+ .finish_non_exhaustive()+ }+}+/// The middleware implementation that processes requests.-#[derive(Debug)]+#[cfg_attr(not(feature = "deja"), derive(Debug))]pub struct RequestIdMiddleware<S> {+ #[cfg(feature = "deja")]+ service: Arc<S>,+ #[cfg(not(feature = "deja"))]service: S,header_name: HeaderName,use_incoming_id: IdReuse,+ #[cfg(feature = "deja")]+ recording_sampler: Option<Arc<dyn RequestRecordingSampler>>,}impl Display for RequestId {@@ -168,6 +721,7 @@ impl TryFrom<&str> for RequestId {impl RequestId {/// Generate a new request ID using UUID v7.+ #[cfg_attr(feature = "deja", track_caller)]pub fn new_generated() -> Self {Self(generate_uuid_v7().into())}@@ -176,6 +730,7 @@ impl RequestId {////// This is the core logic: try to extract from the specified header,/// if not possible or not desired, generate a new UUID v7.+ #[cfg_attr(feature = "deja", track_caller)]pub fn extract_or_generate(request: &ServiceRequest,header_name: &HeaderName,@@ -237,6 +792,8 @@ impl RequestIdentifier {Self {header_name: header_name.to_string(),use_incoming_id: IdReuse::default(),+ #[cfg(feature = "deja")]+ recording_sampler: None,}}@@ -258,6 +815,23 @@ impl RequestIdentifier {}}+ /// Configure a Deja request recording sampler.+ ///+ /// The sampler is invoked only while the process-level Deja hook is in record+ /// mode, before the request enters the correlation scope and before any+ /// request body capture can occur.+ #[cfg(feature = "deja")]+ #[must_use]+ pub fn with_recording_sampler(+ self,+ recording_sampler: Arc<dyn RequestRecordingSampler>,+ ) -> Self {+ Self {+ recording_sampler: Some(recording_sampler),+ ..self+ }+ }+/// Get the header name used for request ID extraction.////// # Examples@@ -306,6 +880,7 @@ impl IdReuse {/// let (_id, generated) = IdReuse::IgnoreIncoming.get_or_create_request_id(None);/// assert!(generated);/// ```+ #[cfg_attr(feature = "deja", track_caller)]pub fn get_or_create_request_id(&self, existing: Option<&RequestId>) -> (RequestId, bool) {match self {Self::UseIncoming => existing@@ -317,6 +892,44 @@ impl IdReuse {}}+// ---------------------------------------------------------------------------+// Transform / Service — note that when deja is compiled in the response body+// type can capture bytes and emit the finalizer sentinel at stream EOF.+// ---------------------------------------------------------------------------++#[cfg(feature = "deja")]+impl<S, B> Transform<S, ServiceRequest> for RequestIdentifier+where+ S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,+ S::Future: 'static,+ B: actix_web::body::MessageBody + 'static,+{+ type Response =+ ServiceResponse<EitherBody<boundary::RecordingBody<B>, boundary::RecordingBody<B>>>;+ type Error = S::Error;+ type Transform = RequestIdMiddleware<S>;+ type InitError = ();+ type Future = Ready<Result<Self::Transform, Self::InitError>>;++ fn new_transform(&self, service: S) -> Self::Future {+ let header_name = HeaderName::from_str(&self.header_name).unwrap_or_else(|_| {+ tracing::error!(+ "Invalid header name '{}', using fallback 'x-request-id'",+ self.header_name+ );+ HeaderName::from_static("x-request-id")+ });++ ready(Ok(RequestIdMiddleware {+ service: Arc::new(service),+ header_name,+ use_incoming_id: self.use_incoming_id,+ recording_sampler: self.recording_sampler.clone(),+ }))+ }+}++#[cfg(not(feature = "deja"))]impl<S, B> Transform<S, ServiceRequest> for RequestIdentifierwhereS: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,@@ -346,7 +959,131 @@ where}}+/// RAII guard for the per-request recording decision. Clearing the+/// `RECORD_DECISIONS` entry on drop (rather than with a straight-line call after+/// the handler) means a cancelled or panicking record-mode request — whose+/// future is dropped mid-flight, skipping the trailing clear — cannot leak a+/// registry entry forever.+#[cfg(feature = "deja")]+struct RecordingDecisionGuard(String);++#[cfg(feature = "deja")]+impl Drop for RecordingDecisionGuard {+ fn drop(&mut self) {+ deja::clear_recording_decision(&self.0);+ }+}+#[allow(clippy::type_complexity)]+#[cfg(feature = "deja")]+impl<S, B> Service<ServiceRequest> for RequestIdMiddleware<S>+where+ S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,+ S::Future: 'static,+ B: actix_web::body::MessageBody + 'static,+{+ type Response =+ ServiceResponse<EitherBody<boundary::RecordingBody<B>, boundary::RecordingBody<B>>>;+ type Error = S::Error;+ type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;++ fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {+ self.service.poll_ready(ctx)+ }++ fn call(&self, request: ServiceRequest) -> Self::Future {+ let service = Arc::clone(&self.service);+ let header_name = self.header_name.clone();++ let incoming_request_id = request.headers().get(&header_name).cloned();+ let request_id =+ RequestId::extract_or_generate(&request, &header_name, self.use_incoming_id);+ let header_value = request_id.to_header_value().unwrap_or_else(|e| {+ tracing::error!(+ error = %e,+ request_id = %request_id,+ "Failed to convert request ID to header value"+ );+ HeaderValue::from_static("invalid-request-id")+ });+ request.extensions_mut().insert(request_id.clone());++ let request_facts = RequestRecordingFacts {+ request_id: request_id.to_string(),+ method: request.method().as_str().to_owned(),+ path: request.path().to_owned(),+ };+ let recording_sampler = self.recording_sampler.clone();++ Box::pin(async move {+ if let Some(upstream_request_id) = incoming_request_id {+ tracing::debug!(+ ?upstream_request_id,+ generated_request_id = %request_id,+ "Received upstream request ID for correlation"+ );+ }++ let mut response: ServiceResponse<+ EitherBody<boundary::RecordingBody<B>, boundary::RecordingBody<B>>,+ > = if boundary::process_is_active() {+ // The guard clears the pushed decision on drop, covering the normal+ // return, the `?` early-return, AND a panic / cancellation of the+ // request future (any of which would otherwise skip a trailing clear+ // and leak the RECORD_DECISIONS entry).+ let mut _decision_guard: Option<RecordingDecisionGuard> = None;+ let should_record_http_incoming = if boundary::process_is_record_mode() {+ let decision = match recording_sampler {+ Some(sampler) => sampler.should_record(request_facts.clone()).await,+ None => true,+ };+ deja::set_recording_decision(request_id.to_string(), decision);+ _decision_guard = Some(RecordingDecisionGuard(request_id.to_string()));+ decision+ } else {+ false+ };++ if should_record_http_incoming {+ let (request, incoming_record) =+ boundary::capture_incoming_request(request, request_id.as_str()).await;+ let fut = service.call(request);+ let request_span = tracing::info_span!(+ "deja::http_incoming",+ method = %request_facts.method,+ path = %request_facts.path,+ request_id = %request_id,+ );+ // Correlation comes from the ingress root span (CustomRootSpanBuilder+ // stamps `request_id`) via DejaCorrelationLayer — no explicit scope needed.+ let recorded_result = boundary::recorded_incoming(fut, incoming_record)+ .instrument(request_span)+ .await;+ let recorded = recorded_result?;+ recorded.map_body(|_head, body| EitherBody::left(body))+ } else {+ // Correlation rides the ingress root span via DejaCorrelationLayer.+ let response_result = service.call(request).await;+ let response = response_result?;+ response.map_body(|_head, body| {+ EitherBody::right(boundary::RecordingBody::passthrough(body))+ })+ }+ } else {+ let resp = service.call(request).await?;+ resp.map_body(|_head, body| {+ EitherBody::right(boundary::RecordingBody::passthrough(body))+ })+ };++ response.headers_mut().insert(header_name, header_value);+ Ok(response)+ })+ }+}++#[allow(clippy::type_complexity)]+#[cfg(not(feature = "deja"))]impl<S, B> Service<ServiceRequest> for RequestIdMiddleware<S>whereS: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,@@ -419,3 +1156,295 @@ impl FromRequest for RequestId {)}}++#[cfg(test)]+mod tests {+ use super::*;++ /// Regression sentinel for the ingress circular-dependency bug.+ ///+ /// The opt-in recording flip made `RecordingHook::mode()` return `Record`+ /// only while a per-correlation decision is pushed. The ingress middleware+ /// is what pushes that decision, so gating ingress on `mode()` was circular:+ /// `mode()` is `Disabled` at ingress (no decision yet) → the predicate is+ /// false → the sampler never runs → no decision is ever pushed → nothing is+ /// ever recorded (the empty-tape bug).+ ///+ /// The fix routes the ingress predicates through `process_mode()`, which+ /// reflects the boot-time configuration and ignores the per-request gate.+ /// This test pins the exact pivot at the type level, with no global install+ /// and no async: a fresh recorder with no decision in scope must report+ /// `process_mode() == Record` (ingress may proceed) while `mode() ==+ /// Disabled` (the boundary gate still governs actual capture). On the old+ /// code the first assertion is what the middleware needed and never got.+ #[cfg(feature = "deja")]+ #[test]+ fn ingress_process_mode_is_record_before_any_decision_is_pushed() {+ struct NullSink;+ impl deja::RecordSink<deja::DejaRecord> for NullSink {+ fn write_batch(&mut self, _records: &[deja::DejaRecord]) -> std::io::Result<()> {+ Ok(())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }++ let hook = deja::RecordingHook::with_sink(+ NullSink,+ "ingress-sentinel".to_string(),+ deja::WriterConfig::default(),+ );++ // No per-correlation decision has been pushed for this thread.+ assert_eq!(+ deja::DejaHook::process_mode(&hook),+ deja::RuntimeMode::Record,+ "ingress predicate must see Record from process config alone, or the \+ middleware can never push the decision that flips the boundary gate"+ );+ assert_eq!(+ deja::DejaHook::capture_verdict(&hook),+ deja::CaptureVerdict::SkipNoDecision,+ "the per-boundary capture gate must stay closed until a decision is \+ pushed — the split is what breaks the ingress circular dependency"+ );+ }++ #[test]+ fn request_identifier_builder_keeps_explicit_header_and_id_reuse_without_sampler() {+ let identifier =+ RequestIdentifier::new("x-correlation-id").use_incoming_id(IdReuse::IgnoreIncoming);++ assert_eq!(identifier.header_name(), "x-correlation-id");+ assert_eq!(identifier.id_reuse_strategy(), IdReuse::IgnoreIncoming);+ }++ #[cfg(feature = "deja")]+ struct RejectAllSampler;++ #[cfg(feature = "deja")]+ impl RequestRecordingSampler for RejectAllSampler {+ fn should_record(+ &self,+ _facts: RequestRecordingFacts,+ ) -> RequestRecordingSamplerFuture<'_> {+ Box::pin(ready(false))+ }+ }++ #[cfg(feature = "deja")]+ struct EmptyLookup;++ #[cfg(feature = "deja")]+ impl deja::LookupTableSource for EmptyLookup {+ fn load(&mut self) -> std::io::Result<deja::LookupTable> {+ Ok(deja::LookupTable {+ recording_id: "empty".to_string(),+ policy_version: 1,+ entries: Vec::new(),+ })+ }+ }++ #[cfg(feature = "deja")]+ struct ObservedRecordingHook {+ recorded: std::sync::Mutex<Vec<deja::BoundaryEvent>>,+ }++ #[cfg(feature = "deja")]+ impl ObservedRecordingHook {+ fn new() -> Self {+ Self {+ recorded: std::sync::Mutex::new(Vec::new()),+ }+ }++ fn recorded_len(&self) -> usize {+ self.recorded.lock().expect("recording hook lock").len()+ }++ fn recorded_events(&self) -> Vec<deja::BoundaryEvent> {+ self.recorded.lock().expect("recording hook lock").clone()+ }+ }++ #[cfg(feature = "deja")]+ impl deja::DejaHook for ObservedRecordingHook {+ fn process_mode(&self) -> deja::RuntimeMode {+ deja::RuntimeMode::Record+ }++ fn record(&self, event: deja::BoundaryEvent) {+ self.recorded+ .lock()+ .expect("recording hook lock")+ .push(event);+ }++ fn next_global_sequence(&self) -> u64 {+ 150+ }++ fn next_request_sequence(&self, _correlation_id: Option<&str>) -> u64 {+ 1+ }+ }++ #[cfg(feature = "deja")]+ struct ExactSizedNeverEofBody {+ chunk: Option<bytes::Bytes>,+ size: u64,+ }++ #[cfg(feature = "deja")]+ impl ExactSizedNeverEofBody {+ fn new(chunk: &'static [u8]) -> Self {+ Self {+ chunk: Some(bytes::Bytes::from_static(chunk)),+ size: u64::try_from(chunk.len()).unwrap_or(u64::MAX),+ }+ }+ }++ #[cfg(feature = "deja")]+ impl actix_web::body::MessageBody for ExactSizedNeverEofBody {+ type Error = actix_web::Error;++ fn size(&self) -> actix_web::body::BodySize {+ actix_web::body::BodySize::Sized(self.size)+ }++ fn poll_next(+ mut self: Pin<&mut Self>,+ _cx: &mut Context<'_>,+ ) -> Poll<Option<Result<bytes::Bytes, Self::Error>>> {+ match self.chunk.take() {+ Some(chunk) => Poll::Ready(Some(Ok(chunk))),+ None => Poll::Pending,+ }+ }+ }++ #[cfg(feature = "deja")]+ #[test]+ fn recording_body_finalizes_exact_sized_body_after_matching_chunk_without_eof() {+ let hook = Arc::new(ObservedRecordingHook::new());+ let hook_dyn: Arc<dyn deja::DejaHook> = hook.clone();+ let event = deja::EventBuilder::start_with_correlation_id(+ hook_dyn.as_ref(),+ "http_incoming",+ "RequestIdMiddleware",+ "call",+ std::panic::Location::caller(),+ Some("97cd".to_string()),+ serde_json::json!({ "path": "/payments/confirm" }),+ );+ let finalizer = deja::LazyEventFinalizer::new(+ event,+ hook_dyn,+ serde_json::json!({ "status": 200 }),+ false,+ );+ let mut body = boundary::RecordingBody::for_test_with_finalizer(+ ExactSizedNeverEofBody::new(b"{\"ok\":true}"),+ finalizer,+ );+ let waker = std::task::Waker::noop();+ let mut context = Context::from_waker(waker);++ let first_poll = actix_web::body::MessageBody::poll_next(Pin::new(&mut body), &mut context);++ let Poll::Ready(Some(Ok(chunk))) = first_poll else {+ panic!("first poll must yield the exact-sized body chunk before the body parks");+ };+ assert_eq!(&chunk[..], br#"{"ok":true}"#);+ assert_eq!(+ hook.recorded_len(),+ 1,+ "exact-sized bodies must finalize as soon as the declared bytes are captured, without waiting for EOF or drop"+ );++ let events = hook.recorded_events();+ let event = events.first().expect("finalized http_incoming event");+ assert_eq!(event.global_sequence, 150);+ assert_eq!(event.correlation_id.as_deref(), Some("97cd"));+ assert_eq!(event.boundary, "http_incoming");+ assert_eq!(+ event+ .result+ .get("response_body")+ .and_then(|body| body.get("text"))+ .and_then(serde_json::Value::as_str),+ Some(r#"{"ok":true}"#)+ );+ }++ #[cfg(feature = "deja")]+ #[tokio::test]+ async fn spawn_fork_runs_without_waiting_for_body_eof() {+ // Stamp-only model: fork work is spawned immediately with span-derived+ // lineage stamps — nothing queues, nothing drains at body EOF, and the+ // recorder never reshapes scheduling.+ let hook =+ deja::LookupTableHook::from_source(EmptyLookup, deja::InMemoryObservedSink::new())+ .expect("lookup replay hook");+ match deja::set_global_runtime_hook(Some(deja::RuntimeHook::LookupReplay(hook))) {+ Ok(()) => {}+ Err(_) if deja::runtime_mode().is_replay() => {}+ Err(err) => panic!("install replay hook: {err}"),+ }++ let (tx, rx) = std::sync::mpsc::channel();+ async move {+ deja::spawn_fork(async move {+ tx.send(()).expect("test receiver alive");+ });+ }+ .await;+ tokio::task::yield_now().await;+ assert!(+ rx.try_recv().is_ok(),+ "stamp-only spawn_fork must run immediately, not wait for a drain"+ );++ let body = boundary::RecordingBody::passthrough(actix_web::body::BoxBody::new("ok"));+ let bytes = actix_web::body::to_bytes(body).await.expect("body bytes");+ assert_eq!(&bytes[..], b"ok");+ }++ #[cfg(feature = "deja")]+ #[test]+ fn request_recording_facts_exposes_only_id_method_and_path_to_sampler() {+ let facts = RequestRecordingFacts {+ request_id: "req-123".to_string(),+ method: "POST".to_string(),+ path: "/payments/confirm".to_string(),+ };++ let RequestRecordingFacts {+ request_id,+ method,+ path,+ } = facts;++ assert_eq!(request_id, "req-123");+ assert_eq!(method, "POST");+ assert_eq!(path, "/payments/confirm");+ }++ #[cfg(feature = "deja")]+ #[test]+ fn recording_sampler_trait_object_can_be_attached_without_losing_configuration() {+ let sampler: Arc<dyn RequestRecordingSampler> = Arc::new(RejectAllSampler);++ let identifier = RequestIdentifier::new("x-correlation-id")+ .use_incoming_id(IdReuse::IgnoreIncoming)+ .with_recording_sampler(sampler);++ assert!(identifier.recording_sampler.is_some());++ assert_eq!(identifier.header_name(), "x-correlation-id");+ assert_eq!(identifier.id_reuse_strategy(), IdReuse::IgnoreIncoming);+ }+}diff --git a/crates/router_env/tests/deja_ingress_records.rs b/crates/router_env/tests/deja_ingress_records.rsnew file mode 100644index 0000000000..845187d0db--- /dev/null+++ b/crates/router_env/tests/deja_ingress_records.rs@@ -0,0 +1,135 @@+#![cfg(feature = "deja")]+//! End-to-end regression test for the ingress recording circular dependency.+//!+//! The per-boundary capture gate answers from the per-correlation sampling+//! decision, and the ingress middleware is what pushes that decision. So the+//! ingress predicate must never consult the per-request gate: at ingress no+//! decision exists yet, the predicate would read false, the sampler would never+//! be consulted, the decision would never be pushed, and every boundary would+//! skip — an empty tape, with nothing to indicate why.+//!+//! The ingress predicates therefore read `process_mode()`, which is boot-time+//! configuration and consults no per-request state. This test drives the real+//! actix middleware end to end and asserts the two effects that disappear if+//! that split is ever lost: the sampler is consulted (so a decision is pushed)+//! and exactly one `http_incoming` boundary event is recorded.+//!+//! It runs in its own integration-test binary so the process-global runtime hook+//! and tracing subscriber install exactly once, with no cross-test contention.++use std::sync::{+ atomic::{AtomicBool, Ordering},+ Arc, Mutex,+};++use actix_web::{test, web, App, HttpResponse};+use router_env::request_id::{+ RequestIdentifier, RequestRecordingFacts, RequestRecordingSampler,+ RequestRecordingSamplerFuture,+};+use tracing_subscriber::prelude::*;++/// Synchronous in-memory sink so the test can read back what the recorder wrote.+#[derive(Clone)]+struct VecSink(Arc<Mutex<Vec<deja::DejaRecord>>>);++impl deja::RecordSink<deja::DejaRecord> for VecSink {+ fn write_batch(&mut self, records: &[deja::DejaRecord]) -> std::io::Result<()> {+ let mut sink = self+ .0+ .lock()+ .map_err(|_| std::io::Error::other("sink lock poisoned"))?;+ sink.extend(records.iter().cloned());+ Ok(())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}++/// A sampler that records whether it was consulted and always votes to record.+/// On the pre-fix code the ingress predicate never passes, so `should_record`+/// is never called — which is exactly what the `sampler_seen` flag catches.+struct InvocationRecordingSampler(Arc<AtomicBool>);++impl RequestRecordingSampler for InvocationRecordingSampler {+ fn should_record(&self, _facts: RequestRecordingFacts) -> RequestRecordingSamplerFuture<'_> {+ self.0.store(true, Ordering::SeqCst);+ Box::pin(async { true })+ }+}++#[actix_web::test]+async fn ingress_records_http_incoming_end_to_end() {+ // The middleware stamps `request_id` on its span; this layer mirrors it into+ // deja-context so the http_incoming boundary gate can resolve the pushed+ // decision (correlation → decision lookup). Own process, so install once.+ tracing_subscriber::registry()+ .with(deja::DejaCorrelationLayer::new())+ .try_init()+ .expect("install correlation layer (own process)");++ // A real RecordingHook (the one with the sampling gate the bug lives in),+ // wired to a readable sink and installed as the process runtime hook.+ let records = Arc::new(Mutex::new(Vec::new()));+ let hook = Arc::new(deja::RecordingHook::with_sink(+ VecSink(records.clone()),+ "ingress-it".to_string(),+ deja::WriterConfig::default(),+ ));+ deja::set_global_runtime_hook(Some(deja::RuntimeHook::Recording(hook)))+ .expect("install record hook (own process)");++ let sampler_seen = Arc::new(AtomicBool::new(false));+ let sampler: Arc<dyn RequestRecordingSampler> =+ Arc::new(InvocationRecordingSampler(sampler_seen.clone()));++ let app = test::init_service(+ App::new()+ .wrap(RequestIdentifier::new("x-request-id").with_recording_sampler(sampler))+ .route(+ "/payments",+ web::post().to(|| async { HttpResponse::Ok().body(r#"{"ok":true}"#) }),+ ),+ )+ .await;++ let request = test::TestRequest::post().uri("/payments").to_request();+ let response = test::call_service(&app, request).await;+ assert!(response.status().is_success(), "handler should return 200");++ // Drive the body to EOF so the RecordingBody finalizes the http_incoming event.+ let _body = test::read_body(response).await;++ // Synchronous drain barrier: flush blocks until the async writer has handed+ // every queued record to the sink.+ deja::flush_global_runtime_hook().expect("flush recording hook");++ // (a) The sampler was consulted → the ingress predicate passed → a decision+ // was pushed. False on the pre-fix code (the circular dependency).+ assert!(+ sampler_seen.load(Ordering::SeqCst),+ "recording sampler was never consulted: the ingress predicate did not pass, \+ so no recording decision was ever pushed"+ );++ // (b) Exactly one http_incoming boundary event reached the sink.+ let recorded = records.lock().expect("sink lock");+ let http_incoming: Vec<_> = recorded+ .iter()+ .filter_map(|record| match record {+ deja::DejaRecord::BoundaryEvent(event) if event.boundary == "http_incoming" => {+ Some(event)+ }+ _ => None,+ })+ .collect();+ assert_eq!(+ http_incoming.len(),+ 1,+ "expected exactly one recorded http_incoming event; got {} (total records: {})",+ http_incoming.len(),+ recorded.len(),+ );+}diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.tomlindex a9711a6675..0c3daa7729 100644--- a/crates/storage_impl/Cargo.toml+++ b/crates/storage_impl/Cargo.toml@@ -29,7 +29,7 @@ api_models = { version = "0.1.0", path = "../api_models" }common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils" }common_types = { version = "0.1.0", path = "../common_types" }-deja = { git = "https://github.com/juspay/deja", rev = "075a614324897b8b6a878af36d7ac243fbec5d33", optional = true, default-features = false }+deja = { git = "https://github.com/juspay/deja", rev = "2c3a795ef4d8d2a5eebc47bbe7134984b75be6b3", optional = true, default-features = false }diesel_models = { version = "0.1.0", path = "../diesel_models", default-features = false }hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }hyperswitch_masking = "0.0.1"diff --git a/crates/storage_impl/src/authentication.rs b/crates/storage_impl/src/authentication.rsindex 4cffe956cc..cd6c3b0167 100644--- a/crates/storage_impl/src/authentication.rs+++ b/crates/storage_impl/src/authentication.rs@@ -67,16 +67,18 @@ impl<T: DatabaseStore> AuthenticationInterface for RouterStore<T> {_storage_scheme: common_enums::MerchantStorageScheme,) -> error_stack::Result<Authentication, errors::StorageError> {let conn = pg_connection_write(self).await?;- let inserted_authentication = authentication- .construct_new()- .await- .change_context(errors::StorageError::EncryptionError)?- .insert(&conn)- .await- .map_err(|error| {- let new_err = diesel_error_to_data_error(*error.current_context());- error.change_context(new_err)- })?;+ let inserted_authentication = Box::pin(+ authentication+ .construct_new()+ .await+ .change_context(errors::StorageError::EncryptionError)?+ .insert(&conn),+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })?;Authentication::convert_back(state,inserted_authentication,@@ -208,11 +210,13 @@ impl<T: DatabaseStore> AuthenticationInterface for RouterStore<T> {.processor_merchant_id.clone().unwrap_or_else(|| previous_state.merchant_id.clone());- let result = diesel_authentication::update_by_processor_merchant_id_authentication_id(- &conn,- &processor_merchant_id,- &previous_state.authentication_id,- authentication_update_internal.clone(),+ let result = Box::pin(+ diesel_authentication::update_by_processor_merchant_id_authentication_id(+ &conn,+ &processor_merchant_id,+ &previous_state.authentication_id,+ authentication_update_internal.clone(),+ ),).await;let result = match result {@@ -222,11 +226,13 @@ impl<T: DatabaseStore> AuthenticationInterface for RouterStore<T> {diesel_models::errors::DatabaseError::NotFound) =>{- diesel_authentication::update_by_merchant_id_authentication_id(- &conn,- &processor_merchant_id,- &previous_state.authentication_id,- authentication_update_internal,+ Box::pin(+ diesel_authentication::update_by_merchant_id_authentication_id(+ &conn,+ &processor_merchant_id,+ &previous_state.authentication_id,+ authentication_update_internal,+ ),).await}diff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rsindex 50da9caa6f..a3ae9bdad3 100644--- a/crates/storage_impl/src/business_profile.rs+++ b/crates/storage_impl/src/business_profile.rs@@ -117,21 +117,23 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {business_profile: domain::Profile,) -> CustomResult<domain::Profile, StorageError> {let conn = pg_accounts_connection_write(self).await?;- business_profile- .construct_new()- .await- .change_context(StorageError::EncryptionError)?- .insert(&conn)- .await- .map_err(|error| report!(StorageError::from(error)))?- .convert(- self.get_keymanager_state()- .attach_printable("Missing KeyManagerState")?,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)+ Box::pin(+ business_profile+ .construct_new()+ .await+ .change_context(StorageError::EncryptionError)?+ .insert(&conn),+ )+ .await+ .map_err(|error| report!(StorageError::from(error)))?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)}#[instrument(skip_all)]@@ -185,20 +187,22 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {profile_update: domain::ProfileUpdate,) -> CustomResult<domain::Profile, StorageError> {let conn = pg_accounts_connection_write(self).await?;- Conversion::convert(current_state)- .await- .change_context(StorageError::EncryptionError)?- .update_by_profile_id(&conn, ProfileUpdateInternal::foreign_from(profile_update))- .await- .map_err(|error| report!(StorageError::from(error)))?- .convert(- self.get_keymanager_state()- .attach_printable("Missing KeyManagerState")?,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)+ Box::pin(+ Conversion::convert(current_state)+ .await+ .change_context(StorageError::EncryptionError)?+ .update_by_profile_id(&conn, ProfileUpdateInternal::foreign_from(profile_update)),+ )+ .await+ .map_err(|error| report!(StorageError::from(error)))?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)}#[instrument(skip_all)]diff --git a/crates/storage_impl/src/connection.rs b/crates/storage_impl/src/connection.rsindex 4d19f3820e..9281e210d8 100644--- a/crates/storage_impl/src/connection.rs+++ b/crates/storage_impl/src/connection.rs@@ -41,9 +41,14 @@ pub async fn pg_connection_read<T: crate::DatabaseStore>())]let pool = store.get_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(crate::errors::StorageError::DatabaseConnectionError)+ .change_context(crate::errors::StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ crate::utils::deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn pg_connection_write<T: crate::DatabaseStore>(@@ -55,7 +60,12 @@ pub async fn pg_connection_write<T: crate::DatabaseStore>(// Since all writes should happen to master DB only choose master DB.let pool = store.get_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(crate::errors::StorageError::DatabaseConnectionError)+ .change_context(crate::errors::StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ crate::utils::deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rsindex 90695e842d..690a0a9b1b 100644--- a/crates/storage_impl/src/customers.rs+++ b/crates/storage_impl/src/customers.rs@@ -62,24 +62,23 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStstorage_scheme: MerchantStorageScheme,) -> CustomResult<Option<domain::Customer>, StorageError> {let conn = pg_connection_read(self).await?;- let maybe_result = self- .find_optional_resource_by_id(- key_store,- storage_scheme,- customers::Customer::find_optional_by_customer_id_merchant_id(- &conn,- customer_id,+ let maybe_result = Box::pin(self.find_optional_resource_by_id(+ key_store,+ storage_scheme,+ customers::Customer::find_optional_by_customer_id_merchant_id(+ &conn,+ customer_id,+ merchant_id,+ ),+ kv_router_store::FindResourceBy::Id(+ format!("cust_{}", customer_id.get_string_repr()),+ PartitionKey::MerchantIdCustomerId {merchant_id,- ),- kv_router_store::FindResourceBy::Id(- format!("cust_{}", customer_id.get_string_repr()),- PartitionKey::MerchantIdCustomerId {- merchant_id,- customer_id,- },- ),- )- .await?;+ customer_id,+ },+ ),+ ))+ .await?;maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name {Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,@@ -98,7 +97,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStstorage_scheme: MerchantStorageScheme,) -> CustomResult<Option<domain::Customer>, StorageError> {let conn = pg_connection_read(self).await?;- self.find_optional_resource_by_id(+ Box::pin(self.find_optional_resource_by_id(key_store,storage_scheme,customers::Customer::find_optional_by_customer_id_merchant_id(@@ -113,7 +112,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStcustomer_id,},),- )+ )).await}@@ -126,24 +125,23 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStstorage_scheme: MerchantStorageScheme,) -> CustomResult<Option<domain::Customer>, StorageError> {let conn = pg_connection_read(self).await?;- let maybe_result = self- .find_optional_resource_by_id(- key_store,- storage_scheme,- customers::Customer::find_optional_by_merchant_id_merchant_reference_id(- &conn,- merchant_reference_id,+ let maybe_result = Box::pin(self.find_optional_resource_by_id(+ key_store,+ storage_scheme,+ customers::Customer::find_optional_by_merchant_id_merchant_reference_id(+ &conn,+ merchant_reference_id,+ merchant_id,+ ),+ kv_router_store::FindResourceBy::Id(+ format!("cust_{}", merchant_reference_id.get_string_repr()),+ PartitionKey::MerchantIdMerchantReferenceId {merchant_id,- ),- kv_router_store::FindResourceBy::Id(- format!("cust_{}", merchant_reference_id.get_string_repr()),- PartitionKey::MerchantIdMerchantReferenceId {- merchant_id,- merchant_reference_id: merchant_reference_id.get_string_repr(),- },- ),- )- .await?;+ merchant_reference_id: merchant_reference_id.get_string_repr(),+ },+ ),+ ))+ .await?;maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name {Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,@@ -213,7 +211,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.change_context(StorageError::KVError).attach_printable("Failed to generate customer update query")?;- self.update_resource(+ Box::pin(self.update_resource(key_store,storage_scheme,customers::Customer::update_by_customer_id_merchant_id(@@ -227,7 +225,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStdrainer_query,operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),},- )+ )).await}@@ -241,24 +239,23 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStstorage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;- let result: domain::Customer = self- .find_resource_by_id(- key_store,- storage_scheme,- customers::Customer::find_by_merchant_reference_id_merchant_id(- &conn,- merchant_reference_id,+ let result: domain::Customer = Box::pin(self.find_resource_by_id(+ key_store,+ storage_scheme,+ customers::Customer::find_by_merchant_reference_id_merchant_id(+ &conn,+ merchant_reference_id,+ merchant_id,+ ),+ kv_router_store::FindResourceBy::Id(+ format!("cust_{}", merchant_reference_id.get_string_repr()),+ PartitionKey::MerchantIdMerchantReferenceId {merchant_id,- ),- kv_router_store::FindResourceBy::Id(- format!("cust_{}", merchant_reference_id.get_string_repr()),- PartitionKey::MerchantIdMerchantReferenceId {- merchant_id,- merchant_reference_id: merchant_reference_id.get_string_repr(),- },- ),- )- .await?;+ merchant_reference_id: merchant_reference_id.get_string_repr(),+ },+ ),+ ))+ .await?;match result.name {Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,@@ -276,24 +273,19 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStstorage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;- let result: domain::Customer = self- .find_resource_by_id(- key_store,- storage_scheme,- customers::Customer::find_by_customer_id_merchant_id(- &conn,- customer_id,+ let result: domain::Customer = Box::pin(self.find_resource_by_id(+ key_store,+ storage_scheme,+ customers::Customer::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id),+ kv_router_store::FindResourceBy::Id(+ format!("cust_{}", customer_id.get_string_repr()),+ PartitionKey::MerchantIdCustomerId {merchant_id,- ),- kv_router_store::FindResourceBy::Id(- format!("cust_{}", customer_id.get_string_repr()),- PartitionKey::MerchantIdCustomerId {- merchant_id,- customer_id,- },- ),- )- .await?;+ customer_id,+ },+ ),+ ))+ .await?;match result.name {Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,@@ -368,7 +360,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.change_context(StorageError::KVError).attach_printable("Failed to generate customer insert query")?;- self.insert_resource(+ Box::pin(self.insert_resource(key_store,decided_storage_scheme,new_customer.clone().insert(&conn),@@ -380,7 +372,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStkey,resource_type: "customer",},- )+ )).await}@@ -420,7 +412,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.change_context(StorageError::KVError).attach_printable("Failed to generate customer insert query")?;- self.insert_resource(+ Box::pin(self.insert_resource(key_store,storage_scheme,new_customer.clone().insert(&conn),@@ -432,7 +424,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStkey,resource_type: "customer",},- )+ )).await}@@ -457,19 +449,18 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStstorage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;- let result: domain::Customer = self- .find_resource_by_id(- key_store,- storage_scheme,- customers::Customer::find_by_global_id(&conn, id),- kv_router_store::FindResourceBy::Id(- format!("cust_{}", id.get_string_repr()),- PartitionKey::GlobalId {- id: id.get_string_repr(),- },- ),- )- .await?;+ let result: domain::Customer = Box::pin(self.find_resource_by_id(+ key_store,+ storage_scheme,+ customers::Customer::find_by_global_id(&conn, id),+ kv_router_store::FindResourceBy::Id(+ format!("cust_{}", id.get_string_repr()),+ PartitionKey::GlobalId {+ id: id.get_string_repr(),+ },+ ),+ ))+ .await?;if result.status == common_enums::DeleteStatus::Redacted {Err(StorageError::CustomerRedacted)?@@ -488,19 +479,18 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStstorage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;- let result: domain::Customer = self- .find_resource_by_id(- key_store,- storage_scheme,- customers::Customer::find_by_global_id_merchant_id(&conn, id, merchant_id),- kv_router_store::FindResourceBy::Id(- format!("cust_{}", id.get_string_repr()),- PartitionKey::GlobalId {- id: id.get_string_repr(),- },- ),- )- .await?;+ let result: domain::Customer = Box::pin(self.find_resource_by_id(+ key_store,+ storage_scheme,+ customers::Customer::find_by_global_id_merchant_id(&conn, id, merchant_id),+ kv_router_store::FindResourceBy::Id(+ format!("cust_{}", id.get_string_repr()),+ PartitionKey::GlobalId {+ id: id.get_string_repr(),+ },+ ),+ ))+ .await?;if result.merchant_id != *merchant_id {Err(StorageError::ValueNotFound(@@ -544,7 +534,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.change_context(StorageError::KVError).attach_printable("Failed to generate customer update query")?;- self.update_resource(+ Box::pin(self.update_resource(key_store,storage_scheme,database_call,@@ -553,7 +543,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStdrainer_query,operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),},- )+ )).await}}diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rsindex e84de69a5c..cf4848a5a9 100644--- a/crates/storage_impl/src/database/store.rs+++ b/crates/storage_impl/src/database/store.rs@@ -28,6 +28,13 @@ pub trait DatabaseStore: Clone + Send + Sync {fn get_replica_pool(&self) -> &PgPool;fn get_accounts_master_pool(&self) -> &PgPool;fn get_accounts_replica_pool(&self) -> &PgPool;++ /// Request correlation used by deja replay to route database connections to+ /// the active replay schema. Stores without request identity return `None`.+ #[cfg(feature = "deja")]+ fn get_request_id(&self) -> Option<String> {+ None+ }}#[derive(Debug, Clone)]diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rsindex 43c3e1b240..9db8df9a12 100644--- a/crates/storage_impl/src/kv_router_store.rs+++ b/crates/storage_impl/src/kv_router_store.rs@@ -151,6 +151,14 @@ wherefn get_accounts_replica_pool(&self) -> &PgPool {self.router_store.get_accounts_replica_pool()}++ /// Request correlation consumed by the deja replay DB routing hook.+ #[cfg(feature = "deja")]+ fn get_request_id(&self) -> Option<String> {+ self.request_id+ .clone()+ .or_else(|| self.router_store.get_request_id())+ }}impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> {diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rsindex e7213dad8b..5dd2711a21 100644--- a/crates/storage_impl/src/lib.rs+++ b/crates/storage_impl/src/lib.rs@@ -139,6 +139,12 @@ wherefn get_accounts_replica_pool(&self) -> &PgPool {self.db_store.get_accounts_replica_pool()}++ /// Request correlation consumed by the deja replay DB routing hook.+ #[cfg(feature = "deja")]+ fn get_request_id(&self) -> Option<String> {+ self.request_id.clone()+ }}impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> {diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rsindex e7c697b5bf..9fd6f3f8e3 100644--- a/crates/storage_impl/src/payment_method.rs+++ b/crates/storage_impl/src/payment_method.rs@@ -49,12 +49,12 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resource_by_id(+ Box::pin(self.find_resource_by_id(key_store,storage_scheme,PaymentMethod::find_by_payment_method_id(&conn, payment_method_id),FindResourceBy::LookupId(format!("payment_method_{payment_method_id}")),- )+ )).await}@@ -67,7 +67,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resource_by_id(+ Box::pin(self.find_resource_by_id(key_store,storage_scheme,PaymentMethod::find_by_id(&conn, payment_method_id),@@ -75,7 +75,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {"payment_method_{}",payment_method_id.get_string_repr())),- )+ )).await}@@ -87,12 +87,12 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resource_by_id(+ Box::pin(self.find_resource_by_id(key_store,storage_scheme,PaymentMethod::find_by_locker_id(&conn, locker_id),FindResourceBy::LookupId(format!("payment_method_locker_{locker_id}")),- )+ )).await}@@ -194,21 +194,20 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {.change_context(errors::StorageError::KVError).attach_printable("Failed to generate payment method insert query")?;- let payment_method: DomainPaymentMethod = self- .insert_resource(- key_store,- storage_scheme,- payment_method_new.clone().insert(&conn),- payment_method,- InsertResourceParams {- drainer_query,- reverse_lookups,- key,- identifier,- resource_type: "payment_method",- },- )- .await?;+ let payment_method: DomainPaymentMethod = Box::pin(self.insert_resource(+ key_store,+ storage_scheme,+ payment_method_new.clone().insert(&conn),+ payment_method,+ InsertResourceParams {+ drainer_query,+ reverse_lookups,+ key,+ identifier,+ resource_type: "payment_method",+ },+ ))+ .await?;if let Some(compat_action) = compat_action {compat_action.execute(&payment_method).await;@@ -345,7 +344,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.filter_resources(+ Box::pin(self.filter_resources(key_store,storage_scheme,PaymentMethod::find_by_customer_id_merchant_id_status(@@ -364,7 +363,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {pattern: "payment_method_id_*",limit,},- )+ )).await}@@ -381,7 +380,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, Self::Error> {let conn = pg_connection_read(self).await?;- self.filter_resources(+ Box::pin(self.filter_resources(key_store,storage_scheme,PaymentMethod::find_by_customer_id_merchant_id_status_pm_type(@@ -401,7 +400,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {pattern: "payment_method_id_*",limit,},- )+ )).await}@@ -614,9 +613,8 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.change_context(errors::StorageError::DecryptionError)?;let conn = pg_connection_write(self).await?;- let payment_method: DomainPaymentMethod = self- .call_database(key_store, payment_method_new.insert(&conn))- .await?;+ let payment_method: DomainPaymentMethod =+ Box::pin(self.call_database(key_store, payment_method_new.insert(&conn))).await?;if let Some(compat_action) = compat_action {compat_action.execute(&payment_method).await;@@ -640,12 +638,11 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.change_context(errors::StorageError::DecryptionError)?;let conn = pg_connection_write(self).await?;- let payment_method: DomainPaymentMethod = self- .call_database(- key_store,- payment_method.update_with_payment_method_id(&conn, payment_method_update.into()),- )- .await?;+ let payment_method: DomainPaymentMethod = Box::pin(self.call_database(+ key_store,+ payment_method.update_with_payment_method_id(&conn, payment_method_update.into()),+ ))+ .await?;if let Some(compat_action) = compat_action {compat_action.execute(&payment_method).await;@@ -668,12 +665,11 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.await.change_context(errors::StorageError::DecryptionError)?;let conn = pg_connection_write(self).await?;- let payment_method: DomainPaymentMethod = self- .call_database(- key_store,- payment_method.update_with_id(&conn, payment_method_update.into()),- )- .await?;+ let payment_method: DomainPaymentMethod = Box::pin(self.call_database(+ key_store,+ payment_method.update_with_id(&conn, payment_method_update.into()),+ ))+ .await?;if let Some(compat_action) = compat_action {compat_action.execute(&payment_method).await;@@ -854,10 +850,10 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.and_then(|initiator| initiator.to_created_by()).map(|last_modified_by| last_modified_by.to_string()),};- self.call_database(+ Box::pin(self.call_database(key_store,payment_method.update_with_id(&conn, payment_method_update.into()),- )+ )).await}diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rsindex 9022468b43..2ed9053012 100644--- a/crates/storage_impl/src/payments/payment_attempt.rs+++ b/crates/storage_impl/src/payments/payment_attempt.rs@@ -89,24 +89,26 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<PaymentAttempt, errors::StorageError> {let conn = pg_connection_write(self).await?;- payment_attempt- .construct_new()- .await- .change_context(errors::StorageError::EncryptionError)?- .insert(&conn)- .await- .map_err(|error| {- let new_error = diesel_error_to_data_error(*error.current_context());- error.change_context(new_error)- })?- .convert(- self.get_keymanager_state()- .attach_printable("Missing KeyManagerState")?,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(errors::StorageError::DecryptionError)+ Box::pin(+ payment_attempt+ .construct_new()+ .await+ .change_context(errors::StorageError::EncryptionError)?+ .insert(&conn),+ )+ .await+ .map_err(|error| {+ let new_error = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_error)+ })?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)}#[cfg(feature = "v1")]@@ -122,26 +124,28 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {let key_manager_state = self.get_keymanager_state().attach_printable("Missing KeyManagerState")?;- this.convert()- .await- .change_context(errors::StorageError::EncryptionError)?- .update_with_attempt_id(&conn, payment_attempt.to_storage_model())- .await- .map_err(|er| {- let new_err = diesel_error_to_data_error(*er.current_context());- er.change_context(new_err)- })- .async_map(|diesel_payment_attempt| async {- PaymentAttempt::convert_back(- key_manager_state,- diesel_payment_attempt,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )+ Box::pin(+ this.convert().await- .change_context(errors::StorageError::DecryptionError)- })- .await?+ .change_context(errors::StorageError::EncryptionError)?+ .update_with_attempt_id(&conn, payment_attempt.to_storage_model()),+ )+ .await+ .map_err(|er| {+ let new_err = diesel_error_to_data_error(*er.current_context());+ er.change_context(new_err)+ })+ .async_map(|diesel_payment_attempt| async {+ PaymentAttempt::convert_back(+ key_manager_state,+ diesel_payment_attempt,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ })+ .await?}#[cfg(feature = "v2")]@@ -155,26 +159,28 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {) -> CustomResult<PaymentAttempt, errors::StorageError> {let conn = pg_connection_write(self).await?;- Conversion::convert(this)- .await- .change_context(errors::StorageError::EncryptionError)?- .update_with_attempt_id(- &conn,- diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt),- )- .await- .map_err(|error| {- let new_error = diesel_error_to_data_error(*error.current_context());- error.change_context(new_error)- })?- .convert(- self.get_keymanager_state()- .attach_printable("Missing KeyManagerState")?,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(errors::StorageError::DecryptionError)+ Box::pin(+ Conversion::convert(this)+ .await+ .change_context(errors::StorageError::EncryptionError)?+ .update_with_attempt_id(+ &conn,+ diesel_models::PaymentAttemptUpdateInternal::from(payment_attempt),+ ),+ )+ .await+ .map_err(|error| {+ let new_error = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_error)+ })?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)}#[cfg(feature = "v1")]@@ -1405,7 +1411,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> CustomResult<PaymentAttempt, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resource_by_id(+ Box::pin(self.find_resource_by_id(merchant_key_store,storage_scheme,DieselPaymentAttempt::find_by_profile_id_connector_transaction_id(@@ -1417,7 +1423,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {profile_id.get_string_repr(),connector_transaction_id,)),- )+ )).await}@@ -1673,12 +1679,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PaymentAttempt, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resource_by_id(+ Box::pin(self.find_resource_by_id(merchant_key_store,storage_scheme,DieselPaymentAttempt::find_by_id(&conn, attempt_id),FindResourceBy::LookupId(label::get_global_id_label(attempt_id)),- )+ )).await}@@ -1691,7 +1697,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.filter_resources(+ Box::pin(self.filter_resources(merchant_key_store,storage_scheme,DieselPaymentAttempt::find_by_payment_id(&conn, payment_id),@@ -1701,7 +1707,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {pattern: "pa_*",limit: None,},- )+ )).await}diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rsindex 23433a8d19..08af526cdb 100644--- a/crates/storage_impl/src/payments/payment_intent.rs+++ b/crates/storage_impl/src/payments/payment_intent.rs@@ -725,16 +725,18 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PaymentIntent, StorageError> {let conn = pg_connection_write(self).await?;- let diesel_payment_intent = payment_intent- .construct_new()- .await- .change_context(StorageError::EncryptionError)?- .insert(&conn)- .await- .map_err(|er| {- let new_err = diesel_error_to_data_error(*er.current_context());- er.change_context(new_err)- })?;+ let diesel_payment_intent = Box::pin(+ payment_intent+ .construct_new()+ .await+ .change_context(StorageError::EncryptionError)?+ .insert(&conn),+ )+ .await+ .map_err(|er| {+ let new_err = diesel_error_to_data_error(*er.current_context());+ er.change_context(new_err)+ })?;PaymentIntent::convert_back(self.get_keymanager_state()@@ -759,16 +761,17 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {let conn = pg_connection_write(self).await?;let diesel_payment_intent_update = DieselPaymentIntentUpdate::from(payment_intent);- let diesel_payment_intent = this- .convert()- .await- .change_context(StorageError::EncryptionError)?- .update(&conn, diesel_payment_intent_update)- .await- .map_err(|er| {- let new_err = diesel_error_to_data_error(*er.current_context());- er.change_context(new_err)- })?;+ let diesel_payment_intent = Box::pin(+ this.convert()+ .await+ .change_context(StorageError::EncryptionError)?+ .update(&conn, diesel_payment_intent_update),+ )+ .await+ .map_err(|er| {+ let new_err = diesel_error_to_data_error(*er.current_context());+ er.change_context(new_err)+ })?;PaymentIntent::convert_back(self.get_keymanager_state()diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rsindex 538d7c8c94..b711358433 100644--- a/crates/storage_impl/src/redis/cache.rs+++ b/crates/storage_impl/src/redis/cache.rs@@ -339,6 +339,36 @@ where}}+/// Deja boundary for the in-memory (L1) cache lookup. Captures the `Option<T>`+/// outcome on record and Substitutes it per-correlation on replay: a recorded+/// `Some(v)` returns the value; a recorded `None` (absence) returns `None`, so+/// the caller re-runs the redis fallback — the same control flow as record. The+/// `cache` handle is not serialized (args = cache name + physical key); the+/// value round-trips through `SerdeCodec<Option<T>>`. NOT `fall_through_silent`:+/// a novel L1 read on replay is a real divergence, and falling through would+/// read the cross-correlation-shared moka — fail-stop is correct.+#[cfg(feature = "deja")]+#[deja::boundary(+ boundary = "imc",+ component = "storage_impl::redis::cache",+ operation = "in_memory_get",+ replay = Substitute,+ effect = Imc,+ codec = SerdeCodec,+ args = deja_in_memory_args(cache.name, &cache_key),+)]+async fn deja_in_memory_get<T>(cache: &Cache, cache_key: CacheKey) -> Option<T>+where+ T: Clone + Cacheable + serde::Serialize + serde::de::DeserializeOwned,+{+ cache.get_val::<T>(cache_key).await+}++#[cfg(feature = "deja")]+fn deja_in_memory_args(cache_name: &str, key: &CacheKey) -> serde_json::Value {+ serde_json::json!({ "cache": cache_name, "key": String::from(key.clone()) })+}+#[instrument(skip_all)]pub async fn get_or_populate_in_memory<T, F, Fut>(store: &(dyn RedisConnInterface + Send + Sync),@@ -357,12 +387,23 @@ whereRedisError::RedisConnectionError.into(),)).attach_printable("Failed to get redis connection")?;- let cache_val = cache- .get_val::<T>(CacheKey {- key: key.to_string(),- prefix: redis.key_prefix.clone(),- })- .await;+ let cache_key = CacheKey {+ key: key.to_string(),+ prefix: redis.key_prefix.clone(),+ };+ // Deja L1 seam: the in-memory (moka) lookup is a process-global cache that+ // spans correlations. Instrument the LOOKUP itself (not the surrounding+ // populate) so its `Option` outcome is recorded per-correlation and+ // Substituted on replay — a recorded `Some(v)` returns the value; a recorded+ // `None` re-triggers the (separately instrumented) redis fallback below,+ // identically on record and replay. Because the lookup returns BEFORE redis,+ // L1 and L2 stay sequential (not nested) → no subsumed/orphan event. Record+ // stays a pure observer (the real moka runs); replay never reads the shared+ // moka, so cross-correlation contamination is impossible by construction.+ #[cfg(feature = "deja")]+ let cache_val = deja_in_memory_get::<T>(cache, cache_key).await;+ #[cfg(not(feature = "deja"))]+ let cache_val = cache.get_val::<T>(cache_key).await;if let Some(val) = cache_val {Ok(val)} else {diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rsindex fd71361e0d..bba63f5fca 100644--- a/crates/storage_impl/src/redis/kv_store.rs+++ b/crates/storage_impl/src/redis/kv_store.rs@@ -145,6 +145,18 @@ pub enum KvResult<T: de::DeserializeOwned> {Scan(Vec<T>),}+#[cfg(feature = "deja")]+pub trait DejaKvValue: serde::Serialize {}++#[cfg(feature = "deja")]+impl<T: serde::Serialize> DejaKvValue for T {}++#[cfg(not(feature = "deja"))]+pub trait DejaKvValue {}++#[cfg(not(feature = "deja"))]+impl<T> DejaKvValue for T {}+impl<T> std::fmt::Display for KvOperation<'_, T>whereT: serde::Serialize + Debug,@@ -167,7 +179,7 @@ pub async fn kv_wrapper<'a, T, D, S>(partition_key: PartitionKey<'a>,) -> CustomResult<KvResult<T>, RedisError>where- T: de::DeserializeOwned,+ T: de::DeserializeOwned + DejaKvValue,D: crate::database::store::DatabaseStore,S: serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync,{diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rsindex acd708e617..be0e0bacd0 100644--- a/crates/storage_impl/src/utils.rs+++ b/crates/storage_impl/src/utils.rs@@ -7,6 +7,125 @@ use crate::{metrics, DatabaseStore,};+// Deja replay (R1): the per-correlation DB routing hook, at the ACTUAL storage+// connection seam (the store methods acquire connections here, not via the+// router-crate copy). On a just-leased pg connection during replay, SET+// search_path to the active correlation's schema, derived from the store's+// request_id — a reliable, request-scoped value, NOT the ambient thread-local+// (bled at checkout). No-op outside replay / when the store carries no request id.+// The SET SQL is built by the library (`deja::replay_search_path_sql_for`).+//+// Replay-only fail-loud: a faithless replay (mis-routed / missing schema) must+// STOP rather than silently serve wrong-schema rows, so the hard failures below+// panic. This runs only in a replay sandbox pod (guarded by `replay_is_active`),+// never on a production request path — hence the `clippy::panic` allowance.+#[cfg(feature = "deja")]+#[allow(clippy::panic)]+pub(crate) async fn deja_route_replay_schema<T: DatabaseStore>(+ conn: &mut PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,+ store: &T,+) {+ use async_bb8_diesel::AsyncConnection;+ if !deja::replay_is_active() {+ return;+ }++ // Replay is active but the store carries no request id. Two cases,+ // deliberately distinguished so a real stamping bug fails loud without a+ // background actor spuriously killing the pod:+ // - a correlation context IS active -> the store id should have been stamped+ // and wasn't. The connection would silently route to `public` and serve+ // wrong-schema rows, so fail loud (a definite bug).+ // - both None -> a background actor (scheduler / drainer clone) with no+ // request in flight: routing is legitimately a no-op. Rate-limited log.+ let Some(corr) = store.get_request_id() else {+ if deja::current_correlation_id().is_some() {+ panic!(+ "deja replay: a correlation context is active but the store carries no \+ request_id — DB routing would silently fall through to `public`"+ );+ }+ deja_replay_route_warn_no_correlation();+ return;+ };++ let sql = deja::replay_search_path_sql_for(&corr);+ // The SET must succeed under replay — a swallowed failure leaves the+ // connection on the wrong schema. Propagate loudly (replay-only code).+ let corr_for_set = corr.clone();+ conn.run(move |c| diesel::connection::SimpleConnection::batch_execute(c, &sql))+ .await+ .unwrap_or_else(|e| {+ panic!("deja replay: SET search_path failed for correlation {corr_for_set}: {e:?}")+ });++ // `SET search_path TO "<schema>", public` does NOT error when+ // <schema> is missing — it silently resolves to `public`. Assert the+ // correlation's schema actually resolved, once per correlation (a replay-only+ // roundtrip, cached to avoid per-connection cost). `current_schema() == public`+ // after a per-correlation SET means the schema was never materialized.+ if deja_replay_schema_needs_check(&corr) {+ let corr_for_assert = corr.clone();+ conn.run(move |c| {+ diesel::connection::SimpleConnection::batch_execute(+ c,+ "DO $$ BEGIN IF current_schema() = 'public' THEN \+ RAISE EXCEPTION 'deja replay: correlation schema missing — \+ search_path resolved to public'; END IF; END $$;",+ )+ })+ .await+ .unwrap_or_else(|e| {+ panic!(+ "deja replay: schema-existence check failed for correlation \+ {corr_for_assert} (schema missing or unreachable): {e:?}"+ )+ });+ deja_replay_schema_mark_checked(corr);+ }+}++// Per-correlation cache of schemas already asserted-present, so the+// existence roundtrip runs once per correlation rather than per leased connection.+#[cfg(feature = "deja")]+fn deja_replay_schema_verified() -> &'static std::sync::Mutex<HashSet<String>> {+ static VERIFIED: std::sync::OnceLock<std::sync::Mutex<HashSet<String>>> =+ std::sync::OnceLock::new();+ VERIFIED.get_or_init(|| std::sync::Mutex::new(HashSet::new()))+}++#[cfg(feature = "deja")]+fn deja_replay_schema_needs_check(corr: &str) -> bool {+ deja_replay_schema_verified()+ .lock()+ .map(|set| !set.contains(corr))+ .unwrap_or(true)+}++#[cfg(feature = "deja")]+fn deja_replay_schema_mark_checked(corr: String) {+ if let Ok(mut set) = deja_replay_schema_verified().lock() {+ set.insert(corr);+ }+}++// Rate-limited (>=30s) error log for background-actor DB access with no live+// correlation — noisy-but-benign, so we surface it without flooding.+#[cfg(feature = "deja")]+fn deja_replay_route_warn_no_correlation() {+ static LAST: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);+ let now = std::time::Instant::now();+ if let Ok(mut last) = LAST.lock() {+ if last.is_none_or(|t| now.duration_since(t) >= std::time::Duration::from_secs(30)) {+ *last = Some(now);+ router_env::logger::error!(+ "deja replay: DB access from a background actor with no live correlation \+ (store request_id and deja correlation both None); schema routing no-op'd"+ );+ }+ }+}+pub async fn pg_connection_read<T: DatabaseStore>(store: &T,) -> error_stack::Result<@@ -28,9 +147,14 @@ pub async fn pg_connection_read<T: DatabaseStore>())]let pool = store.get_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(StorageError::DatabaseConnectionError)+ .change_context(StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn pg_connection_write<T: DatabaseStore>(@@ -42,9 +166,14 @@ pub async fn pg_connection_write<T: DatabaseStore>(// Since all writes should happen to master DB only choose master DB.let pool = store.get_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(StorageError::DatabaseConnectionError)+ .change_context(StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn pg_accounts_connection_read<T: DatabaseStore>(@@ -68,9 +197,14 @@ pub async fn pg_accounts_connection_read<T: DatabaseStore>())]let pool = store.get_accounts_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(StorageError::DatabaseConnectionError)+ .change_context(StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn pg_accounts_connection_write<T: DatabaseStore>(@@ -82,9 +216,14 @@ pub async fn pg_accounts_connection_write<T: DatabaseStore>(// Since all writes should happen to master DB only choose master DB.let pool = store.get_accounts_master_pool();- pool.get()+ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut conn = pool+ .get().await- .change_context(StorageError::DatabaseConnectionError)+ .change_context(StorageError::DatabaseConnectionError)?;+ #[cfg(feature = "deja")]+ deja_route_replay_schema(&mut conn, store).await;+ Ok(conn)}pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>(diff --git a/docs/design/deja-non-boundaries.md b/docs/design/deja-non-boundaries.mdnew file mode 100644index 0000000000..c159210a8a--- /dev/null+++ b/docs/design/deja-non-boundaries.md@@ -0,0 +1,61 @@+# Deja: sites deliberately left un-instrumented++Most of the record/replay work is about choosing where a boundary goes. An equally+load-bearing set of decisions is where a boundary deliberately does **not** go. Those+choices are invisible in the code — an absent boundary looks identical to an oversight —+so they are recorded here, and the call sites carry a one-line pointer back to this file.++Two failure modes motivate every entry below.++**Nesting.** A boundary that wraps other boundaries is substituted as a unit on replay.+Substituting the outer call returns the recorded reply *without executing the body*, so+the inner boundaries never run and their events are silently missing from the replay. An+outer boundary over instrumented inner calls therefore does not add fidelity; it removes it.++**Recording a secret that the seam already handles.** Where non-determinism enters at a+narrow seam, instrumenting the seam records the minimum. Instrumenting the surrounding+computation instead records its output — which may be the very secret the seam was chosen+to keep off disk.++## `crypto_operation` — `hyperswitch_domain_models::type_encryption`++Not a boundary. `crypto_operation` is pure computation over inputs that are all already+deterministic on replay, so it reproduces byte-identically when re-run live. Instrumenting+it would only record non-`serde` metadata that cannot be substituted, forcing a dishonest+verdict exclusion.++The single source of crypto non-determinism — the AEAD nonce — is recorded and replayed at+its own seam (`common_utils::crypto::NonceSequence::new`, a `deja::id` boundary). Given+substituted inputs the rest of the chain is pure:++- the master key is config, identical across record and replay;+- `DecryptLocally` of the merchant key store derives the DEK via `GcmAes256::decode_message`,+ which has no randomness;+- the encrypted ciphertext (DEK and PII) arrives from substituted DB reads;+- the plaintext arrives from the kernel-re-driven request.++Recording the output instead would write the plaintext DEK — the merchant's data key — into+the event log, where recording the seam does not.++> **Open item (tracked, not resolved here).** The last paragraph does not currently hold+> globally: `generate_aes256_key` *is* instrumented (`router::services`), and that is the DEK+> generator used by `db::merchant_key_store`, `db::merchant_connector_account` and `db::events`.+> The plaintext DEK therefore does reach the tape at that seam. Under the full-fidelity capture+> policy this may be intended, but the "keeps it off disk" reasoning above is not a guarantee+> the reader should rely on. Tape protection is a separate, deferred workstream.++## `delete_multiple_keys` — `redis_interface` (fred and redis-rs)++Not a boundary. It is a thin wrapper that maps `delete_key` over each key, and `delete_key`+is already hermetic. An outer boundary would nest: substituting the wrapper on replay+returns the recorded reply without executing, skipping the inner `delete_key` calls and+omitting their recorded `DEL` events. The inner boundaries carry record and replay.++## `perform_locking_action` and `free_lock_action` — `router::core::api_locking`++Not boundaries. Acquiring a lock is a redis SETNX-and-get retry loop+(`set_multiple_keys_if_not_exists_and_get_values`); releasing one is a `delete_key` on the+lock key. Neither is an independent source of non-determinism. Once the redis boundary is+hermetic the lock outcome replays deterministically from the recorded redis reply, so a+separate `deja::lock` boundary would only double-record — and substituting it would skip,+and therefore omit, the inner redis call.diff --git a/scripts/seed_superposition.sh b/scripts/seed_superposition.shindex d3d993e159..e7dd6aefd9 100755--- a/scripts/seed_superposition.sh+++ b/scripts/seed_superposition.sh@@ -97,4 +97,58 @@ echo "$SEED_JSON" | jq -c '."default-configs" | to_entries[] | {key: .key, valuepost_or_fail "$SUPERPOSITION_URL/default-config" "$config" "default-config $key"done+# Seed the Deja recording sampler: cohort dimension + override+# ------------------------------------------------------------------------------+# `deja_dimension` is a LOCAL_COHORT on the `path` dimension: its json-logic+# classifies the RAW request path (substring `in`, so parametric paths like+# /payments/{id}/confirm are covered) into "recordable"/"otherwise". The override+# records the recordable bucket; `deja_record` defaults to false (seeded above),+# so /health and other probe traffic skip. The path -> deja_dimension dependency+# graph is derived server-side from the LOCAL_COHORT type.+# Posted here as explicit JSON (not via the TOML) because a cohort's+# dimension_type + json-logic definitions do not round-trip cleanly through yq.+echo "Seeding Deja recording sampler (deja_dimension cohort + deja_record override)..."+post_or_fail "$SUPERPOSITION_URL/dimension" '{+ "dimension": "deja_dimension",+ "position": 10,+ "dimension_type": { "LOCAL_COHORT": "path" },+ "description": "Deja request treatment class (path-derived cohort)",+ "change_reason": "Deja recording sampler",+ "schema": {+ "type": "string",+ "enum": ["recordable", "otherwise"],+ "definitions": {+ "recordable": { "or": [+ { "in": ["/payments", { "var": "path" }] },+ { "in": ["/accounts", { "var": "path" }] },+ { "in": ["/user/signup", { "var": "path" }] },+ { "in": ["/organization", { "var": "path" }] },+ { "in": ["/api_keys", { "var": "path" }] },+ { "in": ["/configs", { "var": "path" }] }+ ]}+ }+ }+}' "deja_dimension cohort"++# The override context is created via PUT /context (context = condition map,+# override = config values): deja_dimension == "recordable" -> deja_record = true.+echo "Creating deja_record override for the recordable cohort..."+ctx_tmp=$(mktemp)+ctx_status=$(curl -sS -o "$ctx_tmp" -w "%{http_code}" -X PUT "$SUPERPOSITION_URL/context" \+ -H "Content-Type: application/json" \+ -H "x-org-id: $ORG_ID" \+ -H "x-workspace: $WORKSPACE_ID" \+ -d '{+ "context": { "deja_dimension": "recordable" },+ "override": { "deja_record": true },+ "description": "Record the recordable endpoint bucket",+ "change_reason": "Deja recording sampler"+ }')+case "$ctx_status" in+ 2??) ;;+ 409) echo " deja_record override already exists (HTTP 409), continuing" ;;+ *) echo "Error: deja_record override failed with HTTP $ctx_status"; cat "$ctx_tmp"; rm -f "$ctx_tmp"; exit 1 ;;+esac+rm -f "$ctx_tmp"+echo "Seeding complete!"