# Concurrency -- Deep Dive

This page covers advanced concurrency features: the M:N scheduler, synchronization primitives, and channel patterns.

This page separates public task/channel behavior from runtime implementation
notes. The complete [async workflow](async.md) and
[fan-in example](fan-in.md) are the starting points for application
code. Internal scheduler and synchronization types are not public imports.

## M:N Scheduler Architecture

Vex uses an M:N user-space scheduler: M coroutines multiplexed onto N operating system threads. This is the same model as Go's runtime, but Vex's scheduler is designed for both throughput and latency-sensitive workloads.

### Architecture Overview

```text
User tasks
  → compiler-selected scheduler variant
  → owner-local queues / shared work distribution
  → worker execution and bounded stealing
  ↔ channel wakeups / timer deadlines / native I/O provider
```

This is a responsibility map, not a fixed object layout. The compiler can
select a cooperative-local runtime for a graph that needs no external wake
provider; the full M:N runtime has different initialization and shutdown rules.

### Worker Threads

The development M:N runtime derives a worker ceiling from CPU discovery and
caps its default at 32. Embedders and compiler-selected runtime variants can
use different configurations. A CPU count query is not a scheduler introspection
API, and this guide does not prescribe a `VEX_WORKERS` environment variable or
a `vex.toml` key without an implementation that consumes it.

### Work-Stealing Algorithm

Each worker maintains a **local deque** (double-ended queue) of tasks:

1. **Push/pop from local end** -- The owning worker pushes new tasks to the back and pops from the back (LIFO, cache-friendly).
2. **Steal from remote end** -- Idle workers steal from the front of another worker's deque (FIFO from that end; task age does not establish task size).
3. **Global queue fallback** -- If all deques are empty, workers check the global queue.

The runtime contains a Chase-Lev-style deque. Its atomic publication and
steal protocol are implementation details; FIFO/LIFO endpoints do not promise
application-level task order or a latency bound.

```
Worker A's deque:  [task1, task2, task3, task4]
                     ^                    ^
                     |                    |
              Steal (FIFO)          Push/Pop (LIFO)
```

### Task Lifecycle

```
Created --> Queued --> Running --> Complete
                  |         |
                  |         +--> Suspended (await) --> Queued
                  |
                  +--> Stolen (migrated to another worker)
```

## `go` Blocks -- Deep Semantics

### Capture Semantics

`go` capture analysis selects ownership behavior from the value and how it is
used. An owned value can move into the task; some shared owners use their
documented sharing protocol. A borrowed reference must not outlive its owner:

```vex
fn spawnTasks(data: Vec<i32>) {
    // data is moved into the go block -- cannot be used after
    go {
        for item in data {
            process(item)
        }
    }
    // data is inaccessible here -- compile error
}
```

For mutable coordination, use `Channel<T>`. Immutable owned data may be captured
through `Box<T>`; VUMM recognizes the cross-task escape and selects the required
thread-safe representation internally. Vex does not expose `Arc`, `Rc`, reference
counts, or thread-ownership bookkeeping to application code:

The owner and immutable captures must remain valid until every task completes.
A function that starts two tasks and returns without a completion protocol is
not a useful proof of shared ownership. Use separate result/completion messages
as in the [fan-in example](fan-in.md), and validate any custom
sharing protocol's final drop behavior.

### `go` with Return Values

`go` blocks do not return values directly. Use channels or shared state:

```vex
fn computeAsync(): Channel<i32> {
    let! ch = Channel.new<i32>(1)

    go {
        let result = expensiveComputation()
        ch <- result        // send result through channel
    }

    return ch               // caller receives the channel
}

fn main() {
    let resultCh = computeAsync()
    // ... do other work ...
    let result = <-resultCh  // blocks until result is ready
    $println(f"Result: {result}")
}
```

### Capture and Lifetime Boundaries

A spelling such as `&T` or `&T!` alone does not determine every accepted capture.
The compiler checks origin, lifetime, storage and mutation. Moving a pointer
is not the same as transferring ownership of what it points to. Keep borrowed
views within the lifetime of their storage; use an owning value or explicit
communication when work may outlive its caller.

### Exact detached batches and automatic fanout

When a detached integer-range group has an exact small task count, a
non-suspending body, and a capture layout whose ownership can be completed
before publication, the compiler may lower the source operation as one private
batch. This is a physical optimization only: it does not change iteration
values, ownership, completion, or source-visible concurrency semantics.

