# zwire-tx

> Rebaseable OptimisticLayer, zero-flicker atomic settle_with/try_settle, and read-set verified STM Draft in Rust.

**Rebaseable Optimistic Mutation Layers**, **RAII `OptimisticGuard`**, **zero-flicker atomic `settle()`**, and **STM read-verify `Draft`** transactions for [`zwire-core`](https://github.com/kjmin-dev/zwire/blob/main/rust/crates/zwire-core/README.md).

Part of the [`zwire`](https://github.com/kjmin-dev/zwire/blob/main/rust/crates/zwire/README.md) Rust workspace (native companion to [`@zwire/core/tx`](https://github.com/kjmin-dev/zwire#readme)).

## Why `zwire-tx`?

Unlike thread-contention STM retry crates or heavyweight CRDTs, `zwire-tx` solves **long-lived overlapping optimistic intents** in interactive apps, trading terminals, local-first sync clients, and multiplayer client-side prediction:

- **Automatic Rebase on Concurrent Authoritative Updates:** When a server/exchange push writes a new committed base value, every active optimistic intent layer automatically re-folds on top — **zero lost updates**.
- **Surgical Single-Layer `revert()`:** Failing intent #1 rolls back only intent #1 while preserving overlapping intent #2.
- **Zero-Flicker Atomic `try_settle()`:** Snapshots committed and effective state before stripping the layer, intercepts writes inside the settle closure, and atomically rolls back every affected atom on `Err` or panic without intermediate subscriber flicker.
- **RAII `OptimisticGuard`:** Automatically reverts on early `?` error returns unless explicitly settled.
- **Detached STM `Draft` (`commit_verified`):** Stage speculative reads and writes against either `Committed` or `Effective` state and fail with `DraftError::StmConflict` if any read atom or external source changed before commit.

## Quick Start

```rust
use zwire_core::Scope;
use zwire_tx::{Draft, OptimisticLayer};

let scope = Scope::new();
let likes = scope.atom(10i32);

let mut l1 = OptimisticLayer::new(&scope);
l1.update(likes, |n| n + 1); // UI: 11

let mut l2 = OptimisticLayer::new(&scope);
l2.update(likes, |n| n + 1); // UI: 12

// Concurrent authoritative push -> active intents auto-rebase!
scope.set(likes, 15);
assert_eq!(scope.get(likes), 17);

// First request fails -> surgical rollback preserves l2
l1.revert();
assert_eq!(scope.get(likes), 16);

// Second request succeeds -> atomic zero-flicker settle
l2.settle_with(|| scope.set(likes, 16));
assert_eq!(scope.get(likes), 16);

// Speculative STM draft with read-set verification
let mut draft = Draft::new(&scope);
let cur = draft.get(likes).unwrap();
draft.set(likes, cur + 5).unwrap();
draft.commit_verified().unwrap();
assert_eq!(scope.get(likes), 21);
```
