Skip to content

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

refactor(deja): let the gRPC boundary hold an optional transport (#14000)

Uzair Khan7d7b5899083c
diff --git a/Cargo.lock b/Cargo.lock
index 7370c9fc25..2baf8484a5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2870,7 +2870,7 @@ checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"
[[package]]
name = "deja"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"
+source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"
dependencies = [
"deja-context",
"deja-core",
@@ -2887,7 +2887,7 @@ dependencies = [
[[package]]
name = "deja-context"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"
+source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"
dependencies = [
"pin-project-lite",
]
@@ -2895,7 +2895,7 @@ dependencies = [
[[package]]
name = "deja-core"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"
+source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"
dependencies = [
"serde",
"serde_json",
@@ -2905,7 +2905,7 @@ dependencies = [
[[package]]
name = "deja-derive"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"
+source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"
dependencies = [
"proc-macro2",
"quote",
@@ -2915,7 +2915,7 @@ dependencies = [
[[package]]
name = "deja-diesel"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"
+source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"
dependencies = [
"async-bb8-diesel",
"deja-runtime",
@@ -2925,7 +2925,7 @@ dependencies = [
[[package]]
name = "deja-runtime"
version = "0.1.0"
-source = "git+https://github.com/juspay/deja?rev=337181ebfd74b7e571a63a9cce515ff3c9309db7#337181ebfd74b7e571a63a9cce515ff3c9309db7"
+source = "git+https://github.com/juspay/deja?rev=1838093c7f29938022ba0614d7b78fd2a2e92c4d#1838093c7f29938022ba0614d7b78fd2a2e92c4d"
dependencies = [
"async-trait",
"deja-context",
@@ -8480,6 +8480,7 @@ dependencies = [
"strum 0.26.3",
"subscriptions",
"superposition_sdk",
+ "tempfile",
"tera",
"test_utils",
"thiserror 1.0.69",
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index 924e95f0ea..2495b4cd0a 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -32,7 +32,7 @@ base64-serde = "0.8.0"
blake3 = { version = "1.8.2", features = ["serde"] }
bytes = { version = "1.10.1", features = ["serde"] }
diesel = "2.2.10"
-deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }
+deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", 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/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml
index e33285952a..607eda0d04 100644
--- a/crates/diesel_models/Cargo.toml
+++ b/crates/diesel_models/Cargo.toml
@@ -34,7 +34,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 = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false, features = ["error-stack"] }
+deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false, features = ["error-stack"] }
[lints]
workspace = true
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index 9c2b6ec48d..d3846cf53f 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -64,7 +64,7 @@ aws-smithy-types = "1.3.1"
base64 = "0.22.1"
dyn-clone = "1.0.19"
google-cloud-kms = { version = "0.6.0", optional = true }
-deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }
+deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }
error-stack = "0.4.1"
hex = "0.4.3"
hyper = "0.14.32"
diff --git a/crates/external_services/src/grpc_client/deja_transport.rs b/crates/external_services/src/grpc_client/deja_transport.rs
index 4856a17c8e..4d80ed8a14 100644
--- a/crates/external_services/src/grpc_client/deja_transport.rs
+++ b/crates/external_services/src/grpc_client/deja_transport.rs
@@ -40,18 +40,101 @@ 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.
+///
+/// `inner` is `None` only for a boundary built by
+/// [`DejaGrpcTransport::substituted`] — see there and [`connect_or_substitute`].
#[derive(Debug, Clone)]
pub struct DejaGrpcTransport<S> {
- inner: S,
+ inner: Option<S>,
}
impl<S> DejaGrpcTransport<S> {
- /// Wraps a transport. Call at the construction site, never per request.
+ /// Wraps a live transport. Call at the construction site, never per request.
pub fn new(inner: S) -> Self {
- Self { inner }
+ Self { inner: Some(inner) }
+ }
+
+ /// A boundary with no transport beneath it.
+ ///
+ /// Valid ONLY under replay, where every call is served from the recording:
+ /// readiness is answered directly, and a call the recording cannot answer
+ /// fail-stops via [`fail_stop_absent_transport`] rather than connecting.
+ pub fn substituted() -> Self {
+ Self { inner: None }
+ }
+}
+
+/// Wrap a transport the host builds eagerly, standing in for it under replay.
+///
+/// Under replay `connect` is never run: no rpc is issued live, so the transport
+/// is dead weight and could not have connected anyway. In every other mode it
+/// runs verbatim, and `None` propagates the host's own outcome unchanged.
+pub async fn connect_or_substitute<S, F, Fut>(connect: F) -> Option<DejaGrpcTransport<S>>
+where
+ F: FnOnce() -> Fut,
+ Fut: Future<Output = Option<S>>,
+{
+ if deja::__private::runtime_mode().is_replay() {
+ Some(DejaGrpcTransport::substituted())
+ } else {
+ connect().await.map(DejaGrpcTransport::new)
}
}
+/// Replay fail-stop for a boundary that deliberately has no transport.
+///
+/// Distinct from `deja::__private::fail_stop_substitute_miss`, whose message
+/// offers `replay_strategy = Execute` as the remedy: with nothing beneath the
+/// boundary there is nothing to run, and the miss says nothing about the
+/// candidate either way.
+///
+/// Names the rpc path and authority because `BOUNDARY` and `COMPONENT` are
+/// module constants shared by every transport this wrapper is installed on.
+// Panicking IS deja's fail-stop mechanism, not an accident: `catch_fail_stop_async`
+// classifies the payload by `FAIL_STOP_SENTINEL` and renders the divergence. Returning
+// an error instead would erase the stop from the diff artifact.
+#[allow(clippy::panic)]
+#[cold]
+#[inline(never)]
+fn fail_stop_absent_transport(
+ boundary: &str,
+ component: &str,
+ rpc: &str,
+ authority: Option<&str>,
+) -> ! {
+ let target = match authority {
+ Some(authority) => format!("`{rpc}` at `{authority}`"),
+ None => format!("`{rpc}`"),
+ };
+ panic!(
+ "{} Substitute boundary `{boundary}` in `{component}` has no transport for \
+ {target}. It was constructed for substitution only: the host builds this \
+ transport eagerly, that connect did not succeed, and replay never issues \
+ this call live. The recording has no entry for these args, so there is \
+ nothing to substitute and nothing this boundary could have executed. This \
+ says nothing about the candidate — the call could not have been served \
+ here whatever the candidate did.",
+ deja::FAIL_STOP_SENTINEL
+ );
+}
+
+/// A boundary with no transport asked to issue a call live. Unreachable in
+/// practice — [`DejaGrpcTransport::substituted`] exists only under replay, where
+/// the `run` thunk is never invoked — but named so a broken invariant is legible.
+#[derive(Debug)]
+pub struct AbsentTransportError;
+
+impl std::fmt::Display for AbsentTransportError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(
+ "deja: gRPC boundary has no transport (constructed for substitution only) \
+ and cannot issue this call live",
+ )
+ }
+}
+
+impl std::error::Error for AbsentTransportError {}
+
/// 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`).
@@ -88,7 +171,19 @@ where
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)
+ match &mut self.inner {
+ // KNOWN FRAGILITY, deliberately left alone. This delegates ungated by
+ // `is_active()`, so the inner service answers readiness even on replay.
+ // Safe only because tonic's readiness is buffer-backed, not
+ // connection-backed: `Buffer::poll_ready` checks worker liveness and
+ // queue capacity, not a connection (tonic 0.14.5). An inner service
+ // that answered from a live connection would fail HERE, before `call`
+ // can substitute. Tracked deja-side, where the mode lifecycle a gate
+ // would have to depend on lives.
+ Some(inner) => inner.poll_ready(cx).map_err(Into::into),
+ // Nothing to drive: substitution answers every call.
+ None => Poll::Ready(Ok(())),
+ }
}
#[track_caller]
@@ -96,14 +191,23 @@ where
// 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);
+ let inner = match self.inner.as_mut() {
+ Some(inner) => {
+ let clone = inner.clone();
+ Some(std::mem::replace(inner, clone))
+ }
+ None => None,
+ };
// 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));
+ return match inner {
+ Some(inner) => Box::pin(passthrough(inner, request)),
+ // A transport-less boundary outside replay cannot serve anything.
+ None => Box::pin(async { Err(BoxError::from(AbsentTransportError)) }),
+ };
}
let caller = Location::caller();
Box::pin(boundary_call(inner, request, caller))
@@ -133,7 +237,7 @@ where
/// One unary gRPC exchange as one deja boundary crossing.
async fn boundary_call<S, RB>(
- inner: S,
+ inner: Option<S>,
request: http::Request<TonicBody>,
caller: &'static Location<'static>,
) -> Result<http::Response<TonicBody>, BoxError>
@@ -218,14 +322,35 @@ where
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
+ match inner {
+ // Transport present: a miss may be a genuine novel call, so this keeps
+ // `dispatch_async`'s default substitute-miss fail-stop.
+ Some(inner) => {
+ deja::__private::dispatch_async(
+ observation,
+ move || args_value,
+ move || run_and_capture(inner, rebuilt_request),
+ reconstruct_from_recorded,
+ extract_envelope,
+ )
+ .await
+ }
+ // Transport deliberately absent: a miss establishes nothing about the
+ // candidate, so it gets its own reason. The `run` thunk is never invoked
+ // here (replay + Substitute neither runs nor re-runs); an error rather
+ // than an `unreachable!` so a broken invariant stays legible.
+ None => {
+ deja::__private::dispatch_async_or_miss(
+ observation,
+ move || args_value,
+ move || async { Err(BoxError::from(AbsentTransportError)) },
+ reconstruct_from_recorded,
+ extract_envelope,
+ move || fail_stop_absent_transport(BOUNDARY, COMPONENT, &rpc, authority.as_deref()),
+ )
+ .await
+ }
+ }
}
/// The `run` thunk: forward to the real transport, buffer the response
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index e48967feaf..e98d21ec0f 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -193,39 +193,77 @@ pub struct HyperswitchVaultMetadata {
pub vault_auth_data: VaultConnectorAuth,
}
+/// Connects `endpoint` eagerly, bounded by `connection_timeout`, naming `client_name` on failure.
+///
+/// `None` means the caller must abandon the whole client: an unreachable service is reported here
+/// and nulls [`UnifiedConnectorServiceClient`], so the router serves from the direct connector
+/// path rather than routing live traffic at a service it cannot reach.
+pub async fn connect_ucs_endpoint(
+ endpoint: &tonic::transport::Endpoint,
+ connection_timeout: UcsConnectionTimeoutInSeconds,
+ client_name: &str,
+) -> Option<tonic::transport::Channel> {
+ match timeout(connection_timeout.as_duration(), endpoint.connect()).await {
+ Ok(Ok(channel)) => Some(channel),
+ Ok(Err(err)) => {
+ logger::error!(
+ "Failed to connect to Unified Connector Service for {}: {:?}",
+ client_name,
+ err
+ );
+ None
+ }
+ Err(err) => {
+ logger::error!(
+ "Connection to Unified Connector Service timed out for {}: {:?}",
+ client_name,
+ err
+ );
+ None
+ }
+ }
+}
+
/// Builds a gRPC client. `$connection_timeout` bounds connect; `$request_timeout` bounds each RPC.
+///
+/// The connect is eager and gating: an unreachable service is logged and nulls the whole client,
+/// so the router serves from the direct connector path instead of routing live traffic at a
+/// service it cannot reach. That is the behaviour in every mode this router actually runs in,
+/// recording included, so a recording never diverges from the deployment it records.
+///
+/// Under the `deja` feature the connect is handed to `connect_or_substitute`, which runs it
+/// unchanged except under replay — where no rpc is ever issued live, so the transport is dead
+/// weight and the boundary stands in for it. This file expresses no opinion about deja's modes;
+/// that decision lives in the boundary adapter.
#[macro_export]
macro_rules! build_grpc_client {
($client:ty, $name:expr, $uri:expr, $connection_timeout:expr, $request_timeout:expr) => {{
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)) => {
- // 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 {}: {:?}",
- $name,
- err
- );
- return None;
- }
- Err(err) => {
- router_env::logger::error!(
- "Connection to Unified Connector Service timed out for {}: {:?}",
- $name,
- err
- );
- return None;
- }
- }
+
+ // deja: the same eager connect, handed to the gRPC egress boundary so every unary rpc is
+ // recorded/substituted at the wire level (rank-2 identity). The boundary runs the connect
+ // unchanged in every mode but replay, where it stands in for a transport nothing will
+ // use. Feature-off performs the connect directly and passes the raw channel through.
+ #[cfg(feature = "deja")]
+ let channel = $crate::grpc_client::deja_transport::connect_or_substitute(|| {
+ $crate::grpc_client::unified_connector_service::connect_ucs_endpoint(
+ &endpoint,
+ $connection_timeout,
+ $name,
+ )
+ })
+ .await?;
+
+ #[cfg(not(feature = "deja"))]
+ let channel = $crate::grpc_client::unified_connector_service::connect_ucs_endpoint(
+ &endpoint,
+ $connection_timeout,
+ $name,
+ )
+ .await?;
+
+ <$client>::new(channel)
}};
}
@@ -364,6 +402,19 @@ impl UnifiedConnectorServiceClient {
request_timeout
);
+ // Replay connected nothing — the boundary stands in for every channel — so the
+ // usual claim would be false there. Every other mode performed the same eager
+ // connect it always did.
+ #[cfg(feature = "deja")]
+ if deja::__private::runtime_mode().is_replay() {
+ logger::info!(
+ "Unified Connector Service clients substituted at the deja boundary; no transport connected"
+ );
+ } else {
+ logger::info!("Successfully connected to Unified Connector Service");
+ }
+
+ #[cfg(not(feature = "deja"))]
logger::info!("Successfully connected to Unified Connector Service");
Some(Self {
diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml
index cef7142fee..39cf60c7c9 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 crates
common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }
-deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false, features = ["error-stack"] }
+deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", 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/router/Cargo.toml b/crates/router/Cargo.toml
index 209b379e3c..82c8512c12 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -300,8 +300,8 @@ common_utils = { version = "0.1.0", path = "../common_utils", features = [
"keymanager",
] }
common_types = { version = "0.1.0", path = "../common_types" }
-deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }
-deja-core = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true }
+deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }
+deja-core = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", 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 = [
@@ -341,6 +341,7 @@ awc = { version = "3.7.0", features = ["rustls"] }
derive_deref = "1.1.1"
rand = "0.8.5"
serial_test = "3.2.0"
+tempfile = "3.8"
time = { version = "0.3.41", features = ["macros"] }
tokio = "1.48.0"
tracing-subscriber = { version = "0.3.19", default-features = false, features = ["registry"] }
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 3bd33af9d9..bfe11ffa1c 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -1099,6 +1099,7 @@ pub async fn sync_refund_with_gateway(
);
}
}
+ .in_current_span()
});
let response = state
@@ -1470,6 +1471,7 @@ pub async fn validate_and_create_refund(
);
}
}
+ .in_current_span()
});
}
(updated_refund, raw_response)
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 7f46764f94..5d5298b8dc 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -1052,8 +1052,9 @@ where
create_updated_session_state_with_proxy(state.clone(), proxy_override)
}
None => {
- router_env::logger::debug!(
- "No proxy override available for Shadow UCS, Using the Original State and Sending Request Directly"
+ // info, not debug: this downgrade has to be visible at default log levels.
+ router_env::logger::info!(
+ "No proxy override available for Shadow UCS; falling back to Direct, so no shadow comparison will run for this request"
);
execution_path = ExecutionPath::Direct;
state.clone()
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 81f6a0eff8..b1490c0f8c 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -28,7 +28,7 @@ use hyperswitch_interfaces::webhooks::{
IncomingWebhookFlowError, IncomingWebhookRequestDetails, WebhookContext, WebhookResourceData,
};
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
-use router_env::{instrument, tracing};
+use router_env::{instrument, tracing, tracing::Instrument};
use super::{types, MERCHANT_ID};
use crate::{
@@ -1637,7 +1637,7 @@ async fn refunds_incoming_webhook_flow(
let state_task = state.clone();
let processor_task = platform.get_processor().clone();
let payment_intent_task = payment_intent.clone();
- tokio::spawn(async move {
+ let state_metadata_update = async move {
if let Err(err) = PaymentIntentStateMetadataExt::from(
payment_intent_task
.state_metadata
@@ -1649,7 +1649,8 @@ async fn refunds_incoming_webhook_flow(
{
tracing::error!(?err, "Failed to update intent state metadata for refund");
}
- });
+ };
+ tokio::spawn(state_metadata_update.in_current_span());
let event_type: Option<enums::EventType> = updated_refund.refund_status.into();
@@ -2521,6 +2522,7 @@ async fn disputes_incoming_webhook_flow(
);
}
}
+ .in_current_span()
});
}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 6abcd2d58b..bf62b05148 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -384,7 +384,11 @@ pub struct SinglePurposeOrLoginToken {
pub tenant_id: Option<id_type::TenantId>,
}
-#[derive(serde::Deserialize)]
+// `Serialize` so the decode boundary can record the claims it reconstructs.
+// The untagged round-trip is unambiguous in this direction: `EmbeddedToken`
+// carries neither `user_id` nor `role_id`, both of which `AuthToken` requires,
+// so an embedded token's JSON cannot deserialize as an `AuthToken`.
+#[derive(serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum AuthOrEmbeddedClaims {
AuthToken(AuthToken),
@@ -5000,7 +5004,7 @@ where
pub async fn parse_jwt_payload<A, T>(headers: &HeaderMap, state: &A) -> RouterResult<T>
where
- T: serde::de::DeserializeOwned,
+ T: Serialize + serde::de::DeserializeOwned,
A: SessionStateInfo + Sync,
{
let cookie_token_result =
@@ -6205,25 +6209,109 @@ where
}
}
-pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T>
+/// The decision `jsonwebtoken` reaches about a token, as something that can be
+/// recorded.
+///
+/// [`errors::ApiErrorResponse`] cannot be: it derives neither `Serialize` nor
+/// `Deserialize`, and it carries a hundred variants that have nothing to do with
+/// this call. `decode_jwt` collapses every `jsonwebtoken` failure into two of
+/// them anyway, so these are those two and nothing else crosses the boundary.
+/// The mapping back to the public error type stays in `decode_jwt`, unchanged.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, thiserror::Error,
+)]
+pub enum JwtDecodeOutcome {
+ /// The token parsed and verified, but `exp` had passed.
+ #[error("expired JWT token")]
+ Expired,
+ /// Anything else: malformed, wrong algorithm, bad signature, absent claims.
+ #[error("invalid JWT token")]
+ Invalid,
+}
+
+/// Names a token to the recorder without putting the token in the tape.
+///
+/// A recording lives in object storage for weeks and is read by anyone who can
+/// read the bucket; a dashboard JWT stays valid for two days
+/// (`consts::JWT_TOKEN_TIME_IN_SECS`). The digest is enough to pair a replayed
+/// call with its recorded outcome and cannot be presented as a credential.
+#[cfg(feature = "deja")]
+fn token_digest(token: &str) -> String {
+ blake3::hash(token.as_bytes()).to_hex().to_string()
+}
+
+/// Verifies `token` and returns its claims, or which of the two failures it hit.
+///
+/// This is a boundary because the clock that decides the answer is not one deja
+/// can reach. `Validation::new` defaults `validate_exp` to true and
+/// `jsonwebtoken` reads `SystemTime::now()` itself, so the instrumented
+/// `date_time::now` boundary never sees it — the same bypass already recorded
+/// on the issuing side in `services::jwt::generate_exp`. API-key expiry has no
+/// such problem: it compares against `date_time::now()` and so already replays
+/// deterministically. Recording the decode outcome takes the clock out of the
+/// replay path entirely, rather than trying to hold it still.
+///
+/// The seam is deliberately this narrow. Recording the whole authentication
+/// result instead would also swallow the merchant-key-store, merchant-account,
+/// business-profile and decrypt calls that follow it, which are exactly the
+/// calls a replay exists to compare.
+///
+/// A token absent from the recording does not decode silently: the substitute
+/// misses and the boundary fail-stops, the same as any other missed substitute.
+///
+/// `pub` only so the boundary can be exercised from an integration test:
+/// `set_global_runtime_hook` is a one-shot `OnceLock`, so record and replay
+/// each need their own test binary, and a test binary cannot reach a private
+/// item. Callers should use [`decode_jwt`].
+#[doc(hidden)]
+#[cfg_attr(
+ feature = "deja",
+ deja::time(
+ component = "router::authentication",
+ operation = "decode_jwt",
+ codec = deja::codec::ResultCodec::<T, JwtDecodeOutcome>,
+ args = {
+ serde_json::json!({
+ "token_digest": token_digest(token),
+ // Two call sites may present the same token for different
+ // claims, and their recorded shapes differ. Identity says which.
+ "claims_type": std::any::type_name::<T>(),
+ })
+ },
+ )
+)]
+pub fn decode_jwt_verified<T>(
+ token: &str,
+ secret: &[u8],
+) -> common_utils::errors::CustomResult<T, JwtDecodeOutcome>
where
- T: serde::de::DeserializeOwned,
+ T: Serialize + serde::de::DeserializeOwned,
{
- let conf = state.conf();
- let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes();
-
let key = DecodingKey::from_secret(secret);
decode::<T>(token, &key, &Validation::new(Algorithm::HS256))
.map(|decoded| decoded.claims)
.map_err(|e| {
if e.kind() == &ExpiredSignature {
- report!(errors::ApiErrorResponse::ExpiredJwtToken)
+ report!(JwtDecodeOutcome::Expired)
} else {
- report!(errors::ApiErrorResponse::InvalidJwtToken)
+ report!(JwtDecodeOutcome::Invalid)
}
})
}
+pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T>
+where
+ T: Serialize + serde::de::DeserializeOwned,
+{
+ let conf = state.conf();
+ let secret = conf.secrets.get_inner().jwt_secret.peek().as_bytes();
+
+ decode_jwt_verified::<T>(token, secret).map_err(|report| match report.current_context() {
+ JwtDecodeOutcome::Expired => report!(errors::ApiErrorResponse::ExpiredJwtToken),
+ JwtDecodeOutcome::Invalid => report!(errors::ApiErrorResponse::InvalidJwtToken),
+ })
+}
+
pub fn get_api_key(headers: &HeaderMap) -> RouterResult<&str> {
get_header_value_by_key("api-key".into(), headers)?.get_required_value("api_key")
}
diff --git a/crates/router/src/services/kafka/deja_record_sink.rs b/crates/router/src/services/kafka/deja_record_sink.rs
index cef484be56..5d0f87e461 100644
--- a/crates/router/src/services/kafka/deja_record_sink.rs
+++ b/crates/router/src/services/kafka/deja_record_sink.rs
@@ -392,6 +392,9 @@ mod tests {
correlation_id: Some("c-123".to_string()),
timestamp_ns: 1_000_000_000,
recording_run_id: Some("run-abc".to_string()),
+ // Egress event, so no structural role. `role` skips serialization
+ // when `None`, which keeps the envelope shape this test asserts.
+ role: None,
graph_node_id: None,
tracing_span_id: None,
task_id: None,
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index e27972b6ec..796969425d 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1501,7 +1501,7 @@ pub async fn trigger_subscriptions_outgoing_webhook(
let created_at = subscription.created_at;
let business_profile = profile.clone();
- tokio::spawn(async move {
+ let outgoing_webhook = async move {
Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook(
cloned_state,
platform,
@@ -1516,7 +1516,8 @@ pub async fn trigger_subscriptions_outgoing_webhook(
business_profile,
))
.await
- });
+ };
+ tokio::spawn(outgoing_webhook.in_current_span());
Ok(())
}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index a17506dab0..be15b7370b 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -16,7 +16,7 @@ use error_stack::ResultExt;
use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount as DomainMerchantConnectorAccount;
use hyperswitch_masking::{ExposeInterface, Secret};
use redis_interface::RedisConnectionWithContext;
-use router_env::{env, instrument, logger, tracing};
+use router_env::{env, instrument, logger, tracing, tracing::Instrument};
use crate::{
consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL},
@@ -359,7 +359,7 @@ pub fn spawn_async_lineage_context_update_to_db(
let state = state.clone();
let lineage_context = lineage_context.clone();
let user_id = user_id.to_owned();
- tokio::spawn(async move {
+ let lineage_update = async move {
match state
.global_store
.update_active_user_by_user_id(
@@ -379,7 +379,8 @@ pub fn spawn_async_lineage_context_update_to_db(
);
}
}
- });
+ };
+ tokio::spawn(lineage_update.in_current_span());
}
pub fn generate_env_specific_merchant_id(value: String) -> UserResult<id_type::MerchantId> {
diff --git a/crates/router/tests/deja_jwt_novel_token_fail_stops.rs b/crates/router/tests/deja_jwt_novel_token_fail_stops.rs
new file mode 100644
index 0000000000..10012a5afe
--- /dev/null
+++ b/crates/router/tests/deja_jwt_novel_token_fail_stops.rs
@@ -0,0 +1,62 @@
+// Integration test: assertions use panic!/expect(); allow the production-code
+// lints the v2 clippy profile denies.
+#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used)]
+//! A token the recording has never seen must not decode silently on replay.
+//!
+//! Substituting the decode outcome is what takes the clock out of the replay
+//! path, but it must not become a way for an unknown credential to be accepted.
+//! An empty lookup table guarantees a miss for any call, so this is decisive
+//! without constructing a matching key: the boundary fail-stops, and the real
+//! `jsonwebtoken` decode never runs.
+//!
+//! Own test binary: `set_global_runtime_hook` is a one-shot `OnceLock`.
+#![cfg(feature = "deja")]
+
+use router::services::authentication::decode_jwt_verified;
+
+// `Debug` because `expect_err` requires it on the Ok type.
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+struct Claims {
+ sub: String,
+}
+
+#[test]
+fn a_token_absent_from_the_recording_fail_stops() {
+ let table = deja::LookupTable {
+ recording_id: "jwt-novel-token-test".to_string(),
+ policy_version: 1,
+ entries: vec![],
+ };
+ let dir = tempfile::tempdir().expect("tempdir");
+ let path = dir.path().join("lookup.json");
+ std::fs::write(&path, serde_json::to_vec(&table).expect("serialize")).expect("write table");
+
+ let hook = deja::LookupTableHook::from_source(
+ deja::LocalFileLookupSource::new(path),
+ deja::InMemoryObservedSink::new(),
+ )
+ .expect("hook");
+ deja::set_global_runtime_hook(Some(deja::RuntimeHook::LookupReplay(hook)))
+ .expect("install replay hook");
+
+ // The fail-stop's panic backtrace is expected; silence the default hook.
+ let prev = std::panic::take_hook();
+ std::panic::set_hook(Box::new(|_| {}));
+ let result = std::panic::catch_unwind(|| {
+ decode_jwt_verified::<Claims>("a-token-this-recording-has-never-seen", b"test-secret")
+ });
+ std::panic::set_hook(prev);
+
+ let payload = result.expect_err(
+ "a token absent from the recording must FAIL-STOP — not fall through to a real decode",
+ );
+ let message = payload
+ .downcast_ref::<String>()
+ .map(String::as_str)
+ .or_else(|| payload.downcast_ref::<&str>().copied())
+ .unwrap_or("<non-string panic payload>");
+ assert!(
+ message.contains("deja replay fail-stop") && message.contains("decode_jwt"),
+ "the fail-stop must name the boundary that missed; got: {message:?}"
+ );
+}
diff --git a/crates/router/tests/deja_jwt_tape_excludes_token.rs b/crates/router/tests/deja_jwt_tape_excludes_token.rs
new file mode 100644
index 0000000000..a7ad2c5688
--- /dev/null
+++ b/crates/router/tests/deja_jwt_tape_excludes_token.rs
@@ -0,0 +1,89 @@
+// Integration test: assertions use panic!/expect(); allow the production-code
+// lints the v2 clippy profile denies.
+#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used)]
+//! A recording must be able to pair a replayed `decode_jwt` with its recorded
+//! outcome without carrying the token that produced it.
+//!
+//! A tape lives in object storage for weeks and is read by anyone who can read
+//! the bucket. A dashboard JWT stays valid for two days, so a tape that quoted
+//! one would be handing out a live credential. The boundary therefore records a
+//! digest, and this test reads the artifact bytes back off disk and asserts the
+//! token itself is nowhere in them.
+//!
+//! Own test binary: `set_global_runtime_hook` is a one-shot `OnceLock`, so the
+//! recording install here cannot share a process with the replay install in
+//! `deja_jwt_novel_token_fail_stops.rs`.
+#![cfg(feature = "deja")]
+
+use router::services::authentication::{decode_jwt_verified, JwtDecodeOutcome};
+
+/// Not a real JWT. The boundary records the outcome whichever way the decode
+/// goes, and `Err(Invalid)` exercises the same capture path as a success while
+/// keeping the test free of a signing fixture.
+const TOKEN: &str = "deja-tape-probe.this-string-must-not-reach-the-tape.0123456789";
+
+const CORRELATION_ID: &str = "req-deja-jwt-tape-excludes-token";
+
+// `Debug` because `expect_err` requires it on the Ok type.
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+struct Claims {
+ sub: String,
+}
+
+fn artifact_bytes(dir: &std::path::Path) -> Vec<u8> {
+ let mut out = Vec::new();
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(path) = stack.pop() {
+ for entry in std::fs::read_dir(&path).expect("read artifact dir") {
+ let entry = entry.expect("dir entry");
+ let entry_path = entry.path();
+ if entry_path.is_dir() {
+ stack.push(entry_path);
+ } else {
+ out.extend(std::fs::read(&entry_path).expect("read artifact file"));
+ }
+ }
+ }
+ out
+}
+
+#[test]
+fn recorded_call_carries_a_digest_and_never_the_token() {
+ let artifacts = tempfile::tempdir().expect("tempdir");
+ deja::set_global_runtime_hook(Some(deja::RuntimeHook::Recording(std::sync::Arc::new(
+ deja::RecordingHook::new(artifacts.path()).expect("recording hook"),
+ ))))
+ .expect("install recording hook");
+ // Recording is gated on a correlation being CURRENT, not merely on a
+ // decision being registered for one — an earlier version of this test set
+ // the decision alone and recorded nothing at all. The guard must outlive
+ // the call below, so it is bound rather than dropped.
+ let _correlation = deja::test_support::recording_correlation(CORRELATION_ID);
+
+ let outcome = decode_jwt_verified::<Claims>(TOKEN, b"test-secret");
+ assert_eq!(
+ outcome
+ .expect_err("a non-JWT string cannot decode")
+ .current_context(),
+ &JwtDecodeOutcome::Invalid,
+ "a malformed token is Invalid, not Expired"
+ );
+
+ deja::flush_global_runtime_hook().ok();
+ let bytes = artifact_bytes(artifacts.path());
+ assert!(
+ !bytes.is_empty(),
+ "the boundary must have recorded something to assert about"
+ );
+
+ let haystack = String::from_utf8_lossy(&bytes);
+ assert!(
+ !haystack.contains(TOKEN),
+ "the raw token must never appear in a recording artifact"
+ );
+ let digest = blake3::hash(TOKEN.as_bytes()).to_hex().to_string();
+ assert!(
+ haystack.contains(&digest),
+ "the recording must carry the token's digest, or replay cannot pair the call"
+ );
+}
diff --git a/crates/router/tests/detached_spawn_inventory.rs b/crates/router/tests/detached_spawn_inventory.rs
new file mode 100644
index 0000000000..aa9c0dc06a
--- /dev/null
+++ b/crates/router/tests/detached_spawn_inventory.rs
@@ -0,0 +1,182 @@
+// Integration test: assertions use panic!/expect(); allow the production-code
+// lints the v2 clippy profile denies.
+#![allow(clippy::panic, clippy::expect_used, clippy::unwrap_used)]
+//! Detached work must carry the request span.
+//!
+//! deja attributes a boundary to a correlation by reading the tracing span the
+//! work is running under (`DejaCorrelationLayer`, keyed on the `request_id`
+//! field the ingress root span stamps). A `tokio::spawn` whose future carries no
+//! span hands the child neither the correlation nor anything to resolve one
+//! from, so every boundary it crosses records uncorrelated — or, once the
+//! request's recording is closed, records nothing at all and leaves the tape
+//! ending mid-correlation with no marker to say why.
+//!
+//! So the rule is the tracing convention, not a deja-specific one: **a spawned
+//! future is instrumented**. `.in_current_span()` for work that belongs to the
+//! request, or `.instrument(some_span)` where the site already builds its own.
+//! This test inspects the argument of every `tokio::spawn` in the crates that
+//! serve a request and fires only when one is bare, so adding a correctly
+//! instrumented spawn needs no change here.
+//!
+//! Crates outside the request path (`drainer`, `scheduler`, the redis and
+//! database connection pools) are not scanned: nothing there runs under a
+//! correlation, so nothing there can truncate one.
+//!
+//! Carrying the request span attributes the work; it does not give the child a
+//! span of its own, so its boundaries still address below rank 2. That is a
+//! deliberate deferral — naming those spans is address-additive and measurable
+//! on its own — not an oversight.
+
+use std::{collections::BTreeMap, fs, path::Path};
+
+/// Crates in which an HTTP request correlation is live.
+const SCANNED_ROOTS: &[&str] = &[
+ "crates/router/src",
+ "crates/router_env/src",
+ "crates/hyperswitch_interfaces/src",
+];
+
+/// Files permitted to spawn an uninstrumented future, with the count in that
+/// file and the reason no correlation is being lost.
+const ALLOWED_BARE: &[(&str, usize, &str)] = &[
+ (
+ "crates/router/src/routes/metrics/bg_metrics_collector.rs",
+ 1,
+ "process-lifetime: the background metrics collector, spawned at startup \
+ with no request in scope",
+ ),
+ (
+ "crates/router/src/db/events.rs",
+ 1,
+ "test-only: the concurrent webhook-creation test in this module's \
+ #[cfg(test)] block",
+ ),
+ (
+ "crates/router/src/services/authentication/decision.rs",
+ 1,
+ "the #[cfg(not(feature = \"deja\"))] arm of spawn_tracked_job; the deja \
+ arm carries context through deja::spawn_fork, so nothing is lost from a \
+ recording. The bare arm costs log context only, and is worth tidying \
+ separately — changing it under the deja feature would move an existing \
+ fork region and re-address the tape",
+ ),
+];
+
+fn workspace_root() -> &'static Path {
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .ancestors()
+ .nth(2)
+ .expect("crates/<name> is two levels below the workspace root")
+}
+
+/// The argument text of each `tokio::spawn(...)` in `source`, by paren matching,
+/// with the 1-based line the call starts on. Matching the parens rather than
+/// scanning lines is what lets the check look at the spawned expression itself
+/// instead of guessing from nearby text.
+fn spawned_arguments(source: &str) -> Vec<(usize, String)> {
+ const CALL: &str = "tokio::spawn(";
+ let mut found = Vec::new();
+ let mut from = 0;
+ while let Some(offset) = source[from..].find(CALL) {
+ let start = from + offset;
+ let line = source[..start].matches('\n').count() + 1;
+ let after_call = start + CALL.len();
+ // Walk to the paren that closes the call. An unbalanced tail leaves `end`
+ // just past `CALL`, which still advances `from` — no rescan, no loop.
+ let mut depth = 1usize;
+ let mut end = after_call;
+ for (index, character) in source[after_call..].char_indices() {
+ match character {
+ '(' => depth += 1,
+ ')' => depth -= 1,
+ _ => {}
+ }
+ if depth == 0 {
+ end = after_call + index + character.len_utf8();
+ break;
+ }
+ }
+ found.push((line, source[start..end].to_owned()));
+ from = end;
+ }
+ found
+}
+
+fn is_instrumented(argument: &str) -> bool {
+ argument.contains(".in_current_span()") || argument.contains(".instrument(")
+}
+
+fn collect(root: &Path, relative: &Path, bare: &mut BTreeMap<String, Vec<usize>>) {
+ let directory = root.join(relative);
+ let entries = fs::read_dir(&directory)
+ .unwrap_or_else(|error| panic!("read {}: {error}", directory.display()));
+ for entry in entries {
+ let entry = entry.expect("directory entry");
+ let path = entry.path();
+ let child = relative.join(entry.file_name());
+ if path.is_dir() {
+ collect(root, &child, bare);
+ } else if path.extension().is_some_and(|extension| extension == "rs") {
+ let source = fs::read_to_string(&path)
+ .unwrap_or_else(|error| panic!("read {}: {error}", path.display()));
+ for (line, argument) in spawned_arguments(&source) {
+ if !is_instrumented(&argument) {
+ bare.entry(child.to_string_lossy().replace('\\', "/"))
+ .or_default()
+ .push(line);
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn every_spawned_future_on_the_request_path_carries_a_span() {
+ let root = workspace_root();
+ let mut bare = BTreeMap::new();
+ for scanned in SCANNED_ROOTS {
+ collect(root, Path::new(scanned), &mut bare);
+ }
+
+ let allowed: BTreeMap<&str, (usize, &str)> = ALLOWED_BARE
+ .iter()
+ .map(|(path, count, reason)| (*path, (*count, *reason)))
+ .collect();
+
+ let mut problems = Vec::new();
+ for (path, lines) in &bare {
+ match allowed.get(path.as_str()) {
+ None => problems.push(format!(
+ "{path}: spawns an uninstrumented future at line(s) {lines:?}.\n \
+ Work detached from a request must carry its span, or deja cannot \
+ attribute it and its boundaries record uncorrelated — or, past \
+ the request's teardown, not at all. Add `.in_current_span()` (or \
+ `.instrument(..)` if the site builds its own span). If no request \
+ is in scope here, add the file to ALLOWED_BARE with that reason."
+ )),
+ Some((allowed_count, reason)) if allowed_count != &lines.len() => {
+ problems.push(format!(
+ "{path}: {} uninstrumented spawn(s) at {lines:?}, ALLOWED_BARE \
+ says {allowed_count} ({reason}).\n Check the new one \
+ against the same question before updating the count.",
+ lines.len()
+ ));
+ }
+ Some(_) => {}
+ }
+ }
+ for (path, (count, reason)) in &allowed {
+ if !bare.contains_key(*path) {
+ problems.push(format!(
+ "{path}: ALLOWED_BARE expects {count} uninstrumented spawn(s) \
+ ({reason}) but the file has none. Drop the stale entry."
+ ));
+ }
+ }
+
+ assert!(
+ problems.is_empty(),
+ "detached work is losing its request span:\n - {}",
+ problems.join("\n - ")
+ );
+}
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 026c0623b7..860b1a97ca 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -10,8 +10,8 @@ license.workspace = true
[dependencies]
cargo_metadata = "0.18.1"
config = { version = "0.14.1", features = ["toml"] }
-deja = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }
-deja-core = { git = "https://github.com/juspay/deja", rev = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true }
+deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true, default-features = false }
+deja-core = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", optional = true }
error-stack = "0.4.1"
gethostname = "0.4.3"
# Optional (deja-only): types the captured request/response payloads as `Secret`
diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml
index 61a005e672..23fc2105f8 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 = "337181ebfd74b7e571a63a9cce515ff3c9309db7", optional = true, default-features = false }
+deja = { git = "https://github.com/juspay/deja", rev = "1838093c7f29938022ba0614d7b78fd2a2e92c4d", 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/migrations/2026-09-02-104500_drop_stale_default_on_payment_intent_business_label/down.sql b/migrations/2026-09-02-104500_drop_stale_default_on_payment_intent_business_label/down.sql
new file mode 100644
index 0000000000..f6c799762f
--- /dev/null
+++ b/migrations/2026-09-02-104500_drop_stale_default_on_payment_intent_business_label/down.sql
@@ -0,0 +1,3 @@
+-- Restores the default this migration removed. Reverting reintroduces the
+-- divergence between a freshly migrated database and a long-running one.
+ALTER TABLE payment_intent ALTER COLUMN business_label SET DEFAULT 'default';
diff --git a/migrations/2026-09-02-104500_drop_stale_default_on_payment_intent_business_label/up.sql b/migrations/2026-09-02-104500_drop_stale_default_on_payment_intent_business_label/up.sql
new file mode 100644
index 0000000000..9953335d56
--- /dev/null
+++ b/migrations/2026-09-02-104500_drop_stale_default_on_payment_intent_business_label/up.sql
@@ -0,0 +1,18 @@
+-- `payment_intent.business_label` still carries `DEFAULT 'default'` from
+-- 2023-03-23, when the column was created `NOT NULL DEFAULT 'default'` — a
+-- default being what NOT NULL requires. 2023-08-28 dropped the NOT NULL and
+-- left the default behind.
+--
+-- Three of the four columns created that way have since had the default
+-- removed: merchant_connector_account.business_country and .business_label in
+-- 2023-02-20, payment_intent.business_country in 2023-04-05 (alongside its enum
+-- conversion). This column is the one that was missed, so the value is an
+-- omission rather than a choice.
+--
+-- It is not inert. A freshly migrated database inserts the literal string
+-- 'default' where a long-running one stores NULL, for byte-identical SQL:
+-- diesel's Insertable emits the SQL keyword DEFAULT for an Option::None field
+-- rather than binding NULL, so the value is decided by the schema alone. The
+-- row then reads back as 'default' and is carried into later updates, which is
+-- how one schema difference becomes a behavioural one.
+ALTER TABLE payment_intent ALTER COLUMN business_label DROP DEFAULT;