> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apich.org/llms.txt
> Use this file to discover all available pages before exploring further.

# dtact

> Non-preemptive, stackful coroutine runtime with a lock-free ContextPool, P2P mesh deflection scheduling, and C/C++ FFI.

**dtact** is a non-preemptive, stackful coroutine (fiber) runtime built for hardware-level control, heterogeneous orchestration, and zero-copy C/C++ interoperability.

> [!NOTE]
>
> This page is an architectural overview. For full Rust API documentation, live crate versions, and C header details, visit [docs.rs/dtact](https://docs.rs/dtact) and [apich.org/projects/dtact](https://apich.org/projects/dtact/).

> [card] [Full API Reference](https://docs.rs/dtact)
>
> Generated rustdoc for `dtact`, `dtact-macros`, and `dtact-util` on docs.rs.

> [card] [Project Homepage](https://apich.org/projects/dtact/)
>
> Release metadata, benchmarks, and Open Collective budget on apich.org.

> [card] [GitHub Repository](https://github.com/Apich-Organization/dtact)
>
> Source code, C/C++ headers (`dtact.h`, `dtact.hpp`), and Criterion benchmarks.

> [card] [Zenodo DOI](https://doi.org/10.5281/zenodo.20002105)
>
> Persistent academic citation (`10.5281/zenodo.20002105`) and Software Heritage archive.

## Architecture & Core Design

Instead of compiling async functions into stackless state machines, `dtact` assigns each task its own stack from a pre-allocated, lock-free `ContextPool` arena and switches execution with hand-written assembly switchers for `x86_64`, `AArch64`, and `RISC-V`.

```mermaid theme={null}
flowchart TB
    Spawn["spawn / #[task] (7 spawn-time knobs)"] --> Pool["ContextPool (pre-allocated lock-free arena)"]
    Pool -->|"zero-copy future on fiber stack"| WorkerA["Worker A (local mailbox)"]
    WorkerA -->|"mailbox full -> deflect"| Mesh["P2P Mesh Topology (SameCore / SameCCX / SameNUMA / Any)"]
    Mesh --> WorkerB["Worker B (neighbouring cache domain)"]
    WorkerA --> Switcher["Assembly Context Switcher (x86_64 · AArch64 · RISC-V)"]
    Switcher --> Util["dtact-util (native io_uring/IOCP/kqueue · tokio · sync)"]
```

### Key Architectural Trade-offs

* **Stackful vs. stackless**: A yield in `dtact` performs a full CPU register context switch, which is heavier than polling a stackless state machine. In return, suspended fibers preserve their C stack, allowing C and C++ code (`dtact.h` / `dtact.hpp`) to launch, yield, and await fibers natively.
* **P2P mesh deflection**: Instead of contending on a single global work-stealing queue, workers pull only from their own bounded lock-free mailbox and deflect overflow to neighbouring cores within the configured cache or NUMA domain.
* **Best-fit workloads**: Ideal for Bag-of-Tasks (BoT) workloads at moderate-to-high load, parallel batch computation, and mixed Rust/C++ orchestration.

## Repository Structure

| Crate / Path | Role |
| - | - |
| `src/dta_scheduler.rs` | Decentralized P2P mesh scheduler, bounded lock-free mailboxes, and deflection logic |
| `src/context_switch.rs` | Hand-written assembly switchers (`x86_64`, `AArch64`, `RISC-V`, float/no-float, cross-thread) |
| `src/memory_management.rs` | Lock-free `ContextPool` arena, zero-copy future placement, and stack canary guards |
| `src/future_bridge.rs` & `src/c_ffi.rs` | Rust `Future` polling bridge and `cbindgen` C/C++ FFI (`dtact.h`, `dtact.hpp`) |
| `dtact-macros/` | `#[dtact_init]`, `#[task]`, and `#[export_fiber]` procedural macros |
| `dtact-util/` | Async I/O (`io`, `fs`, `process`, `signal`, `stream`, `timer`) with `native`, `tokio`, and `sync` backends |
| `benches/` & `fuzz/` & `tests/` | 7 Criterion benchmark suites, libFuzzer targets, Loom, and proptest concurrency tests |

## Spawn-Time Knobs & `dtact-util` Backends

Every fiber spawned via `#[task(...)]`, `ClosureSpawnOptions`, or `dtact_spawn_options_t` applies seven runtime knobs:

| Knob | Values / Purpose |
| - | - |
| `priority` | `Low`, `Normal`, `High`, `Critical` (never deflected, front-of-queue, parks instead of migrating) |
| `kind` | `Compute` through `IO` — seeds the adaptive spin budget in `wait_pinned` |
| `affinity` | `SameCore`, `SameCCX`, `SameNUMA`, `Any` — confines deflection neighbourhood |
| `topology_mode` | `P2PMesh`, `Global`, `Pinned` — per-fiber override of runtime topology |
| `stack` | Granted stack size carved from the slot's reserved region |
| `safety` | `Safety0` (none), `Safety1` (canary at exit), `Safety2` (canary on every suspension) |
| `name` | Diagnostic fiber label exposed via `dtact::fiber_info(handle)` |

`dtact-util` decouples I/O from the scheduler behind three Cargo feature modes: **`native`** (default, `io_uring` / IOCP / `kqueue`), **`tokio`** (wrapper for workloads dominated by short-lived connection churn), and **`sync`** (backend-agnostic utility primitives), plus a blocking C ABI (`dtact_util.h`).

## Benchmarks

![dtact spawn and join benchmark comparison against Tokio](https://mintcdn.com/apich-organization/-dwr41T2xn7sv5RT/images/bench/spawn_join.png?fit=max\&auto=format\&n=-dwr41T2xn7sv5RT\&q=85\&s=a0ee47000d342d36bea5a54a017a309c)

Criterion spawn + join median per-task cost (nanoseconds) and Tokio-to-dtact ratio on 4-core x86\_64.

![dtact hot-core deflection benchmark chart](https://mintcdn.com/apich-organization/-dwr41T2xn7sv5RT/images/bench/work_deflection.png?fit=max\&auto=format\&n=-dwr41T2xn7sv5RT\&q=85\&s=c1bb98d070f6327be8abd897de58a785)

Hot-core work-deflection behaviour across task batch sizes.

## Quick Example

```rust Rust (dtact) theme={null}
use dtact::{dtact_await, dtact_init, spawn, task, yield_now};

#[task(priority = "Normal", kind = "Compute", stack = "256K")]
async fn worker(id: u32) {
    for i in 0..3 {
        println!("[Fiber {id}] step {i}");
        yield_now().await;
    }
}

#[dtact_init(workers = 4, stack = "256K", capacity = "1024")]
fn main() {
    let handles: Vec<_> = (0..5).map(|i| spawn(worker(i))).collect();
    for h in handles {
        dtact_await(h);
    }
}
```

```c C FFI (dtact.h) theme={null}
#include "dtact.h"

void worker_fiber(void* arg) {
    int id = *(int*)arg;
    printf("[Fiber %d] running\n", id);
    dtact_free_arg(arg);
}

int main(void) {
    dtact_config_t cfg = dtact_default_config();
    cfg.mWorkers = 4;
    cfg.mFiberCapacity = 1024;
    cfg.mStackSize = 256 * 1024;
    void* rt = dtact_init(&cfg);
    dtact_fiber_launch(master_fiber, NULL);
    dtact_run(rt);
    return 0;
}
```


## Related topics

- [Stack Architecture & Project Map](https://docs.apich.org/guides/architecture.md)
- [Quickstart](https://docs.apich.org/quickstart.md)
- [Apich Organization Documentation](https://docs.apich.org/index.md)
- [Security Policy & Release Standards](https://docs.apich.org/guides/security-and-releases.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.