Structured Concurrency Policy with Cancellations and Timeouts
This policy defines a robust framework for structured concurrency in asynchronous programming environments. It ensures that concurrent tasks are organized hierarchically (parent-child relationships), preventing resource leaks by guaranteeing that child tasks are cancelled when their parent scope completes, fails, or times out. The policy emphasizes cooperative cancellation, propagation of cancellations, and timeout enforcement to build reliable, scalable systems.
Core Principles
-
Hierarchy and Scoping: All concurrent operations must occur within a scope. Scopes form a tree structure:
- A parent scope owns its child scopes/tasks.
- A scope completes only when all its children complete (successfully or cancelled).
-
Cancellation Propagation: Cancellation is cooperative (tasks must check for cancellation) and propagates immediately down the hierarchy:
- Cancelling a parent cancels all descendants.
- Children notify parents on cancellation.
-
Timeouts: Every scope can have an optional timeout. Expiry cancels the scope and all descendants.
-
No Leaks: Orphaned tasks are forbidden; all tasks must be attached to a scope.
-
Error Handling: Failures in children propagate to parents, cancelling siblings.
-
Observability: Scopes emit events for start/complete/cancel/timeout/fail.
Key Components
1. Scope Lifecycle
A scope has states: Active, Cancelling, Cancelled, Completed, TimedOut, Failed.
| State Transition | Trigger | Effect |
|---|
Active → Cancelling | cancel() called or timeout expires | Propagate to children; interrupt blocking ops if possible |
Cancelling → Cancelled | All children cancelled | Scope marked cancelled |
Active → Completed | All children completed successfully | Scope completes |
Active → TimedOut | Timeout expires | Cancel scope |
Any → Failed | Unhandled error in scope or child | Cancel siblings; propagate error |
2. Cancellation Model
- Cooperative: Tasks poll
isCancelled() periodically (e.g., at await points, loops).
- Immediate Propagation: On parent cancel:
- Mark parent
Cancelling.
- Recursively cancel all children (async, non-blocking).
- Await child confirmations.
- Interruption: For blocking operations (e.g., I/O), use interruptible primitives (e.g.,
select in Go, CancellationToken in .NET).
3. Timeout Model
- Per-Scope Timeout: Specified at scope creation (e.g.,
Scope(timeout=5s)).
- Hierarchical: Child timeouts are independent but clipped by parent (effective timeout = min(parent, child)).
- Expiry Handling:
- Cancel scope.
- Log timeout event.
- Propagate
TimeoutError upwards.
API Design (Pseudocode)
Language-agnostic pseudocode, adaptable to Kotlin Coroutines, Swift Task Groups, Java StructuredTaskScope (JDK 21+), or async Rust/Tokio.
// Core Scope Interface
interface Scope {
id: string // Unique ID for tracing
timeout: Duration? // Optional timeout
children: List<Task> // Tracked children
// Launch a child task
launch(block: () -> Unit, timeout: Duration? = null): Task
// Await all children
join(): Result<Unit, Error>
// Cancel this scope and descendants
cancel(reason: string = "Cancelled")
// Check cancellation
isCancelled(): bool
// Events (callbacks or observables)
onCancel(handler: (reason: string) -> Unit)
onTimeout(handler: () -> Unit)
onComplete(handler: () -> Unit)
}
// Task represents a launched unit of work
interface Task {
scope: Scope // Parent scope
isCancelled(): bool
cancel(): Unit
join(): Result<Unit, Error> // Await completion
}
// Factory for root scopes
fun structuredScope(timeout: Duration? = null, block: Scope.() -> Unit): Scope {
val scope = ScopeImpl(timeout)
scope.block() // Execute block within scope
return scope
}
Timeout Implementation Sketch
class ScopeImpl(private val timeout: Duration?) : Scope {
private var timer: Timer? = timeout?.let { Timer(it) { cancel("Timeout") } }
override fun launch(block: () -> Unit, childTimeout: Duration?): Task {
val childScope = ScopeImpl(childTimeout)
val task = TaskImpl(childScope)
children.add(task)
spawnAsync { // Platform-specific async spawn
try {
block()
childScope.join()
} catch (e: CancellationException) {
// Propagate
} finally {
children.remove(task)
checkCompletion()
}
}
return task
}
private fun checkCompletion() {
if (children.isEmpty() && !isCancelled()) {
timer?.cancel()
state = Completed
}
}
}
Usage Examples
1. Basic Parallel Tasks with Timeout
val root = structuredScope(timeout = 10.seconds) {
val task1 = launch({ fetchUserData() }, timeout = 5.seconds)
val task2 = launch({ fetchPosts() })
// Await all
join().expectSuccess() // Fails if timeout or error
}
2. Nested Scopes (Hierarchy)
val root = structuredScope(timeout = 30.seconds) {
val apiScope = launch({
structuredScope(timeout = 20.seconds) {
launch({ callEndpoint1() })
launch({ callEndpoint2() })
}.join()
})
launch({ processData() })
root.cancel("User aborted") // Cancels everything
}
3. Error Propagation
val scope = structuredScope {
launch({ throw NetworkError("Failed") }) // Cancels siblings
launch({ heavyComputation() }) // Gets cancelled
}
val result = scope.join() // Returns NetworkError
Enforcement and Best Practices
- Static Analysis: Linters must flag unscoped async calls.
- Runtime Checks: Throw
UnstructuredTaskException for orphans.
- Defaults: Root scopes timeout after 60s.
- Tracing: Integrate with OpenTelemetry; log scope IDs, durations, reasons.
- Testing: Provide
TestScope with fake timers for unit tests.
Compliance Rules
- Mandatory: All async code in scopes.
- Prohibited: Fire-and-forget tasks; manual child tracking.
- Recommended: Always specify timeouts; use
withTimeout wrappers.
This policy ensures deterministic resource cleanup, fault tolerance, and composability in concurrent systems. Implementations should be verified against these rules for production use.