@@ -119,14 +119,14 @@ private AgentScope.Continuation captureSpan(final AgentSpan span, byte source) {
119119 }
120120
121121 private AgentScope activate (
122- final Context context ,
122+ final AgentSpan span ,
123123 final byte source ,
124124 final boolean overrideAsyncPropagation ,
125125 final boolean isAsyncPropagating ) {
126126 ScopeStack scopeStack = scopeStack ();
127127
128128 final ContinuableScope top = scopeStack .top ;
129- if (top != null && top . context . equals (context )) {
129+ if (top != null && span . equals (top . span () )) {
130130 top .incrementReferences ();
131131 return top ;
132132 }
@@ -139,14 +139,16 @@ private AgentScope activate(
139139 return noopScope ();
140140 }
141141
142- assert context != null ;
142+ assert span != null ;
143143
144144 // Inherit the async propagation from the active scope unless the value is overridden
145145 boolean asyncPropagation =
146146 overrideAsyncPropagation
147147 ? isAsyncPropagating
148148 : top != null ? top .isAsyncPropagating () : DEFAULT_ASYNC_PROPAGATING ;
149149
150+ Context context = top != null ? top .context .with (span ) : span ;
151+
150152 final ContinuableScope scope =
151153 new ContinuableScope (this , context , source , asyncPropagation , createScopeState (context ));
152154 scopeStack .push (scope );
@@ -155,6 +157,36 @@ private AgentScope activate(
155157 return scope ;
156158 }
157159
160+ private AgentScope activate (final Context context ) {
161+ ScopeStack scopeStack = scopeStack ();
162+
163+ final ContinuableScope top = scopeStack .top ;
164+ if (top != null && top .context .equals (context )) {
165+ top .incrementReferences ();
166+ return top ;
167+ }
168+
169+ // DQH - This check could go before the check above, since depth limit checking is fast
170+ final int currentDepth = scopeStack .depth ();
171+ if (depthLimit <= currentDepth ) {
172+ healthMetrics .onScopeStackOverflow ();
173+ log .debug ("Scope depth limit exceeded ({}). Returning NoopScope." , currentDepth );
174+ return noopScope ();
175+ }
176+
177+ assert context != null ;
178+
179+ // Inherit the async propagation from the active scope
180+ boolean asyncPropagation = top != null ? top .isAsyncPropagating () : DEFAULT_ASYNC_PROPAGATING ;
181+
182+ final ContinuableScope scope =
183+ new ContinuableScope (this , context , CONTEXT , asyncPropagation , createScopeState (context ));
184+ scopeStack .push (scope );
185+ healthMetrics .onActivateScope ();
186+
187+ return scope ;
188+ }
189+
158190 /**
159191 * Activates a scope for the given {@link ScopeContinuation}.
160192 *
@@ -326,7 +358,7 @@ public Context current() {
326358
327359 @ Override
328360 public ContextScope attach (Context context ) {
329- return activate (context , CONTEXT , false , true );
361+ return activate (context );
330362 }
331363
332364 @ Override
0 commit comments