# Transactions

---

# Transactions

_Peios Kernel / Internals / LCS / Transactions_

> Find the Peios kernel articles about transactions.

Use these articles to understand transactions in the Peios kernel.

- [Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md>)
- [Isolation and the Mutation Log](</kernel/internals/lcs/transactions/isolation-and-the-mutation-log.md>)
- [Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md>)

---

# Scope and Lifetime

_Peios Kernel / Internals / LCS / Transactions_

> Grouping registry operations so they commit together or not at all — binding, states, timeout, and sources that do not support them.

<a id="trm-5-7-1"></a>

A transaction groups registry operations so that they commit together
or not at all. <a id="cite-txn.lifetime.commit-together-or-not-at-all"></a>
Installing a role writes service definitions, defaults and registry
entries; a transaction is what makes that one event rather than a
sequence of partially-applied ones.

`reg_begin_transaction` takes no arguments and returns a transaction
fd. It contacts no source: it allocates an id, creates an anonymous
inode, starts the lifetime timer, and returns. <a id="cite-txn.lifetime.begin-contacts-no-source"></a>

A transaction begins in the state `REG_TXN_ACTIVE_UNBOUND`. <a id="cite-txn.lifetime.begins-active-unbound"></a>

<a id="trm-5-7-1-1"></a>

## Binding

A write transaction binds to a source on its first **mutating** operation. <a id="cite-txn.lifetime.binds-on-first-mutating-operation"></a>

There are seven: writing a value, deleting a value entry, setting or
removing a blanket tombstone, creating a key, deleting a key's path
entry, hiding a key, and changing a Security Descriptor. <a id="cite-txn.lifetime.the-seven-binding-operations"></a>

Reads never bind a write transaction. <a id="cite-txn.lifetime.reads-never-bind"></a>

A read passed an unbound write transaction fd is sent to the source with a
transaction id of zero and behaves as an ordinary non-transactional
read. <a id="cite-txn.lifetime.unbound-read-is-non-transactional"></a>

`reg_begin_read_transaction` creates a read-only transaction. Its first read
binds the source/hive and fixes the persistent and volatile data snapshot and
layer view. It uses the ordinary lifetime timer and read-only source quota.
The kernel rejects mutations with `EROFS`. Snapshot capture overlapping a
publication returns `EAGAIN`; the caller retries its whole read using a fresh
transaction. Writers continue while an established read snapshot exists.

Once bound, every operation on that fd must target the same hive.
One that does not fails with `EXDEV`, and it fails in the kernel,
before anything reaches a source — a source never sees a cross-hive
operation inside a transaction. <a id="cite-txn.lifetime.cross-hive-operation-is-exdev-in-the-kernel"></a>
Cross-source atomicity would require two-phase commit and is not
supported.

Binding identity is the pair of source and hive root GUID carried on
the transaction object, which identifies the hive exactly. <a id="cite-txn.lifetime.binding-identity-is-source-and-hive-root"></a>

<a id="trm-5-7-1-2"></a>

## Sources that do not support transactions

Because `reg_begin_transaction` chooses no source, it cannot fail for
lack of transaction support. The failure surfaces on the operation that
would have bound: LCS sends `RSI_BEGIN_TRANSACTION`, the source answers
`RSI_TXN_NOT_SUPPORTED`, and the operation returns `ENOTSUP`. <a id="cite-txn.lifetime.unsupported-source-binds-with-enotsup"></a>

The transaction stays `ACTIVE_UNBOUND`, its source binding untouched,
and the caller can use the fd against a different hive. <a id="cite-txn.lifetime.failed-bind-leaves-the-transaction-unbound"></a>

There is no advance check of whether a source supports transactions.
The answer comes from the source, on the attempt.

If the source is Down before the first bind, the binding operation
fails `EIO` under the ordinary rules and the transaction likewise
remains unbound. <a id="cite-txn.lifetime.source-down-before-bind-is-eio"></a>
If a source goes Down after binding, the transaction becomes
`REG_TXN_SOURCE_DOWN` ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).

<a id="trm-5-7-1-3"></a>

## States <a id="cite-txn.lifetime.the-six-transaction-states"></a>