The compiler chooses producer-local or 2/4/8-way publication from the target,
the exact task population, and a transitive typed-HIR cost. Calls are followed
by resolved semantic identity and exact generic instantiation, never by a
function-name match. Recursion, indirect calls, dynamic control flow,
unsupported targets, or incomplete inference retain the ordinary scheduler
path. Suspension uses a separate persistent-frame admission path described
below; it never uses transient inline capture storage.

Automatic fanout is also subordinate to the runtime's configured worker
ceiling. For example, an eight-way compiler request in a four-worker embedder
uses at most four execution contexts; it never silently expands the pool.
This keeps scheduler tuning and host resource ownership under application
control while allowing zero-source-noise batching where the proof is complete.

Exact owned indexed sources participate in the same physical optimization.
Copy arrays move into one generation-owned aggregate, while `Vec<T>` and
`Deque<T>` move one owning container and yield immutable `&T` items to the lane
tasks. A Deque remains a ring: the compiler transports its semantic head and
capacity and maps logical indices directly to wrapped physical slots without
linearizing or copying it. The final lane releases compiler-generated drop glue
exactly once. Borrowed Slice/Span views intentionally keep the ordinary path,
because a view alone does not prove that its backing owner outlives detached
execution.

Read-only shared captures may also use this exact batch path when ownership can
be completed before reservation. Today that proof is available for the exact
`Channel<T>` language item and for `Box<T>` sites that VUMM has selected as
thread-safe shared owners. `Box<T>` remains the public API; no Arc type or
manual thread-aware ownership leaks into user code. Retains may be combined
into one same-owner multiplicity operation before private task reservation. The
compiler passes the exact owner and lane count directly; no pointer array is
materialized, and VexArch performs one RC update or one uncontended CAS.
Channel and VUMM ownership remain distinct internally, so this optimization
cannot accidentally apply VUMM release or permanence rules to Channel storage.
Owned strings and arbitrary user containers remain fail-closed because their
clone operation may allocate or otherwise fail.

Suspending Array, Vec, and Deque bodies retain the same ownership model rather
than falling back to one universal coroutine. One allocation owns the single
source value and exactly N persistent lane frames. Array/Vec frames carry only
`data`, `length`, and a logical cursor; Deque adds `head` and `capacity` so every
lane can address the ring directly. Generic iterator state is omitted.
Vec/Deque drop glue runs exactly once after the final lane reaches terminal
completion, including lane-local `break`; Copy arrays need no owner destructor.
The parent evaluates the source once, even when the `go` is nested in an async
function.

For an integer-range body that can suspend, `go(cpu: N) for` likewise creates
exactly N persistent coroutine lanes rather than one universal task. The parent
evaluates range bounds or a trusted first-class `Range` once, allocates one
aggregate frame generation, initializes every private lane, and publishes the
group once. Lane `i` visits offsets `i, i + N, ...` from a widened frame field.
Empty lanes finish normally, and inclusive integer maxima cannot wrap at the
source width.

Transient inline captures remain DONE-only. Aggregate coroutine frames instead
survive YIELDED/WAIT returns and are released only after terminal DONE and drop
glue. The final lane reclaims the shared allocation. Resume blocks reload bounds
and offsets from the frame, so no entry-state SSA value is reused across a
suspension edge. Admission is based on exact HIR identities and repeat-safe
capture ownership; unsupported owners retain the single-coroutine fallback.
Borrowed views and non-Copy arrays stay on that fallback until backing lifetime
and exact-once element destruction can be proven. Generic iterator lane
batching additionally requires a semantic partition capability: sharing one
mutable `next()` cursor across lanes would race, while calling `iter()` once per
lane could repeat user-visible conversion effects.

This fallback is not limited to integer ranges. An inference-sealed custom
`Iterator` keeps its normalized source value in the coroutine frame, and a
custom `IntoIterator` keeps the converted iterator in a separate exact frame
field when its type or ABI differs from the source. `iter`, `next`, and
`Option<Item>` are selected by semantic identity rather than spelling. Mutable
receivers are reloaded after resume, and converted iterator drop glue runs
exactly once on exhaustion, `break`, return, or terminal cleanup. Re-entering
the same source loop reinitializes the persistent field and its ownership flag
without reusing stale state.

Ordered results require an explicit collection protocol: include an input
index in each result and let a single collector place it in the corresponding
slot. Launch order does not establish completion or arrival order. The
`ordered` modifier is reserved; use indexed results or channels for this
behavior.

## Channel `select`

`select` chooses among channel operations. A `default` case gives a
non-blocking path; without it the operation may wait. The order in which tasks
are spawned does not establish arrival order or the winning case.

