Skip to content

RFC-020: Dynamic Modules and FFI Integration ​

⚠️ Deprecated: This document has been deprecated, and its contents have been merged into RFC-026: FFI Core Mechanism.

References:

Abstract ​

Building on RFC-001, RFC-008, and RFC-018, this document further refines and extends YaoXiang's concurrency model to address practical scenarios involving dynamic module loading, the foreign function interface (FFI), and more fine-grained scheduling optimizations. The core designs include:

  1. Dynamic Module Metadata Contract: Provides compile-time dependency descriptions for dynamic libraries written in the same language, allowing the main program to construct the DAG statically while preserving transparent concurrency.
  2. FFI Scheduling Semantics: External functions default to @block nodes in the DAG and can participate in parallel scheduling through annotations. See RFC-021 for the FFI toolchain.
  3. Call-Context-Based Optimization: Replaces static-threshold fallback with intelligent compiler decisions based on a function's actual role in the DAG, such as its number of consumers and side effects, to determine whether it should be inlined or scheduled as an independent node.
  4. Control Flow and DAG Merging Mechanism: Naturally integrates dynamic structures such as if and loop into the dataflow graph through Phi nodes and dynamic expansion.
  5. Runtime Scheduler Memory and Performance Optimizations: Defines low-overhead abstractions for node lifecycle management, arena allocation, lock-free queues, and related mechanisms.

This document aims to refine the language specification so that YaoXiang's concurrency model can support static whole-program analysis while flexibly handling dynamic behavior and external interactions, all while maintaining high performance and a good developer experience.

Motivation ​

Shortcomings of the Existing Design ​

RFC-001, RFC-008, and RFC-018 established an elegant transparent concurrency model, but gaps remain when addressing real-world requirements:

  • Dynamic Modules: When a program supports plugins or dynamically linked libraries, the main program cannot determine the call relationships and dependencies within a module at compile time, preventing construction of the global DAG.
  • FFI Calls: External functions, such as those in C libraries, are entirely opaque. Their internals may contain concurrency, blocking operations, or side effects, so treating them as ordinary nodes would compromise concurrency safety.
  • Scheduling Overhead for Small Functions: The “L1 automatic fallback” proposed in RFC-001 uses a static threshold (instruction count <50). This implicit rule makes behavior difficult for developers to predict and cannot adapt to complex call contexts.
  • Integration of Control Flow and the DAG: The representation of dynamic structures such as if and loop in the DAG remains unclear and may affect the accuracy of dependency analysis.
  • Runtime Overhead Control: As the number of DAG nodes grows, scheduler memory management and performance optimization require explicit designs to avoid becoming bottlenecks.

Goals ​

  • Preserve the core philosophy of transparent concurrency while providing clear, safe, and progressive support for dynamic modules and FFI.
  • Shift scheduling optimization from an “implicit global rule” to “intelligent context-based decisions,” improving predictability and performance.
  • Refine the DAG's representation of dynamic control flow so that all program structures can integrate naturally into the dataflow model.
  • Define scheduler memory-management and performance-optimization strategies that provide low-overhead abstractions.

Proposal ​

1. Dynamic Module Metadata Contract ​

1.1 Contract Contents ​

Every dynamic library compiled with YaoXiang (.yxo or a platform-specific dynamic library) must include a metadata description file (.yxmeta) containing:

  • Exported Function List: The complete type signature of each function, including parameters, return values, and resource tags.
  • Side-Effect Markers: Compiler-inferred @pure / @io markers, which developers may also override explicitly.
  • Resource Dependencies: Whether each parameter is a resource type, such as File, and whether the return value contains a new resource.
  • Call Graph Summary (optional): IDs of other exported functions that the function may call, used to detect cyclic dependencies across modules.
  • Ownership Information: Parameter ownership semantics, such as borrow or move, and ownership of return values.
  • Concurrency Safety: Automatically inferred results indicating whether Send / Sync requirements are satisfied.

The metadata format may be binary or structured text, such as MessagePack, to ensure efficient parsing.

1.2 Compile-Time Processing ​

When the main program encounters a call to a dynamic module function during compilation:

  1. Read the corresponding module's .yxmeta file.
  2. Create a placeholder node in the global DAG and record its input/output dependencies, side-effect markers, and other metadata.
  3. The placeholder node participates in dependency analysis like an ordinary node, allowing the scheduler to plan its execution order ahead of time.

1.3 Runtime Binding ​

When a dynamic module is loaded:

  • The runtime verifies that the actual function signature matches the metadata to prevent version mismatches.
  • The placeholder nodes are bound to the actual function pointers.

