# Parallel block execution (Block-STM)

Real Ethereum blocks contain hundreds of transactions, most of which touch
disjoint accounts and storage slots. Guillotine includes an opt-in,
**deterministic Block-STM parallel block executor** (`src/block/`) exposed
across Zig (`evm.block`), C ABI v4 (`guillotine_execute_block_parallel`), and
TypeScript (`evm.executeBlockParallel`).

For every thread count (`1`, `2`, `4`, `8`, …, `256`), Block-STM produces the
**exact same per-transaction receipts, logs, gas used, and post-state MPT root**
as executing the block serially in index order.

## How it works

```text
WorkerPool.init(allocator, io, threads)          once per node / replay
  for each block:
    recoverWithPool(pool, chain_id, tuples, out) parallel EIP-7702 ecrecover
    runWithPool(pool, base_db, coinbase, receipts, ctx)
      ├── seed      park txs whose ctx.hint(i) names a lower conflicting tx
      ├── dispatch  workers loop: execute -> publish -> validate
      │               • value-based read-set validation
      │               • quiet-write suppression (e.g. reentrancy guards)
      │               • ESTIMATE markers + early abort on conflict
      │               • deferred coinbase tips (zero false coinbase contention)
      └── install   serial commit in index order under one Database snapshot
pool.deinit()
```

Key design properties verified in `src/block/`:

* **Zero virtual dispatch (`SpeculativeDb`):** Each worker runs a comptime-specialized
  `Evm(.{ .DatabaseType = SpeculativeDb, .track_state_dump = false })`. Every
  account, storage, code, and transient read records into the incarnation's
  `ReadSet`; writes stay in a local overlay until publication.
* **Persistent `WorkerPool` (`src/block/worker_pool.zig`):** Worker threads
  start once, keep warm `Evm` instances (`DispatchCache`, `FrameStackPool`,
  `FrameMemoryPool`) and multi-version tables across blocks, and park on a futex
  between jobs.
* **Deferred coinbase rewards:** Priority-fee tips are accumulated via
  `SpeculativeDb.deferReward()` instead of mutating `block.coinbase` on every
  transaction, eliminating artificial contention across unrelated transactions.
  If a transaction actually reads `BALANCE(coinbase)` or sends from `coinbase`,
  it validates against the exact preceding tip prefix.
* **Validation by value & quiet writes:** A read stays valid if the visible
  value did not change after a lower transaction re-executed. A write that
  restores the exact value it read (such as a reentrancy lock toggled `1 → 2 → 1`)
  is installed at commit without invalidating higher readers.
* **Dependency hints (`hint(index)`):** Callers can optionally provide a
  lightweight hint naming the latest lower transaction likely to write a shared
  account (for example, the previous transaction from the same sender). A wrong
  hint only affects scheduling, never correctness.
* **Atomic failure semantics:** If any transaction fails admission or hits a
  host error and validates in serial order, `run` / `runWithPool` returns that
  error with `base_db` completely untouched.

## 1. Using Block-STM from Zig (`evm.block`)

`src/block/root.zig` exports `ParallelExecutor`, `WorkerPool`, `SpeculativeDb`,
and `MVMemory` under `@import("evm").block`.

### Single-block convenience (`ParallelExecutor.run`)

