# Theus V3 Feedback: Transaction Update Overwrite Issue

**Date:** 2026-01-27
**Component:** `TheusEngine.transaction().update()`
**Severity:** High (Potential Data Loss)
**Version Tested:** Theus v3.0.2 (as detected in environment)

## 1. Executive Summary

During the implementation of a FastAPI backend using Theus V3, we encountered a critical data loss issue when using `tx.update()` to modify nested fields within the Domain Context.

Specifically, when updating a nested object (e.g., `domain.order`), the sibling fields (e.g., `domain.payment`) were **silently deleted/overwritten**, leading to data corruption and runtime errors (`AttributeError`) in subsequent processes.

This behavior seems to contradict the "Smart CAS / Partial Merge" capabilities described in the advanced documentation (v3.1+), or suggests that `tx.update()` behaves differently from internal process updates.

## 2. Reproduction Scenario

### Context Structure
```python
class DemoDomain(BaseModel):
    order: OrderDomain      # Contains inventory, orders list...
    payment: PaymentDomain  # Contains balance...
```

### Initial State
```json
{
  "domain": {
    "order": { "inventory": {...}, "orders": [] },
    "payment": { "balance": 0.0 }
  }
}
```

### The Operation
Inside an API endpoint, we attempted to inject a new order request into the context:

```python
# Intention: Update ONLY domain.order.order_request
with engine.transaction() as tx:
    tx.update(data={
        "domain": {
            "order": {
                "order_request": {...new_request...}
            }
        }
    })
```

### The Result
After the operation, the state became:
```json
{
  "domain": {
    "order": { "order_request": {...} }, 
    // "payment": MISSING! (Deleted)
    // "order.inventory": MISSING! (Deleted)
  }
}
```
The `payment` domain was completely removed. The `order` domain was replaced entirely by the dict provided in the update, losing all existing inventory data.

## 3. Analysis vs Documentation

### Documentation Claims
*   **08_CONFLICT_RESOLUTION_MECHANISMS.md:** Mentions "Smart Check (Field-Level v3.1)" that allows Partial Merges for unrelated fields.
*   **09_FFI_AND_ARCHITECTURE_REFERENCE.md:** "Unrelated updates are merged automatically."

### Observation
The `tx.update(data=...)` method appears to perform a **Deep Replacement** (Overwrite) at the key level provided, rather than a **Deep Merge**.

*   If `data={"domain": ...}` is passed, it treats the provided `domain` dict as the *new* value for the `domain` key, replacing the existing object.
*   It does *not* recursively traverse the Pydantic models or Dictionaries to merge leaf nodes.

This behavior is dangerous for large Domain Contexts where `tx.update` is used to modify a single sub-field.

## 4. Workaround Implemented

To resolve this, we implemented a manual **Read-Modify-Write** pattern within the transaction scope:

```python
with engine.transaction() as tx:
    # 1. Fetch current proxies
    domain_proxy = engine.state.domain
    
    # 2. Extract full state (to preserve sibling fields)
    order_data = domain_proxy.order.to_dict()
    payment_data = domain_proxy.payment.to_dict() # MUST fetch this to save it
    
    # 3. Modify
    order_data['order_request'] = req_payload
    
    # 4. Write back EVERYTHING
    tx.update(data={"domain": {
        "order": OrderDomain(**order_data),
        "payment": PaymentDomain(**payment_data)
    }})
```

This is verbose and inefficient (requires full serialization/deserialization of the domain).

## 5. Recommendations for Theus Team

1.  **Clarify `tx.update` Semantics:** Explicitly document whether `tx.update` supports Deep Merge or is strictly Key-Level Overwrite.
2.  **Implement Deep Merge:** Enhance `tx.update` to support recursive merging for Dictionary and Pydantic inputs.
    *   Example: `tx.update(data={"domain.order.order_request": ...})` (Dot notation support).
3.  **Safety Guard:** Raise a warning or error if `tx.update` replaces a Complex Object (like a Domain Model) with a sparse Dictionary, which often indicates unintended data loss.
4.  **Targeted Update API:** Provide a method to update specific paths without passing the root structure.
    *   `tx.update_path("domain.order.order_request", value)`

---
*Report generated by AI Assistant during integration testing of `my-theus-app`.*