Subgraph Scheduling Semantics: If a dynamic module contains an independent sub-DAG—for example, when the module itself contains concurrent logic—the subgraph executes as an independent scheduling unit. Its boundary is defined by the module's exported functions: when an exported function is called, the subgraph begins executing as a whole and continues until the function returns. Scheduling of nodes within the subgraph is handled by the subgraph's own scheduler; the module may continue to use the standard scheduler. However, interaction between the subgraph and the main DAG is limited to input/output data flow. The placeholder node in the main DAG only tracks the start and end of the subgraph and does not participate in its internal scheduling. This design preserves module encapsulation while keeping the main DAG statically complete.

1.4 Safety Guarantees ​

  • If a dynamic module violates the contract—for example, claiming @pure while modifying global state—the consequences are the developer's responsibility, similar to an unsafe FFI boundary. Because the module uses the same language, safety could be enhanced through runtime checks, such as memory isolation, but this would add overhead.
  • Cross-module cyclic dependencies: If module A calls B and B calls A, and the metadata declares these call relationships, the compiler can detect and report an error. If they are not declared, a deadlock may occur at runtime, which the scheduler detects and panics on.

2. FFI Scheduling Semantics in the DAG ​

Full FFI toolchain support, including dynamic library loading, binding generation, type conversion, and memory ownership, is defined by RFC-021. This section describes only the behavior of FFI calls during DAG scheduling.

2.1 Default Scheduling Behavior ​

External functions declared through native(“symbol”) default to @block nodes in the DAG:

  • They do not participate in parallel DAG scheduling and execute synchronously on the current thread.
  • The scheduler does not interfere with any concurrency internal to them while they execute.
  • Their return values are available, but the call itself does not produce a dependency edge.

2.2 Optional Concurrency Annotations ​

Developers can use annotations to integrate FFI calls into DAG scheduling. See RFC-021 §2.2 for details:

  • @pure: Treated as an ordinary DAG node and able to execute in parallel with nodes that have no dependencies.
  • @io: Participates in resource dependency analysis, with multiple calls to the same resource automatically serialized.

2.3 Impact on the Scheduler ​

FFI nodes use the same TaskNode structure as ordinary nodes. The only difference is that their effect marker is set to Block. When the scheduler encounters a Block node, it skips parallel scheduling and executes the node synchronously.

3. Call-Context-Based Optimization ​

The static threshold used by RFC-001's “L1 automatic fallback” is replaced by intelligent compiler decisions based on the actual context of each call site in the DAG.

3.1 Optimization Decision Criteria ​

The compiler analyzes each function call node:

  • Number of Consumers: How many downstream nodes use the node's result. A value of 1 makes the node an inline candidate. A value greater than 1 requires it to remain an independent node so that the result can be shared.
  • Side Effects: A node with @io side effects must remain an independent node to preserve ordering.
  • Computation Estimate: Heuristics such as instruction count may still be used, but they are not hard thresholds and are considered only when evaluating the benefit of inlining.
  • Resource Dependencies: If a node involves a resource variable, such as File, and that resource is passed between upstream and downstream nodes, inlining may break the dependency chain and must be handled carefully.

3.2 Inlining Operation ​

If the decision is to inline:

  • Embed the node's computation logic directly into the code of its sole downstream node.
  • Remove the node from the DAG, making its inputs direct inputs of the downstream node.
  • During final code generation, an inlined function does not produce an independent scheduling unit.

3.3 Inlining Restrictions ​

  • Recursive functions and calls within loops are generally not inlined, preventing unbounded expansion.
  • Functions crossing module boundaries, including dynamic modules and FFI, are not inlined.
  • Developers can prohibit inlining with the @noinline annotation or hint that the compiler should attempt to inline with @forceinline.

3.4 Observability ​

The compiler should generate an optimization report, which can be enabled with --emit-optimization-report, containing the following information:

  • Each Inline Site: The name of the inlined function, its call site, and the reason for inlining, such as “single consumer and pure function.”
  • Reasons for Retaining an Independent Node: For example, “multiple consumers,” “contains side effects,” or “cross-module call.”
  • Decision Statistics: The total number of inlined functions and retained nodes, helping developers evaluate the optimization's effectiveness.

The report may be output as text or JSON to facilitate parsing by tools.

4. Merging Control Flow with the DAG ​

4.1 Conditional Branches (if) ​

Phi nodes, inspired by SSA form, are introduced to represent branch merge points:

  • At compile time, each if expression produces:
    • Two branch sub-DAGs, corresponding to the then and else branches respectively.
    • A Phi node whose inputs include the condition variable and the outputs of both branches.
  • Phi node semantics: Once the condition variable is ready, the Phi node selects the output of the corresponding branch according to the condition value and uses it as its own output.
  • At runtime, the Phi node depends on the condition variable. Once the condition is ready, it dynamically adds itself to the selected branch's downstream list and waits for that branch's result.

Example DAG:

        cond
       /    \
  then DAG  else DAG
       \    /
        Phi
         |
      后续节点