```zig
const std = @import("std");
const evm = @import("evm");
const primitives = @import("voltaire");

const Address = primitives.Address.Address;
const SpeculativeDb = evm.block.SpeculativeDb;
const ParallelExecutor = evm.block.ParallelExecutor;
const WorkerEvm = evm.Evm(.{
    .eips = .{ .hardfork = .OSAKA },
    .DatabaseType = SpeculativeDb,
    .track_state_dump = false,
});

const BlockContext = struct {
    txs: []const evm.tx_runner.Transaction,
    block_info: evm.BlockInfo,
    tx_context: evm.TransactionContext,

    pub fn initWorker(
        self: *@This(),
        allocator: std.mem.Allocator,
        db: *SpeculativeDb,
        _: usize,
    ) !WorkerEvm {
        return WorkerEvm.init(
            allocator,
            db,
            self.block_info,
            self.tx_context,
            0,
            primitives.ZERO_ADDRESS,
        );
    }

    pub fn execute(
        self: *@This(),
        vm: *WorkerEvm,
        db: *SpeculativeDb,
        index: u32,
    ) !ParallelExecutor.Receipt {
        vm.database = db;
        var res = try evm.tx_runner.executeTxWithOptions(
            WorkerEvm,
            vm.allocator,
            vm,
            self.txs[index],
            .{ .clone_output = false, .clone_logs = true },
        );
        defer res.deinit(vm.allocator);
        return ParallelExecutor.Receipt.withLogs(
            vm.allocator,
            res.success,
            res.gas_used,
            res.logs,
        );
    }
};

// Run a block across 8 worker threads:
var ctx = BlockContext{
    .txs = txs,
    .block_info = block_info,
    .tx_context = tx_context,
};
var receipts = try allocator.alloc(ParallelExecutor.Receipt, txs.len);
defer {
    for (receipts) |*r| r.deinit(allocator);
    allocator.free(receipts);
}

const stats = try ParallelExecutor.run(
    allocator,
    io,
    8,
    &base_db,
    block_info.coinbase.bytes,
    receipts,
    &ctx,
);
```

### Multi-block replay with a persistent `WorkerPool`

For multi-block replay (as in `bench/blocks/main.zig`), create a `WorkerPool`
once and reuse it across every block, optionally pre-recovering EIP-7702
authorizations in parallel first:

```zig
const pool = try evm.block.WorkerPool.init(allocator, io, 8);
defer pool.deinit();

for (blocks) |blk| {
    // 1. Optional parallel EIP-7702 authority recovery (zero allocation)
    ParallelExecutor.recoverWithPool(pool, blk.chain_id, blk.auth_tuples, blk.recovered_out);

    // 2. Execute and commit the block atomically into base_db
    const stats = try ParallelExecutor.runWithPool(
        pool,
        &base_db,
        blk.coinbase.bytes,
        blk.receipts,
        &ctx,
    );
    _ = stats;
}
```

### Optional `Context` hooks

`ParallelExecutor` detects optional declarations on your context type at compile
time:

* `hint(self: *const Context, index: u32) ?u32` — returns a lower transaction
  index that transaction `index` is likely to depend on.
* `beforeInstall(self: *Context, rows: anytype, stats: ParallelExecutor.Stats) !void` —
  runs after all transactions validate and **before** `base_db` is mutated (used
  by `src/evm_c_api_block.zig` to check cumulative block gas and build C results
  atomically).
* `onFailure(self: *Context, index: ?u32) void` — notified with the failing
  transaction index when execution or admission fails.

:::warning[Allocator choice matters on multi-core hosts]
Use `std.heap.c_allocator` (not `std.heap.smp_allocator`) for the `WorkerPool`
and worker `Evm` instances. `smp_allocator` calls `munmap` when freeing large
blocks, triggering process-wide TLB shootdowns across every worker core (which
made 8 threads slower than 1 thread during 100-block mainnet replay
development). See `src/block/README.md` and `bench/blocks/main.zig`.
:::

## 2. Using Block-STM from C (C ABI v4)

`libguillotine_ffi` exports `guillotine_execute_block_parallel` and
`guillotine_free_block_result` (`sdks/c/include/guillotine.h`,
`src/evm_c_api_block.zig`):

```c
#include "guillotine.h"

GuillotineBlockTx txs[2] = {0};
txs[0].params = tx0_params; // same TxParamsFFI fields as guillotine_execute_tx
txs[1].params = tx1_params;

/* Run on 4 worker threads (1..GUILLOTINE_MAX_BLOCK_THREADS = 256) */
GuillotineBlockResult *res = guillotine_execute_block_parallel(evm, txs, 2, 4);
if (res == NULL) {
    /* Failure names the offending transaction index; database is unchanged */
    fprintf(stderr, "block failed: %s\n", guillotine_get_last_error());
    return 1;
}

for (size_t i = 0; i < res->results_len; i++) {
    const GuillotineBlockTxResult *r = &res->results[i];
    printf("tx %zu: success=%d gas_used=%llu\n", i, r->success,
           (unsigned long long)r->gas_used);
}
guillotine_free_block_result(res);
```

