Skip to content

prefactor_core.context_stack module

Span context stack for managing nested span relationships.

The SpanContextStack provides a stack-based context tracking system for nested spans. Each async context maintains its own stack of active span IDs, allowing automatic parent detection when creating new spans.

This module uses contextvars to ensure proper isolation between concurrent async operations.

class prefactor_core.context_stack.SpanContextStack

Section titled “class prefactor_core.context_stack.SpanContextStack”

Bases: object

Manages a stack of active span IDs within an async context.

The stack tracks the hierarchy of nested spans. The top of the stack is always the current (innermost) active span, which serves as the default parent for any new spans created within the same context.

This class uses contextvars to ensure that each async task maintains its own independent stack, preventing interference between concurrent operations.

SpanContextStack.push(“span-1”) assert SpanContextStack.peek() == “span-1”

SpanContextStack.push(“span-2”) assert SpanContextStack.peek() == “span-2”

SpanContextStack.pop() assert SpanContextStack.peek() == “span-1”

SpanContextStack.pop() assert SpanContextStack.peek() is None

Get the current nesting depth.

  • Returns: The number of active spans in the stack (0 if empty).

Get the current span stack for this async context.

  • Returns: A list of span IDs, from outermost to innermost. Returns an empty list if no spans are active.

Check if the stack is empty.

  • Returns: True if no spans are currently active.

Get the current span ID without removing it from the stack.

  • Returns: The ID of the current (innermost) span, or None if no spans are active in this context.

Pop and return the current span ID from the stack.

  • Returns: The span ID that was removed from the stack, or None if the stack was empty.

Push a span ID onto the stack.

This marks the span as the current (innermost) active span.

  • Parameters: span_id – The ID of the span to push onto the stack.