4.2 Loops (loop/while) ​

A loop is treated as a sub-DAG with feedback edges and is expanded on demand at runtime:

  • At compile time, the compiler identifies the loop body and constructs a loop template containing:
    • The condition node.
    • The loop-body sub-DAG.
    • State variables passed between iterations.
  • At runtime, when the loop result is needed—for example, when an accumulated value is used after the loop—the scheduler begins dynamically expanding iterations:
    1. Schedule the condition node for the first time. If it evaluates to true, instantiate the sub-DAG for the first iteration, with inputs including the initial state and external variables.
    2. After the iteration completes, produce a new state and schedule the condition node again, now depending on the new state, to determine whether execution should continue.
    3. Repeat until the condition becomes false. The output of the final iteration is the loop result.

Complex Example: The Loop Condition Depends on an Update Inside the Loop Body

yaoxiang
let mut x = 0
while x < 10 {
    x = compute(x)  // x is updated inside the loop
}

In this pattern, the condition node x < 10 depends on the x updated after each iteration. The DAG is represented as follows:

  • The loop template contains the state variable x, whose initial value is 0.
  • During each iteration, the condition node is executed first, depending on the current x. If it evaluates to true, x = compute(x) is executed to produce a new x, after which execution returns to the condition node.
  • At runtime, the loop is dynamically expanded according to this process until the condition becomes false.

Dependencies between iterations naturally form a dataflow through state variables. Iterations with dependencies are automatically serialized, while iterations without dependencies can execute in parallel, such as with map.

4.3 Special Handling of Infinite Loops ​

A single infinite loop executes synchronously directly within the main DAG, with no scheduling overhead. Multiple infinite loops run as background DAGs, concurrently time-sliced by the scheduler.

5. Runtime Scheduler Memory and Performance Optimizations ​

5.1 Node Lifecycle Management ​

  • Each node maintains a reference count backed by an atomic variable, representing the number of consumers that depend on its result.
  • After a node finishes executing and passes its result to all downstream nodes, its reference count reaches zero and its memory can be released.
  • The result value itself also uses reference counting (Arc<T>), but this can be optimized: if the result is used by only one consumer, ownership can be moved directly, avoiding reference-counting overhead.

5.2 Arena Memory Allocation ​

For large numbers of dynamically generated, short-lived nodes, such as loop iterations, an arena allocator is used:

  • Allocate a memory region for each loop expansion.
  • Allocate nodes within the region contiguously and release them as a whole, reducing fragmentation and deallocation overhead.
  • Reclaim all node memory at once when the region ends.

5.3 Lock-Free Data Structures ​

  • Dependency counter: Use AtomicUsize and decrement it atomically through fetch_sub.
  • Ready queue: Use a Chase-Lev deque, consisting of a per-thread local queue and work stealing, to reduce lock contention.
  • Downstream lists: Make them read-only after creation to avoid concurrent modification.

5.4 Adaptive Scheduling ​

  • If the system contains only one infinite loop, execute it synchronously for zero scheduling overhead.
  • Dynamically adjust the degree of parallelism based on task granularity and system load, for example by adjusting the number of worker threads according to queue length.

5.5 Low-Overhead Abstraction Principle ​

All scheduling overhead should be proportional to the number of tasks, with the additional overhead of each task—creation, enqueueing, and dependency handling—kept to tens of nanoseconds. For extremely fine-grained tasks, inline optimization, as described in Section 3, avoids scheduling overhead.

Detailed Design ​

6.1 Dynamic Module Metadata Format (Draft) ​

rust
// Metadata file structure (simplified)
struct Metadata {
    version: u32,
    functions: Vec<FuncMeta>,
}

struct FuncMeta {
    name: String,
    signature: TypeSignature,
    effects: EffectTag,      // Pure | IO | Block
    resource_params: Vec<usize>, // List of parameter indices indicating which parameters are resource types
    calls: Vec<String>,       // Names of other exported functions called (optional)
    ownership: OwnershipInfo,
    send_sync: SendSync,      // Whether Send/Sync requirements are satisfied
}

6.2 Core Scheduler Data Structures ​

rust
struct TaskNode {
    id: TaskId,
    deps: Vec<TaskId>,                // Upstream dependencies
    remaining_deps: AtomicUsize,
    inputs: Vec<Option<Value>>,
    result: Option<Value>,
    func: Executable,
    downstream: Vec<TaskId>,           // Downstream nodes (read-only after creation)
    effect: EffectTag,
    arena_id: Option<ArenaId>,         // Owning arena (optional)
}

struct Scheduler {
    ready_queues: PerThreadQueue<TaskId>, // Per-thread local queue
    global_work_stealer: WorkStealer,
    arenas: ArenaAllocator,               // Arena allocator
}

6.3 Context-Based Optimization Analysis ​

The compiler performs the following steps at the MIR layer:

  1. Construct the global call graph and data dependency graph.
  2. For each function call node, calculate its out-degree, or number of consumers.
  3. If the out-degree is 1, the function is side-effect-free (@pure), and it is not recursive, mark it as an “inline candidate.”
  4. Combine heuristics, such as instruction count, to evaluate the benefit of inlining and decide whether to inline it.
  5. When inlining, embed the call node's code into its downstream node and update the dependency relationships.

6.4 Control Flow Node Representation ​

rust
enum NodeKind {
    Normal(FuncId),
    Phi { cond: TaskId, then_branch: TaskId, else_branch: TaskId },
    LoopTemplate { cond: FuncId, body: FuncId, state_var: VarId },
    // ...
}

During runtime dynamic expansion, LoopTemplate generates a sequence of Normal node instances.

Trade-offs ​

Advantages ​

  • Safe Integration of Dynamic Modules: The metadata contract allows dynamic libraries to share the concurrency model seamlessly with the main program while preserving the integrity of the static DAG.
  • Progressive FFI Integration: Developers can gradually annotate external functions, transitioning from safe fallback to efficient concurrent execution.
  • Predictable Optimization: Context-based decisions replace implicit thresholds, making behavior transparent and allowing developers to understand optimizations through tools.
  • Natural Control Flow Integration: Phi nodes and dynamic expansion allow the DAG to represent all program structures without requiring special syntax.
  • Scalable Performance: Designs such as arena allocation and lock-free queues ensure that the scheduler can handle large-scale concurrency.

Disadvantages ​

  • The Metadata Contract Increases Compilation Complexity: Dynamic libraries require metadata generation and parsing, so the toolchain must support both.
  • FFI Annotations Depend on Developer Correctness: Incorrect annotations may cause data races, which must be mitigated through documentation and tooling.
  • Context Optimization Analysis Takes Time: Global analysis may increase compilation time, although incremental compilation can mitigate this.
  • Dynamic Expansion Adds Runtime Overhead: Loop expansion requires dynamically creating nodes, although arena allocation can reduce this cost.

Implementation Strategy ​

Phase Breakdown (with Suggested Priorities) ​

Implementation priority recommendation: The initial implementation need not be perfect. A simple approach may first be adopted to get the system running, followed by incremental optimization. For example:

  • Reference counting can directly use Arc.
  • A mature library can be used for the lock-free queue, such as the deque in crossbeam.
  • Arena allocation can initially use a simple bump allocator and be optimized later.

Phase 1: Basic Support (v0.7) ​

  • [ ] Make FFI default to @block.
  • [ ] Add @pure and @io annotations for FFI.
  • [ ] Implement resource wrapper types, such as File, and their basic methods.

Phase 2: Dynamic Module Metadata (v0.8) ​

  • [ ] Design the metadata format and modify the compiler to generate .yxmeta files for dynamic libraries.
  • [ ] Read metadata at main-program compile time and create placeholder nodes.
  • [ ] Implement the runtime binding mechanism.

Phase 3: Context Optimization (v0.9) ​

  • [ ] Implement call graph analysis and calculate node out-degrees.
  • [ ] Add inline decision-making and code generation support.
  • [ ] Implement optimization report output, including inline sites and reasons.

Phase 4: Control Flow DAG Integration (v0.10) ​

  • [ ] Implement Phi nodes and the compile-time representation of conditional branches.
  • [ ] Implement loop templates and the runtime for dynamic expansion.
  • [ ] Complete background scheduling for infinite loops.

Phase 5: Performance Optimization (v1.0) ​

  • [ ] Implement the arena allocator.
  • [ ] Optimize lock-free queues and work stealing.
  • [ ] Perform benchmarking and tuning.

Relationship to Other RFCs ​

  • RFC-001: Extends side-effect handling and concurrency layers, replacing automatic fallback with context-based optimization.
  • RFC-008: Adds runtime support for dynamic modules and FFI while preserving the scheduler-decoupling design.
  • RFC-018: Elaborates DAG construction and scheduler implementation, adding Phi nodes and dynamic expansion.

Appendix: Design Decision Record ​

DecisionDecisionDateAuthor
Dynamic modules provide a metadata contractAdopt metadata files and runtime binding2026-03-14Chenxu
FFI defaults to @blockYes; developers can add annotations incrementally2026-03-14Chenxu
Context optimization replaces static thresholdsIntelligent decisions based on out-degree, side effects, and other factors2026-03-14Chenxu
Introduce Phi nodes for conditional branchesDraw on SSA and dynamically select a branch2026-03-14Chenxu
Dynamic loop expansionInstantiate iterations on demand, supporting dependency serialization2026-03-14Chenxu
Use arena allocation for short-lived nodesImprove memory efficiency and cache locality2026-03-14Chenxu

References ​