# Chapter 6: Transaction & Delta - The Time Machine v3

In Theus v3.0, the Transaction concept is handled by the **Rust Core**, ensuring absolute data integrity (ACID-like) with optimized performance.

## 1. Core Philosophy: Why we "Hold" the Context?
You might wonder: *"Why does Theus keep a reference to the entire context instead of just copying what I asked for?"*

The answer lies in **Safety** and **Atomicity**.
*   **Preventing Contract Cheating:** If we only copied the declared `outputs`, a malicious or buggy process could secretly modify a variable it *didn't* declare (Side Effect). By wrapping the entire context in a Transaction, Theus ensures that *all* writes go to a temporary "Shadow State". Only declared outputs are committed back; undeclared changes are discarded.
*   **Atomic Rollback:** To guarantee that a system state is either "All New" or "All Old", Theus creates a sandbox. If a process crashes halfway, the Sandbox is destroyed, and the original system remains untouched.

## 2. Snapshot Isolation Strategy (v3.0)
Theus v3.0 moves away from "In-Place Mutation" to a **Snapshot Isolation** model:

### 2.1. The Immutable Snapshot
When a Process starts, it receives a **Restricted View** (Snapshot) of the Context.
- **READ:** Fast, Lock-free access to data at `version=N`.
- **WRITE:** Strictly prohibited on the Snapshot object.

### 2.2. Copy-on-Write (CoW)
To modify data, you must:
1. **Copy:** Create a new instance (e.g., `new_list = list(old_list)`).
2. **Compute:** Modify the new instance.
3. **Return:** Send the new instance back to the Engine.

### 2.3. Atomic Commit (Smart CAS)
The Engine receives your Return Value and performs:
- **Validation:** 
    - **Global Version Check:** fast path if versions match.
    - **Smart Conflict Detection:** If versions mismatch, it checks if *your specific keys* were modified by someone else. If not, it **merges** safely.
- **Swap:** Replaces the pointer `Arc<State>` with the new state.
- **Rollback:** If Exception occurs before Return, the new data is simply discarded. The original State was never touched.

> [!IMPORTANT]
> **The `engine.edit()` Exception:** 
> When using the `engine.edit()` context manager, you perform mutation directly on a **SupervisorProxy**. This *looks* like In-Place Mutation, but it is actually a **Buffered Record**. 
> - **Rollback SAFE:** If an exception occurs within the `with engine.edit()` block, the specific buffer is discarded and the system state is untouched.
> - **Only Raw Mutation is Dangerous:** Modifying a static variable or a global object NOT managed by the Engine is where Rollback fails.


## 3. Transaction Context Manager (v3.0)

```python
with engine.transaction() as tx:
    # Operations here are transactional
    tx.update(data={'counter': 10})
    
# Auto-commit on success, auto-rollback on exception
```

## 4. Compare-and-Swap Pattern (v3.0)

For optimistic concurrency control, Theus v3 supports **Smart CAS**:

```python
# Get current version
current_version = engine.state.version

# Perform optimistic update
try:
    engine.compare_and_swap(
        expected_version=current_version,
        data={'counter': new_value}
    )
except VersionMismatchError:
    # Only raised if 'counter' ITSELF was modified by another process.
    # If someone else modified 'unrelated_key', this succeeds (Merge).
    pass
```

> [!NOTE]
> **Field-Level Conflict Detection:**
> Theus tracks modifications at the field level (e.g., `domain.user.name`). Two processes can update different fields of the same domain object concurrently without conflict.

## 5. The Audit Log: Transient & Ephemeral
A critical design choice in Theus is that **Transaction Logs are Ephemeral**.
*   **While Running:** The log exists to track every change.
*   **After Success:** The log is **discarded** (Dropped).
*   **Why?** Storing full data history (especially for AI Tensors) would explode memory instantly. Theus is designed to be "Audit-Aware" (counting violations) rather than a full "Time-Travel Database" for storage.

---
**Advanced Sabotage Exercise:**
4. Check if `sig_restock_needed` reverts to `False` and item disappears from list after crash.

---

## 6. Interoperability & Serialization (DX)

Theus v3.0 `SupervisorProxy` implements the **Mapping Protocol** (`collections.abc.Mapping`), allowing it to behave like a read-only dictionary in most contexts (Pydantic, Jinja2, etc.).

### 6.1. Using with Pydantic
Theus Proxies work natively with Pydantic v2 if you enable `from_attributes` (ORM Mode).

```python
from pydantic import BaseModel, ConfigDict

class UserSchema(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: int
    name: str

# Works directly with Proxy!
user_data = UserSchema.model_validate(ctx.domain.user)
```

### 6.2. JSON Serialization
The standard `json.dumps()` library does not support custom Mappings by default. 

**Recommended:** Use the `TheusEncoder` for seamless integration.

```python
import json
from theus import TheusEncoder

# ✅ Perfect: Uses IDIOMATIC custom encoder
json.dumps(ctx.domain.user, cls=TheusEncoder)

# ✅ Alternative: Cast to dict (Shallow)
json.dumps(dict(ctx.domain.user))
```

### 6.3. FastAPI Integration
When returning data from an API endpoint, FastAPI/Starlette will automatically handle the Mapping protocol in many cases. If you encounter issues, simply cast to dict before returning.

```python
@app.get("/user")
def get_user():
    # ... inside process ...
    return dict(ctx.domain.user)
```