Requirements and semantics for `guillotine_execute_block_parallel`:

* Requires an **Osaka** handle with in-memory state (`guillotine_evm_create`,
  `_create_mainnet`, `_create_tracing`, `_create_call_tracer`,
  `_create_with_options`, or `_create_with_fork(GUILLOTINE_FORK_OSAKA)`).
* Block-level v3 extensions on the handle (`blob_base_fee`, ancestor
  `block_hashes`) apply automatically. Transaction-level lists (`access_list`,
  `blob_hashes`, `max_fee_per_blob_gas`, `authorizations`) are passed per
  `GuillotineBlockTx`.
* Workers always run the default Tier 0 + Tier 1 interpreter and produce no
  per-opcode trace.
* If any transaction fails admission (nonce, balance, intrinsic gas, EIP-7825
  gas cap, fee caps, or cumulative block gas limit), the function returns `NULL`,
  `guillotine_get_last_error()` names the transaction index, and the database is
  left untouched.

## 3. Using Block-STM from TypeScript (`@tevm/guillotine`)

```ts
import { GuillotineEvm, U256 } from '@tevm/guillotine'

using evm = await GuillotineEvm.create({ number: 1n, baseFee: 10n, gasLimit: 30_000_000n })

const block = await evm.executeBlockParallel(
  [
    {
      from: alice,
      to: bob,
      nonce: 0n,
      gasLimit: 21_000n,
      value: U256.fromBigInt(1_000n),
      maxFeePerGas: U256.fromBigInt(20n),
      maxPriorityFeePerGas: U256.fromBigInt(2n),
    },
    {
      from: carol,
      to: contract,
      nonce: 0n,
      gasLimit: 100_000n,
      maxFeePerGas: U256.fromBigInt(20n),
      maxPriorityFeePerGas: U256.fromBigInt(2n),
    },
  ],
  { threads: 4 },
)

console.log(block.gasUsed, block.threads, block.executions, block.reexecutions)
for (const tx of block.results) {
  console.log(tx.success, tx.gasUsed, tx.output.toHex(), tx.logs.length)
}
```

## Measured 100-block mainnet performance

Measured on 100 contiguous Osaka mainnet blocks (`26,498,000`–`26,498,099`,
`29,560` transactions, `2.973B` gas, `29,560 / 29,560` exact receipts and
bit-exact post-state vs single-threaded execution):

| Host & threads | Cold (100 blocks) | Warm median (100 blocks) | Warm MGas/s | Warm tx/s |
| --- | ---: | ---: | ---: | ---: |
| Apple M3 Max — `1T` (serial baseline) | `1,137.68 ms` | `1,061.43 ms` | `2,801` | `27,849` |
| Apple M3 Max — `--threads 4` | `663.82 ms` | `620.46 ms` | `4,792` | `47,642` |
| Apple M3 Max — `--threads 8` | `597.48 ms` | `557.49 ms` | `5,333` | `53,023` |
| Linux x86\_64 (`EPYC 7443P`) — `1T` | `1,190.00 ms` | `1,107.71 ms` | `2,684` | `26,686` |
| Linux x86\_64 (`EPYC 7443P`) — `--threads 4` | `806.98 ms` | `747.01 ms` | `3,980` | `39,571` |
| Linux x86\_64 (`EPYC 7443P`) — `--threads 8` | `803.63 ms` | `707.91 ms` | `4,200` | `41,757` |

Single-threaded and multi-threaded figures are always reported separately. See
[Benchmarks and native JIT](/guides/benchmarks-and-jit) and
[`docs/performance/PARALLEL-BLOCK-EXECUTION.md`](https://github.com/evmts/guillotine/blob/main/docs/performance/PARALLEL-BLOCK-EXECUTION.md).
