Class Transaction
A single MVCC snapshot-isolated transaction: the unit of ECS reads and mutations (Spawn / Open / Destroy, component reads and writes) executed against the snapshot fixed at its TSN. Obtained from a UnitOfWork (or the convenience CreateQuickTransaction(DatabaseEngine, DurabilityMode, DurabilityDiscipline)) and finished with Commit(ConcurrencyConflictHandler) or Rollback().
public class Transaction : EntityAccessor, IDisposable
- Inheritance
-
Transaction
- Implements
- Inherited Members
Remarks
Instances are pooled and reused; do not hold a reference past Dispose(). Transactions are single-thread-affine — only the thread that created one may call its members. A write-write conflict at commit is resolved by the optional Typhon.Engine.Internals.ConcurrencyConflictHandler (default: last-writer-wins).
Constructors
Transaction()
public Transaction()
Properties
CommittedOperationCount
Number of component operations this transaction carries: the sum of cached entries across every touched component type plus components deleted during rollback bookkeeping. Computed lazily on first access and cached.
public int CommittedOperationCount { get; }
Property Value
IsReadOnly
When true, all write operations (Create/Update/Delete/Commit) are forbidden. No ChangeSet or UoW is allocated.
public bool IsReadOnly { get; }
Property Value
Next
Intrusive link to the next transaction in the engine's transaction chain. Managed by the engine; not intended for external use.
public Transaction Next { get; }
Property Value
State
Current lifecycle state of this transaction.
public Transaction.TransactionState State { get; }
Property Value
Methods
Commit(ConcurrencyConflictHandler)
Commits this transaction using the default commit timeout (DefaultCommitTimeout). See Commit(ref UnitOfWorkContext, ConcurrencyConflictHandler) for the full contract.
public bool Commit(ConcurrencyConflictHandler handler = null)
Parameters
handlerConcurrencyConflictHandlerOptional write-write conflict resolver. null to accept the default last-writer-wins behavior.
Returns
- bool
true if the transaction committed (including read-only and empty transactions); false if it was already committed or rolled back.
Exceptions
- CommitDurabilityUncertainException
The write is committed but its on-media durability was not confirmed within the wait. Only reachable on the FUA/Immediate durability path.
Commit(ref UnitOfWorkContext, ConcurrencyConflictHandler)
Commits this transaction: processes every modified component, appends the WAL batch (the point of no return), then publishes the changes so they become
visible to later transactions. When handler is supplied, each write-write conflict is surfaced to it for resolution; otherwise the
last write wins.
public bool Commit(ref UnitOfWorkContext ctx, ConcurrencyConflictHandler handler = null)
Parameters
ctxUnitOfWorkContextUnit-of-work context carrying the deadline / cancellation used for lock and durability waits.
handlerConcurrencyConflictHandlerOptional write-write conflict resolver. null to accept the default last-writer-wins behavior.
Returns
- bool
true if the transaction committed (including read-only and empty transactions); false if it was already committed or rolled back.
Exceptions
- CommitDurabilityUncertainException
The commit is durably past its point of no return (records were appended) but the durability wait did not confirm — the write is committed, its on-media durability unconfirmed. Only reachable on the FUA/Immediate durability path.
CreateComponentCollectionAccessor<T>(ref ComponentCollection<T>)
Creates a mutable accessor over a ComponentCollection<T> field, bound to this transaction's Typhon.Engine.Internals.ChangeSet so edits are tracked for commit/rollback.
public ComponentCollectionAccessor<T> CreateComponentCollectionAccessor<T>(ref ComponentCollection<T> field) where T : unmanaged
Parameters
fieldComponentCollection<T>Reference to the collection field to wrap.
Returns
- ComponentCollectionAccessor<T>
A mutable accessor over the collection's backing buffer.
Type Parameters
TUnmanaged element type of the collection.
Destroy(EntityId)
Mark an entity for destruction, including cascade delete of children. The entity and all cascade-delete children become invisible to transactions with TSN >= commit TSN. Component data and LinearHash entries are freed later by deferred GC.
public void Destroy(EntityId id)
Parameters
idEntityId
DestroyBatch(ReadOnlySpan<EntityId>)
Destroy a batch of entities. Single EnsureMutable check, pre-sized pending list. Cascade delete is applied per entity.
public void DestroyBatch(ReadOnlySpan<EntityId> ids)
Parameters
idsReadOnlySpan<EntityId>
Destroy<T>(EntityLink<T>)
Mark an entity link target for destruction.
public void Destroy<T>(EntityLink<T> link) where T : class
Parameters
linkEntityLink<T>
Type Parameters
T
Dispose()
Ends the transaction and returns it to the pool: auto-rolls back if it was not committed, processes any deferred cleanups it was gating, flushes its accessors, exits the epoch scope, and removes it from the transaction chain. Disposes the owning UnitOfWork when this transaction owns it (the CreateQuickTransaction(DatabaseEngine, DurabilityMode, DurabilityDiscipline) path). Idempotent.
public override void Dispose()
EcsCount<TArchetype>()
O(1) metadata count of live entities for TArchetype and descendants.
Uses LinearHash.EntryCount — fast but includes entities with DiedTSN set (not yet cleaned up).
For exact counts respecting visibility, use Query<T>().Count().
public long EcsCount<TArchetype>() where TArchetype : class
Returns
Type Parameters
TArchetype
EnumerateArchetypeEntities(ushort)
Non-generic enumeration of every entity in a single exact archetype, visible at this transaction's snapshot (TSN). The runtime counterpart to Query<TArchetype>(string, int, string) for tooling that only knows the archetype by its id at runtime (e.g. the Workbench Data Browser). Walks the archetype's entity map directly, so it works for both cluster and legacy storage. Entities pending destroy in this transaction are excluded; entities spawned (and not yet committed) in this transaction are NOT included — use the typed Query<TArchetype>(string, int, string) path when read-your-own-writes is required.
Prefer the generic Query<TArchetype>(string, int, string) whenever the archetype is known at compile time: it adds Tier-1/2/3 filtering, ordering, and paging, and avoids materializing a List<T> of every id. Reach for this overload only when the archetype type is not available statically.
public List<EntityId> EnumerateArchetypeEntities(ushort routingId)
Parameters
routingIdushortThe exact archetype to enumerate, identified by its per-DB routing id (the value carried in ArchetypeId and persisted as
ArchetypeR1.RoutingId). No subtree / polymorphic expansion.
Returns
- List<EntityId>
Entity ids in entity-map iteration order — deterministic for a given snapshot. Empty when the routing id is unknown or has no engine state. Pair each id with Open(EntityId) + ReadRaw(int) to decode component values without a compile-time type.
EnumerateIndex<T, TKey>(IndexRef, TKey, TKey)
Returns an enumerator that streams entities via a secondary index in key order, filtered by MVCC visibility at this transaction's snapshot.
public Transaction.IndexEntityEnumerator<T, TKey> EnumerateIndex<T, TKey>(IndexRef indexRef, TKey minKey, TKey maxKey) where T : unmanaged where TKey : unmanaged
Parameters
indexRefIndexRefminKeyTKeymaxKeyTKey
Returns
- Transaction.IndexEntityEnumerator<T, TKey>
Type Parameters
TTKey
GetComponentCollectionRefCounter<T>(ref ComponentCollection<T>)
Returns the reference count of the buffer backing a ComponentCollection<T> field (number of entities currently sharing that buffer).
public int GetComponentCollectionRefCounter<T>(ref ComponentCollection<T> field) where T : unmanaged
Parameters
fieldComponentCollection<T>Reference to the collection field to inspect.
Returns
- int
The backing buffer's reference count.
Type Parameters
TUnmanaged element type of the collection.
GetReadOnlyCollectionEnumerator<T>(ref ComponentCollection<T>)
Returns a read-only enumerator that streams the elements of a ComponentCollection<T> field without allocating.
public Transaction.ReadOnlyCollectionEnumerator<T> GetReadOnlyCollectionEnumerator<T>(ref ComponentCollection<T> field) where T : unmanaged
Parameters
fieldComponentCollection<T>Reference to the collection field to enumerate.
Returns
- Transaction.ReadOnlyCollectionEnumerator<T>
A read-only, zero-copy enumerator over the collection.
Type Parameters
TUnmanaged element type of the collection.
Init(DatabaseEngine, long, UnitOfWork, bool, DurabilityDiscipline)
(Re)initializes this pooled transaction instance for a new lease: enters an epoch scope, binds the engine and owning unit of work, fixes the MVCC
snapshot at tsn, and selects the durability discipline. Called by the engine when a transaction is created; not for direct use.
public void Init(DatabaseEngine dbe, long tsn, UnitOfWork uow = null, bool readOnly = false, DurabilityDiscipline discipline = DurabilityDiscipline.TickFence)
Parameters
dbeDatabaseEngineOwning database engine.
tsnlongTransaction sequence number that fixes this transaction's MVCC read snapshot.
uowUnitOfWorkOwning unit of work, or null for the standalone path (UoW id 0).
readOnlyboolWhen true, no Typhon.Engine.Internals.ChangeSet or UoW is allocated and all writes are forbidden.
disciplineDurabilityDisciplineDurability discipline applied to SingleVersion-layout writes for the transaction's lifetime.
IsAlive(EntityId)
Check whether an entity is alive (exists and visible at this transaction's TSN).
public bool IsAlive(EntityId id)
Parameters
idEntityId
Returns
IsAlive<T>(EntityLink<T>)
Check whether an entity link target is alive.
public bool IsAlive<T>(EntityLink<T> link) where T : class
Parameters
linkEntityLink<T>
Returns
Type Parameters
T
OpenMut(EntityId)
Open an entity for reading and writing. Adds EnsureMutable check + state transition.
public override EntityRef OpenMut(EntityId id)
Parameters
idEntityId
Returns
QueryExact<TArchetype>(string, int, string)
Create an exact query matching only TArchetype, no descendants.
public EcsQuery<TArchetype> QueryExact<TArchetype>(string sourceFile = null, int sourceLine = 0, string sourceMethod = null) where TArchetype : class
Parameters
Returns
- EcsQuery<TArchetype>
Type Parameters
TArchetype
QueryRead<T>(long, out T)
Read a component by PK from the ComponentTable revision chain. Used by the query engine for predicate evaluation. Performs MVCC-visible revision walk — more efficient than Open().Read() for single-component access because it doesn't resolve all archetype slots.
public bool QueryRead<T>(long pk, out T t) where T : unmanaged
Parameters
pklongtT
Returns
Type Parameters
T
Query<TArchetype>(string, int, string)
Create a polymorphic query matching TArchetype and all descendants.
Supports Tier 1 (.With, .Without, .Exclude), Tier 2 (.Enabled, .Disabled), and execution (.Execute, .Count, .Any, foreach).
public EcsQuery<TArchetype> Query<TArchetype>(string sourceFile = null, int sourceLine = 0, string sourceMethod = null) where TArchetype : class
Parameters
Returns
- EcsQuery<TArchetype>
Type Parameters
TArchetype
Rollback()
Discards all changes made by this transaction, using an unbounded (no-timeout) context.
public bool Rollback()
Returns
- bool
true if the transaction was rolled back (or had nothing to do because no operation was performed); false if it was already committed or rolled back.
Rollback(ref UnitOfWorkContext)
Discards all changes made by this transaction, tagging the rollback as Explicit.
public bool Rollback(ref UnitOfWorkContext ctx)
Parameters
ctxUnitOfWorkContextUnit-of-work context carrying the deadline / cancellation used for any lock waits during rollback.
Returns
- bool
true if the transaction was rolled back (or had nothing to do because no operation was performed); false if it was already committed or rolled back.
Rollback(ref UnitOfWorkContext, TransactionRollbackReason)
Phase 6: rollback with an explicit reason threaded into the kind 21 payload (D3).
public bool Rollback(ref UnitOfWorkContext ctx, TransactionRollbackReason reason)
Parameters
ctxUnitOfWorkContextreasonTransactionRollbackReason
Returns
SpawnBatchAllocate<TArch>(int, Span<EntityId>)
Allocate a batch of entities with chunks but no component data (all EnabledBits = 0). Returns the base index into the internal spawn list for use with SpawnBatchWriteAll<T>(int, int, Comp<T>, ReadOnlySpan<T>). Called by source-generated SpawnBatch methods for per-entity SOA data.
public int SpawnBatchAllocate<TArch>(int count, Span<EntityId> ids) where TArch : Archetype<TArch>
Parameters
Returns
Type Parameters
TArch
SpawnBatchWriteAll<T>(int, int, Comp<T>, ReadOnlySpan<T>)
Write an entire component span into already-allocated spawn entries. Resolves slot/table/accessor ONCE, then loops N writes with zero dictionary lookups. Called by source-generated SpawnBatch methods.
public void SpawnBatchWriteAll<T>(int baseIndex, int count, Comp<T> comp, ReadOnlySpan<T> values) where T : unmanaged
Parameters
baseIndexintcountintcompComp<T>valuesReadOnlySpan<T>
Type Parameters
T
SpawnBatch<TArch>(Span<EntityId>, params ComponentValue[])
Spawn a batch of entities. Amortizes per-call overhead: single EnsureMutable check, single Interlocked.Add for all entity keys, single epoch refresh at the end. All entities are initialized with the same component values (or zero if none provided).
public void SpawnBatch<TArch>(Span<EntityId> ids, params ComponentValue[] sharedValues) where TArch : Archetype<TArch>
Parameters
idsSpan<EntityId>sharedValuesComponentValue[]
Type Parameters
TArch
SpawnByArchetypeId(ushort, params ComponentValue[])
Spawn an entity using an archetype ID (non-generic). Enables runtime callers (Shell CLI) to create entities without compile-time archetype type parameters.
public EntityId SpawnByArchetypeId(ushort archetypeId, params ComponentValue[] values)
Parameters
archetypeIdushortvaluesComponentValue[]
Returns
Spawn<TArch>(params ReadOnlySpan<ComponentValue>)
Spawns a new entity of archetype TArch with the supplied initial component values.
Components not covered by values are zero-initialized and disabled.
The entity is stored in a pending map and inserted into the LinearHash at commit with BornTSN = TSN.
public EntityId Spawn<TArch>(params ReadOnlySpan<ComponentValue> values) where TArch : Archetype<TArch>
Parameters
valuesReadOnlySpan<ComponentValue>Initial component values; components omitted here are zero-initialized and disabled.
Returns
- EntityId
The id of the newly-spawned entity.
Type Parameters
TArchConcrete archetype type of the entity to spawn.
WriteComponent<T>(long, ref T)
Write a component by PK. Reconstructs EntityId from the raw PK, opens the entity for mutation, and writes the component data.
Generic — the Shell CLI calls this via MakeGenericMethod for runtime-resolved component types.
public bool WriteComponent<T>(long pk, ref T comp) where T : unmanaged
Parameters
pklongcompT
Returns
Type Parameters
T