# Understanding TTL, Idempotency, and Compare-and-Swap Semantics in LoopX's `task_lease_v0` Contract

> Learn how LoopX's task_lease_v0 contract ensures safe, time-bounded, and conflict-free todo ownership with TTL, idempotency, and compare-and-swap.

- Repository: [huangruiteng/loopx](https://github.com/huangruiteng/loopx)
- Tags: internals
- Published: 2026-09-02

---

**The `task_lease_v0` contract in the LoopX control plane implements TTL-based expiration, idempotent acquisition retries, and compare-and-swap write-scope validation to guarantee safe, time-bounded, and conflict-free todo ownership.**

The `huangruiteng/loopx` repository provides a distributed task management system where agents acquire exclusive rights to work on specific todos. To prevent deadlocks, duplicate work, and conflicting writes, the `task_lease_v0` contract enforces strict semantics around **TTL (Time-to-Live)**, **idempotency**, and **compare-and-swap (CAS)** operations with write-scope validation. These mechanisms ensure that ownership automatically lapses, retries remain safe, and concurrent work only proceeds on disjoint file paths.

## TTL and Idempotency: Automatic Lease Expiration and Safe Retries

The `task_lease_v0` contract uses **TTL (Time-to-Live)** to prevent permanent lockouts. When an agent acquires a lease, it specifies `--ttl-seconds`, which sets an absolute expiration time for the ownership. If the holder fails to renew or release the lease before this deadline, the ownership automatically lapses, making the todo available for other agents.

**Idempotency** guarantees that network retries or duplicate commands do not create multiple leases. When acquiring a lease, the caller provides a unique `--idempotency-key`. According to the smoke test in [`examples/control_plane/task-lease-runtime-smoke.py`](https://github.com/huangruiteng/loopx/blob/main/examples/control_plane/task-lease-runtime-smoke.py), re-issuing the same `acquire` command with identical parameters—including the idempotency key—returns the existing lease rather than creating a new one (lines [62-82]).

```python

# Initial acquisition with TTL and idempotency key

result = cli(
    registry_path,
    "acquire",
    "--goal-id", GOAL_ID,
    "--todo-id", TODO_A,
    "--owner", "codex-main-control",
    "--idempotency-key", "turn-1",
    "--ttl-seconds", "120",
    "--write-scope", "loopx/**",
)
assert result["ok"] and result["acquired"]

# lease.version == 1, lease.acquire_ttl_seconds == 120

```

The test validates that the second call with the same `--idempotency-key "turn-1"` returns `idempotent["ok"] is True` and `idempotent["idempotent"] is True`, confirming that the **lease version remains unchanged** (still `1`) rather than incrementing.

## Compare-and-Swap Semantics with Write-Scope Validation

Beyond simple locking, the contract implements **compare-and-swap (CAS)** logic through **write-scope** validation. Each lease records a `write_scope`—a glob pattern defining which file paths the holder may modify (e.g., `loopx/**`). When another agent attempts to acquire a different todo, the contract compares the requested write-scope against existing active leases.

If the scopes overlap, the acquisition fails, protecting the original owner’s exclusive write rights. If the scopes are disjoint, the CAS operation succeeds, allowing parallel work. In [`examples/control_plane/task-lease-runtime-smoke.py`](https://github.com/huangruiteng/loopx/blob/main/examples/control_plane/task-lease-runtime-smoke.py) (lines [84-100]), the test demonstrates this by acquiring `TODO_B` with `--write-scope "docs/**"` after `TODO_A` was locked with `--write-scope "loopx/**"`. Because the scopes do not intersect, the second acquisition succeeds despite both leases being active.

```python

# Idempotent re-acquisition returns existing lease without version increment

result = cli(
    registry_path,
    "acquire",
    "--goal-id", GOAL_ID,
    "--todo-id", TODO_A,
    "--owner", "codex-main-control",
    "--idempotency-key", "turn-1",   # same key as before

    "--ttl-seconds", "120",
    "--write-scope", "loopx/**",
)
assert result["ok"] and result["idempotent"]

# lease.version unchanged (still 1)

# Acquire disjoint todo with non-overlapping write-scope (CAS succeeds)

result = cli(
    registry_path,
    "acquire",
    "--goal-id", GOAL_ID,
    "--todo-id", TODO_B,
    "--owner", "codex-side-bypass",
    "--idempotency-key", "side-1",
    "--ttl-seconds", "120",
    "--write-scope", "docs/**",      # different scope, no conflict

)
assert result["ok"] and result["acquired"]

# New lease created because scopes do not conflict

```

## Source Code Implementation

The `task_lease_v0` semantics are implemented across three key locations in the `huangruiteng/loopx` repository:

- **[`examples/control_plane/task-lease-runtime-smoke.py`](https://github.com/huangruiteng/loopx/blob/main/examples/control_plane/task-lease-runtime-smoke.py)**: Demonstrates the full lifecycle, including TTL expiration, idempotency validation, and write-scope conflict detection (lines [31-51] for initial acquisition, lines [62-82] for idempotency checks, and lines [84-100] for CAS validation).
- **[`loopx/cli.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/cli.py)**: Implements the `task-lease acquire` command that enforces the contract, processing arguments `--ttl-seconds`, `--idempotency-key`, and `--write-scope`.
- **[`loopx/contracts/task_lease_v0.json`](https://github.com/huangruiteng/loopx/blob/main/loopx/contracts/task_lease_v0.json)**: Defines the JSON schema for lease records, specifying fields such as `ttl_seconds`, `idempotency_key`, `write_scope`, and versioning metadata.

## Summary

The `task_lease_v0` contract provides robust todo ownership through three coordinated mechanisms:

- **TTL (Time-to-Live)**: Leases automatically expire after the specified duration, preventing permanent locks from crashed or unresponsive agents.
- **Idempotency**: The `--idempotency-key` parameter ensures repeated acquisition attempts return the existing lease rather than creating duplicates, making retries safe and deterministic.
- **Compare-and-Swap with Write-Scope**: The contract validates that new acquisitions do not conflict with existing leases’ file path scopes, enabling parallel work on disjoint directories while preventing concurrent writes to the same paths.

## Frequently Asked Questions

### What happens when a `task_lease_v0` lease reaches its TTL expiration?

When the **TTL (Time-to-Live)** expires, the lease automatically becomes invalid and the todo becomes available for other agents to acquire. The original holder loses exclusive write rights to the scoped paths, and no explicit release command is required. This prevents deadlocks if an agent crashes or becomes unresponsive before completing its work.

### How does the idempotency key prevent duplicate leases in LoopX?

The `--idempotency-key` acts as a unique fingerprint for each acquisition intent. When the `acquire` command in [`loopx/cli.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/cli.py) detects a matching key for an existing active lease, it returns the current lease state with `idempotent: true` and does not increment the lease version. This guarantees that network retries or script reruns do not accidentally create multiple ownership records for the same task.

### What is the write-scope in `task_lease_v0` and how does it enable concurrent work?

The **write-scope** is a glob pattern (such as `loopx/**` or `docs/**`) that defines the file paths a lease holder is authorized to modify. The contract uses **compare-and-swap (CAS)** logic to verify that new acquisitions request non-overlapping scopes with existing leases. If scopes are disjoint, multiple agents can hold leases simultaneously for different todos, enabling genuine parallelism while maintaining safety through path isolation.

### Where is the `task_lease_v0` contract schema formally defined?

The formal schema definition resides in **[`loopx/contracts/task_lease_v0.json`](https://github.com/huangruiteng/loopx/blob/main/loopx/contracts/task_lease_v0.json)**. This JSON file specifies the structure of lease records, including required fields for `ttl_seconds`, `idempotency_key`, `write_scope`, and version tracking, ensuring consistent validation across the LoopX control plane implementation.