| State | Value | Meaning |
|---|---|---|
| `REG_TXN_ACTIVE_UNBOUND` | 0 | Active, no source chosen. |
| `REG_TXN_ACTIVE_BOUND` | 1 | Active, bound to a source. |
| `REG_TXN_COMMITTED` | 2 | Commit completed. |
| `REG_TXN_ABORTED` | 3 | Explicitly or implicitly aborted. |
| `REG_TXN_TIMED_OUT` | 4 | The lifetime timer fired. |
| `REG_TXN_SOURCE_DOWN` | 5 | The bound source went Down. |

`REG_IOC_TXN_STATUS` reports the state and a `terminal_errno`: 0 for
`COMMITTED`, `EINVAL` for `ABORTED`, `ETIMEDOUT` for `TIMED_OUT`, `EIO`
for `SOURCE_DOWN`, and 0 while active.

For `COMMITTED`, `terminal_errno` is not the errno that a further
operation would return. A committed transaction reports 0, but using
its fd again returns `EINVAL`.

<a id="trm-5-7-1-4"></a>

## Reaching a terminal state

- **Commit.** `REG_IOC_COMMIT` on the transaction fd. The source
  applies everything atomically, watch events fire, and the object
  becomes `COMMITTED`. Later use of the fd returns `EINVAL`. The fd
  should be closed. <a id="cite-txn.lifetime.use-after-commit-is-einval"></a>
- **Explicit abort.** `close()` without committing. The source is told
  to discard, and the object becomes `ABORTED` during release. No
  events. <a id="cite-txn.lifetime.close-without-commit-aborts"></a>
- **Implicit abort.** Process death closes the fd, which aborts it.
  There are no orphaned transactions. <a id="cite-txn.lifetime.process-death-aborts-no-orphans"></a>
- **Timeout.** The lifetime timer fires. See below.

The object stays addressable after reaching a terminal state, until the
fd is closed. <a id="cite-txn.lifetime.terminal-object-stays-addressable-until-close"></a>
That is what makes `REG_IOC_TXN_STATUS` useful.

Transaction fds are pollable. Any terminal transition wakes poll
waiters with `POLLERR | POLLHUP`. <a id="cite-txn.lifetime.terminal-transition-wakes-poll-with-pollerr-pollhup"></a>
A caller that needs a race-free reason for the wakeup queries the
status.

<a id="trm-5-7-1-5"></a>

## Timeout

The lifetime timer starts when the fd is created — not at the first
operation — and runs for `TransactionTimeoutMs`, default 30 seconds. <a id="cite-txn.lifetime.timer-starts-at-fd-creation"></a>

When it fires, the object becomes `TIMED_OUT`, poll waiters are woken,
and further use of the fd returns `ETIMEDOUT`. <a id="cite-txn.lifetime.timeout-makes-further-use-etimedout"></a>

The timer updates transaction state from softirq context. Task and
workqueue callers disable bottom halves while holding the shared state
spinlock, so the timer cannot interrupt a holder on the same CPU and
wait for that holder to release it. Synchronous timer cancellation runs
outside the state lock. <a id="cite-txn.lifetime.timer-state-lock-softirq-safe"></a>

If the transaction was bound and no commit is already in flight,
`RSI_ABORT_TRANSACTION` is sent to the source. <a id="cite-txn.lifetime.timeout-aborts-a-bound-transaction-at-the-source"></a>

The fd is not removed from the caller's table; `close()` still releases
it normally. <a id="cite-txn.lifetime.timeout-leaves-the-fd-in-the-table"></a>

The timeout is not a convenience. Sources serialise writers — loregd
does so through SQLite's WAL — so a stalled transaction blocks every
other write to that source. The timer is what bounds the starvation
window, and `MaxBoundTransactionsPerSource` (default 16) is what stops
colluding processes from extending it indefinitely by binding fresh
transactions at each timeout boundary. An operation that would bind
past that cap returns `EBUSY`. <a id="cite-txn.lifetime.bind-past-the-cap-returns-ebusy"></a>

The cap is tested before the source is contacted, but after the
transaction's mutation-log entry has been allocated; that entry is
freed on the way out. <a id="cite-txn.lifetime.cap-tested-after-log-entry-allocation"></a>

<a id="trm-5-7-1-6"></a>

## Constraints

- **No nesting.** Transactions are flat: no savepoints, no
  sub-transactions. The transaction fd accepts only `REG_IOC_COMMIT`
  and `REG_IOC_TXN_STATUS`; every other ioctl is `ENOTTY`. <a id="cite-txn.lifetime.transactions-are-flat"></a>
- **One transaction per fd.** A process may hold many transaction fds
  at once, but each is exactly one transaction. <a id="cite-txn.lifetime.one-transaction-per-fd"></a>
- **Reads are permitted.** A transaction is not write-only, which is
  what makes verify-then-write possible. <a id="cite-txn.lifetime.reads-are-permitted"></a>

---

# Isolation and the Mutation Log

_Peios Kernel / Internals / LCS / Transactions_

> Read-your-own-writes inside a transaction, implemented by the source rather than LCS — the mutation log, sequence numbers and conflicts.

<a id="trm-5-7-2"></a>

<a id="trm-5-7-2-1"></a>

## Read-your-own-writes

Within a bound write transaction, reads see the transaction's own uncommitted
writes. <a id="cite-txn.isolation.read-your-own-writes"></a>
LCS does not implement this; the source does. A read tagged with the
transaction id is executed by the source inside its open transaction,
which naturally includes the pending writes.

No uncommitted registry data is cached in the kernel for the purpose of
resolving reads. <a id="cite-txn.isolation.no-uncommitted-data-cached-in-the-kernel"></a>

Externally, only committed state is visible. A transaction's writes are
invisible to other threads and processes until commit. <a id="cite-txn.isolation.uncommitted-writes-are-invisible-externally"></a>

Read-only transactions preserve their first-read data and layer selection.
The kernel verifies that capture did not overlap a pending mutation or its
completion effects; this includes requests whose original caller timed out.
An overlap fails with `EAGAIN`, rather than mixing a source commit with an
earlier kernel layer table. The fence covers capture only and never holds a
writer lock for the lifetime of a read transaction.

Security descriptors read through `REG_IOC_GET_SECURITY_TRANSACTED` are
historical data, subject to the key fd's granted rights. New transacted opens
check the current descriptor of the historical target GUID and the actual
caller. The snapshot does not preserve an earlier permission to open a key.

<a id="trm-5-7-2-2"></a>

## The mutation log

LCS does keep something: a per-transaction **mutation log**, holding
what the kernel needs to know after a successful commit and cannot ask
the source for afterwards. Each accepted mutating operation records the
affected key, value or layer name, its assigned sequence number, the
ancestor chain for watch dispatch, and enough context to compute
effective-state changes. <a id="cite-txn.isolation.log-records-per-operation-context"></a>

The log is not the source of truth for reads and it is not a rollback
journal — the source's own transaction state is authoritative for
uncommitted data. <a id="cite-txn.isolation.log-is-not-a-rollback-journal"></a>
The log exists so that when the source says "yes", LCS can produce the
hive generation updates and the watch events that correspond to what
was just committed.

It is bounded at 4096 entries. That bound is a compile-time constant
rather than one of the self-configuration parameters. <a id="cite-txn.isolation.log-bounded-at-4096-entries"></a>

Exceeding it fails the operation with `ENOMEM`. <a id="cite-txn.isolation.log-full-fails-the-operation-with-enomem"></a>

An operation whose log entry cannot be allocated fails **before it is
sent to the source**. <a id="cite-txn.isolation.log-allocation-failure-precedes-the-source-send"></a>
That ordering is deliberate: an operation the source applied but the
kernel cannot account for is exactly the state the log exists to
prevent.

The log is released, with no events emitted, on explicit abort, on a
lifetime timeout that fires before a commit is dispatched, on
source-down cancellation, on a late commit error, and on source
teardown while a post-dispatch commit response is still retained. <a id="cite-txn.isolation.log-release-conditions"></a>

It is **retained** across a post-dispatch commit timeout, because the
source may still answer. <a id="cite-txn.isolation.log-retained-across-a-post-dispatch-timeout"></a>

<a id="trm-5-7-2-3"></a>

## Sequence numbers

A transactional mutation is assigned its sequence number when it is
accepted into the transaction, not at commit. <a id="cite-txn.isolation.sequence-assigned-on-accept-not-at-commit"></a>
This preserves the order in which the caller performed the operations,
which is what layer tiebreaking and watch ordering need.

If the transaction aborts, those numbers are simply never used. <a id="cite-txn.isolation.aborted-sequence-numbers-are-never-used"></a>
Gaps in the sequence space are normal and mean nothing ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)).

<a id="trm-5-7-2-4"></a>

## Layer precedence coherency

Layer metadata lives in the registry, so a transaction can write to it —
and that raises the question of whether a precedence change takes
effect inside the transaction that made it. It does not. <a id="cite-txn.isolation.precedence-change-does-not-take-effect-in-its-own-transaction"></a>

Resolution always uses the published layer cache, which is refreshed
only at commit. <a id="cite-txn.isolation.resolution-uses-the-published-layer-cache"></a>

Reading the `Precedence` value back inside the transaction shows the
new number, because that is an ordinary read-your-own-writes read from
the source. <a id="cite-txn.isolation.precedence-value-reads-back-as-the-new-number"></a>

Resolving any *other* value in the same transaction still uses the old
precedence order. <a id="cite-txn.isolation.other-values-resolve-under-the-old-precedence"></a>
The two are consistent with each other and with the rule that a
transaction's effects become real at commit.

The refresh is deferred to commit, dropped on abort, and performed
before `REG_IOC_COMMIT` returns on success. <a id="cite-txn.isolation.layer-cache-refresh-completes-before-commit-returns"></a>

<a id="trm-5-7-2-5"></a>

## Conflicts

Transactions are atomic. They are not conflict-detecting. <a id="cite-txn.isolation.no-conflict-detection"></a>

If two transactions write the same value, both commits succeed and the
one that committed second wins, because its write carries the higher
sequence number. <a id="cite-txn.isolation.second-committer-wins"></a>
There is no read set, no version check, and no per-key validation
anywhere in the commit path.

Serialising concurrent writers is the source's responsibility, not
LCS's. The RSI requires only that commits are atomic, that writes
within a transaction are ordered, and that concurrent commits are
serialised. <a id="cite-txn.isolation.rsi-requires-atomic-ordered-serialised-commits"></a>

Conditional writes are the mechanism for the cases where losing an
update matters. `REG_IOC_SET_VALUE` takes an `expected_sequence`, the
source verifies it atomically against the layer's own entry, and a
mismatch returns `EAGAIN` ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)).

That is a per-operation check, not a transaction-level one, and it is
deliberately scoped to a single layer: a higher-precedence layer
overriding a value is not a conflict, it is the layer system
working. <a id="cite-txn.isolation.conditional-write-is-per-operation-and-single-layer"></a>

---

# Commit and Failure

_Peios Kernel / Internals / LCS / Transactions_

> What a commit triggers in order, the failures that leave a transaction open, and what happens when the watch events cannot be delivered.

<a id="trm-5-7-3"></a>

`REG_IOC_COMMIT` marks the transaction as having a commit in flight and
sends `RSI_COMMIT_TRANSACTION`. <a id="cite-txn.commit.marks-in-flight-and-sends-rsi-commit"></a>
What happens next depends on the answer.

<a id="trm-5-7-3-1"></a>

## Success

The source's `RSI_OK` triggers, in order: the layer metadata cache
refresh for any layer names the transaction touched, the hive
generation increment, orphan tracking for keys that lost their last
path entry, and the watch event batch derived from the mutation log. <a id="cite-txn.commit.post-commit-step-order"></a>

The object then becomes `COMMITTED`, the log is released, poll waiters
are woken, and the ioctl returns 0. <a id="cite-txn.commit.success-finalises-and-returns-zero"></a>

The hive generation is incremented once per committed transaction per
affected hive, however many operations the transaction contained. <a id="cite-txn.commit.generation-incremented-once-per-transaction-per-hive"></a>

<a id="trm-5-7-3-2"></a>

## Failure that leaves the transaction open

A source that cannot take the write lock answers `RSI_TXN_BUSY`, which
becomes `EBUSY`; a synchronous commit failure becomes `EIO`. <a id="cite-txn.commit.busy-is-ebusy-and-commit-failure-is-eio"></a>

In both cases the transaction stays `ACTIVE_BOUND`: <a id="cite-txn.commit.failed-commit-stays-active-bound"></a>

- the mutation log is retained; <a id="cite-txn.commit.failed-commit-retains-the-log"></a>
- no watch events are emitted; <a id="cite-txn.commit.failed-commit-emits-no-events"></a>
- poll waiters are **not** woken as though the transaction had become
  terminal. <a id="cite-txn.commit.failed-commit-does-not-wake-poll-waiters"></a>

The in-flight marker is cleared, so the caller may simply retry
`REG_IOC_COMMIT`, or close the fd to abort. Nothing has been lost. <a id="cite-txn.commit.in-flight-marker-cleared-so-retry-is-allowed"></a>

<a id="trm-5-7-3-3"></a>

## Timeout after dispatch

If the request timeout expires after the commit was dispatched, the
caller receives `ETIMEDOUT` and the object becomes `TIMED_OUT`, but the
mutation log is kept and the request record stays in the source's
in-flight table. The source may still answer. <a id="cite-txn.commit.post-dispatch-timeout-keeps-log-and-request"></a>

`ETIMEDOUT` on a commit means *may or may not have committed*. A caller
that needs certainty checks state before retrying. <a id="cite-txn.commit.etimedout-is-indeterminate"></a>

A late `RSI_OK` applies the full set of kernel-side effects from the
retained log — the same generation updates and the same watch events an
on-time commit would have produced. Watchers may therefore observe the
effects of a transaction whose caller was told it timed out. <a id="cite-txn.commit.late-ok-applies-the-full-effects"></a>

A late error releases the log with no effects. <a id="cite-txn.commit.late-error-releases-the-log-with-no-effects"></a>

The transaction object does **not** move to `COMMITTED` when a late
success arrives. It stays `TIMED_OUT`, so a caller that queries
`REG_IOC_TXN_STATUS` afterwards is told `TIMED_OUT` with a
`terminal_errno` of `ETIMEDOUT`, even though the writes are durable and
the watch events have gone out. <a id="cite-txn.commit.late-success-leaves-the-state-timed-out"></a>
The state reflects what the caller was told, not what the source did.

<a id="trm-5-7-3-4"></a>

## When the watch events cannot be derived

Two of the post-commit steps query the source. Working out which keys
were orphaned by a key deletion needs a lookup that can only be made
after the commit, and expanding a blanket tombstone into per-value
events needs the value set.

If that derivation cannot complete exactly, LCS does not reinterpret a
successful commit as a failed one and does not emit a partial set of
events. It delivers `OVERFLOW` to the affected watchers instead,
releases the retained replay state, and reports the commit as
successful, which it was. <a id="cite-txn.commit.underivable-events-become-overflow"></a>

A late response arriving afterwards does not resurrect the individual
events once overflow recovery has been chosen. <a id="cite-txn.commit.overflow-recovery-is-not-undone-by-a-late-response"></a>

The carve-out is narrower than it might appear. It covers the orphan
lookup and the watch batch. <a id="cite-txn.commit.carve-out-covers-only-orphan-lookup-and-watch-batch"></a>

The other two post-commit steps — publishing the layer metadata cache
and recording the hive generation — are state updates rather than event
derivation, and a failure in either returns `EIO` and marks the source
Down. <a id="cite-txn.commit.cache-or-generation-failure-is-eio-and-marks-the-source-down"></a>

<a id="trm-5-7-3-5"></a>

## Abort

Aborting generates no events, ever, and releases the log. <a id="cite-txn.commit.abort-emits-no-events-and-releases-the-log"></a>

The source is told to roll back with `RSI_ABORT_TRANSACTION` if the
transaction was bound. <a id="cite-txn.commit.abort-sends-rsi-abort-when-bound"></a>

Process death is the same path: closing the fd aborts.