Selection alone does not define shutdown. A single-value receive from a
closed, drained channel can produce the element type's zero value. An endless
loop can therefore confuse closure with data. Use the explicit
[receive and close contracts](channels.md) and the complete
[fan-in lifecycle](fan-in.md).

A timeout is an application protocol, not just an arbitrary `after
5.seconds()` clause copied from another language. Use the timer or context API
provided by the selected runtime/library and arrange cancellation and cleanup
for every contender. The previous `sync`, `sync/atomic`, Mutex, RwLock and
WaitGroup import examples were API sketches, not verified public packages;
this guide does not present them as copyable current Vex code.

## Synchronization and Shared State

Choose the smallest protocol that states who may change each value:

| Need | Design requirement |
| --- | --- |
| Work distribution | Bound the queue; define overflow/backpressure and shutdown. |
| Completion | Count actual terminal workers; notify exactly once on success and error. |
| Shared mutable state | Use a supported synchronization API or transfer mutation to one owning task. |
| Cancellation | Wake blocked senders and receivers; release resources after workers finish. |
| Reusable initialization | Define ownership, error propagation and whether failure can be retried. |

The runtime contains internal locks and atomics. Their presence does not expose
an application package or a stable set of memory-order defaults. When using a
supported atomic API, derive ordering from a concrete communication relation;
“relaxed is fastest” or “sequential consistency is safest” is not a correctness
argument for a compound algorithm.

Thread-local state belongs to an operating-system thread. A task that can
suspend or migrate must not use thread-local state as if it were task-local
state. Prefer explicit state ownership when that distinction matters.

## Concurrency Safety Contracts

`ConcurrentSafe` and `SuspendSafe` are compiler-recognized capabilities.
They complement storage and lifetime analysis; merely naming a capability
does not establish that every reference or capture is safe. `$Send` and `$Sync`
are not the Vex contract spellings. See [ownership at concurrency
boundaries](overview.md#ownership-at-concurrency-boundaries).

## Debugging Concurrency Issues

Use a small deterministic protocol test before stress or performance testing.
Record how many messages were accepted, which workers completed, and whether
closure was observed after draining. Apply a deadline to the test harness so
that a failed shutdown produces an actionable failure instead of an endless run.

### Thread Sanitizer

`vex compile --sanitize thread` selects sanitizer instrumentation where the
compiler, runtime libraries and target support it. Instrumented compilation is
not proof that all runtime code is instrumented or that no race exists. Check
the selected build and run the actual concurrent paths.

### Deadlock Detection

The compiler-selected cooperative-local runtime has no external wake source. It
therefore reports a deterministic deadlock when live tasks remain but its
runnable FIFO is empty. No environment flag is required.

The full M:N runtime cannot infer a general wait cycle from an empty runnable
set: tasks may be waiting legitimately on I/O, timers, channels, cancellation,
or a remote worker publication. Use bounded contexts/timeouts for application
protocols. General cross-provider wait-cycle diagnostics are not currently a
documented runtime guarantee.

## Performance Characteristics

| Operation                 | Latency               | Notes                                    |
| ------------------------- | --------------------- | ---------------------------------------- |
| `go { }` spawn            | target-dependent      | Measure with the bounded benchmark matrix |
| Channel send              | target-dependent      | Bounded MPMC ring; no direct handoff claim |
| Mutex lock                | target-dependent      | Contention and provider policy dominate  |
| Work stealing             | target-dependent      | Runs only on the scheduler's idle path   |

Vex keeps the common task cell to one 64-byte cache line and uses owner-local
queues plus bounded stealing. Competitive numbers must come from the
repository's bounded benchmark matrix on the target host; these rows are
architecture notes, not fixed nanosecond promises.

## Best Practices

1. Make ownership, errors, cancellation and completion visible in each protocol.
2. Use bounded queues where producers can outpace consumers.
3. Separate task completion from the arrival of an intermediate result.
4. Test empty/full queues and shutdown while work is pending.
5. Use `go` for independent work, including CPU work where appropriate; use
   `graph fn` for supported data-parallel computations rather than as a
   universal replacement for CPU tasks.
6. Measure scheduling and communication overhead on the deployment target.


## Related Pages

- [Concurrency Overview](overview.md) -- goroutines and M:N scheduler
- [Async](async.md) -- async/await basics
- [Channels](channels.md) -- message passing between tasks
- [Runtime Architecture](../../architecture/runtime-architecture.md) -- VUMM, event loop, channel internals
- [Operators Reference](../advanced/operators-reference.md) -- channel send/receive operators
