Skip to content

Lock-free TransactionChain.CreateTransaction #145

Closed

Description

@nockawa

Related Documents

Summary

Make TransactionChain.CreateTransaction() fully lock-free by splitting the chain's synchronization into two tiers: a CAS-based lock-free push for transaction creation (hot path), and an exclusive lock retained only for Remove (cold path).

Today, CreateTransaction acquires an exclusive AccessControl lock that serializes all Creates, Removes, and commit-path tail checks. This is the last global serialization point for write throughput scaling after OLC eliminated the B+Tree global lock.

Motivation

Current contention pattern (4 threads):

Thread A: CreateTransaction → exclusive lock → blocks all others
Thread B: Commit → wants shared lock for tail check → blocked by A
Thread C: Dispose → Remove → wants exclusive lock → blocked by A
Thread D: CreateTransaction → wants exclusive lock → blocked by A

After this change:

Thread A: CreateTransaction → CAS push → zero contention
Thread B: Commit → shared lock → only blocked by concurrent Remove
Thread C: Dispose → Remove → exclusive lock → only blocks other Removes
Thread D: CreateTransaction → CAS push → zero contention

The hot path (Create) no longer serializes with anything.

Design

Three-tier synchronization

Tier 1 — Lock-free (CreateTransaction):

  • TSN allocation: Interlocked.Increment(ref _nextFreeId) — already atomic, move outside lock
  • Pool: Replace Queue<Transaction> with ConcurrentQueue<Transaction>
  • ActiveCount: Interlocked.Increment then check against max. If exceeded, decrement and throw. Transient over-admission by a few slots is acceptable (resource guard, not correctness invariant)
  • PushHead: CAS loop on _head — textbook lock-free stack push
void PushHead(Transaction tx)
{
    Interlocked.Increment(ref _activeCount);
    Transaction oldHead;
    do
    {
        oldHead = Volatile.Read(ref _head);
        tx.Next = oldHead;
    } while (Interlocked.CompareExchange(ref _head, tx, oldHead) != oldHead);

    // If chain was empty, set tail (CAS only succeeds if null → non-overlapping with Remove)
    if (oldHead == null)
    {
        Interlocked.CompareExchange(ref _tail, tx, null);
        Volatile.Write(ref _minTSN, tx.TSN);
    }
}

Tier 2 — Exclusive lock (Remove, cold path):

  • Holds exclusive _control lock
  • Scans from _head to find predecessor (singly-linked, O(n), max 128 transactions ≈ 500ns)
  • Uses Interlocked.CompareExchange on _head when removing head node (handles concurrent PushHead)
  • Updates _tail / _minTSN when tail is removed
  • Pool enqueue via ConcurrentQueue
void Remove(Transaction tx)
{
    _control.EnterExclusiveAccess(ref wc);
    Interlocked.Decrement(ref _activeCount);

    // Scan for predecessor (singly-linked)
    var cur = Volatile.Read(ref _head);
    Transaction prev = null;
    while (cur != null && cur != tx)
    {
        prev = cur;
        cur = cur.Next;
    }

    // Unlink
    if (prev != null)
        prev.Next = tx.Next;
    else
        Interlocked.CompareExchange(ref _head, tx.Next, tx); // CAS handles concurrent PushHead

    // Tail maintenance
    if (Volatile.Read(ref _tail) == tx)
    {
        var newTail = FindTail(); // walk from head to end
        Volatile.Write(ref _tail, newTail);
        Volatile.Write(ref _minTSN, newTail?.TSN ?? 0);
    }

    _pool.Enqueue(tx); // ConcurrentQueue
    _control.ExitExclusiveAccess();
}

Tier 3 — Shared lock (reads):

  • WalkHeadToTail: shared lock on _control — blocks Remove, does NOT block PushHead
  • Commit/rollback tail check: shared lock on _control — same

Drop Previous pointers — singly-linked chain

The doubly-linked list becomes singly-linked (Next only). The Previous pointer was used in 3 call sites to compute NextMinTSN:

// Before (3 sites in Transaction.cs):
context.NextMinTSN = context.IsTail 
    ? _dbe.TransactionChain.Tail.Previous?.TSN ?? (_dbe.TransactionChain.NextFreeId + 1) 
    : 0;

Replace with a scan-based helper on TransactionChain:

// New: scan from head to find second-to-last (the node before tail)
internal long ComputeNextMinTSN()
{
    var cur = Volatile.Read(ref _head);
    Transaction secondToLast = null;
    while (cur != null && cur.Next != null)
    {
        secondToLast = cur;
        cur = cur.Next;
    }
    return secondToLast?.TSN ?? (Volatile.Read(ref _nextFreeId) + 1);
}

This scan runs under shared lock, max 128 entries ≈ 500ns, and only executes when IsTail == true (exactly one transaction at any time).

Affected call sites in Transaction.cs:

  • Line 1426 (rollback tail check)
  • Line 1539 (deferred WAL commit tail check)
  • Line 1586 (commit tail check)

Concurrency correctness

PushHead (lock-free) Remove (exclusive lock) Safe?
CAS on _head Reads _head, scans chain ✅ CAS is atomic. Remove's scan follows stable Next pointers. PushHead only prepends, never modifies existing nodes' Next.
CAS on _head CAS on _head (removing head) ✅ Only one succeeds; loser observes the change.
CAS on _tail (null→non-null) Writes _tail (under lock) ✅ Non-overlapping conditions: PushHead CAS only if _tail == null; Remove only writes when removing current tail (non-null).
WalkHeadToTail (shared lock) PushHead (lock-free) Safe?
Captures _head, walks Next Pushes new head ✅ Walker sees consistent snapshot. New head may not be visible (fine). Existing Next pointers never modified by PushHead.

Implementation Checklist

  • TransactionChain.cs: Replace Queue<Transaction> with ConcurrentQueue<Transaction>
  • TransactionChain.cs: Remove Previous pointer assignments from PushHead and Remove
  • TransactionChain.cs: Rewrite PushHead as CAS-based lock-free push (singly-linked)
  • TransactionChain.cs: Rewrite CreateTransaction — pool/TSN/activeCount outside any lock, only PushHead (now lock-free)
  • TransactionChain.cs: Rewrite Remove — scan from head for predecessor, CAS on _head when removing head, retain exclusive lock
  • TransactionChain.cs: Add ComputeNextMinTSN() helper (scan under shared lock)
  • TransactionChain.cs: Convert Head/Tail/MinTSN to fields with Volatile.Read/Write access
  • Transaction.cs: Update 3 Tail.Previous?.TSN call sites to use ComputeNextMinTSN()
  • Transaction.cs: Remove Previous field from Transaction class
  • Tests: Verify MPSC correctness — 4 threads creating transactions, 1 thread disposing, verify no lost/corrupt transactions
  • Tests: Verify MinTSN tracking — create 5 transactions, dispose oldest, verify MinTSN advances correctly
  • Tests: Verify pool recycling — create/dispose cycle, verify pool objects are reused
  • Tests: Verify max active limit — exceed limit, verify exception thrown and activeCount rolls back
  • Tests: Stress test — 8 threads, continuous create/commit/dispose for 10 seconds, verify no corruption
  • Benchmark: Compare before/after throughput with 4+ concurrent transaction creators

Risk Assessment

Risk Severity Mitigation
CAS-based PushHead Low Textbook lock-free stack push, well understood
Remove scans O(n) instead of O(1) via Previous Low Max 128 transactions, ~500ns under exclusive lock, cold path
Tail/MinTSN race between PushHead and Remove Low Non-overlapping conditions (null→non-null vs non-null→other)
ComputeNextMinTSN scan replaces Previous pointer Medium Only runs when IsTail==true (one transaction), under shared lock

Files Changed

File Change
src/Typhon.Engine/Data/Transaction/TransactionChain.cs Core refactor — lock-free PushHead, singly-linked, ConcurrentQueue pool
src/Typhon.Engine/Data/Transaction/Transaction.cs Drop Previous field, update 3 NextMinTSN call sites
test/Typhon.Engine.Tests/ New concurrency tests for lock-free create path

Activity

  1. moved this to Backlog in Typhon devon Mar 11, 2026
  2. moved this from Backlog to In Progress in Typhon devon Mar 12, 2026
  3. self-assigned this
    on Mar 12, 2026
  4. moved this from In Progress to Review in Typhon devon Mar 12, 2026
  5. moved this from Review to Done in Typhon devon Mar 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

performance

Type

No type

Fields

Priority

None yet

Area

Concurrency

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions