Skip to content

Add partially lock-free size balanced tree with delayed balancing - #109

Open
konard wants to merge 25 commits into
mainfrom
issue-78-a000f3eb
Open

konard wants to merge 25 commits into
mainfrom
issue-78-a000f3eb

Conversation

@konard

@konard konard commented Sep 13, 2025 •

Copy link
Copy Markdown
Member

Summary

Adds PartiallyLockFreeSizeBalancedTreeMethods<TElement>, a size balanced tree that is "locked only for balancing", where "each N inserts can be done without any locking or balancing" (#78). Attaches and searches from many threads run without locks, and the tree is balanced once every N attaches (N = balancingThreshold, 1..4096).

The PR review asked for three things: a check that concurrent operations survive stress, a survey of published concurrent and lock-free trees with the best fitting design reimplemented, and a record of attempts that fail. All three are in docs/concurrent-trees.md.

Design

Attach is lock-free with respect to other attaches and Contains:

  1. reserve a pending slot with one CAS,
  2. descend like an ordinary BST insert, reading links with acquire semantics,
  3. publish the node as a leaf with one CAS of the empty child slot (on failure, continue from the node another thread attached there),
  4. record the node in its pending slot.

Sizes are lazy: an attach writes no field of an existing node, so threads never contend on the root.

Balance runs when the N-th attach finishes, when called explicitly, and before each Detach:

  1. take an exclusive gate (striped reader counters, one per cache line, plus an exclusive flag),
  2. sort the pending nodes,
  3. walk only the paths from the root to them in post-order, adding to each node's size the number of pending nodes in its key range,
  4. run the grown-side check of Chen's Maintain, falling back to the general Maintain.

After Balance or Detach the tree is size balanced and every size is exact.

Other changes:

  • Attach and Detach of SizedBinaryTreeMethodsBase become virtual, and the version is bumped to 1.1.0.
  • The README lists the new tree, and docs/**/*.md and experiments/**/*.md are now linted by markdownlint in CI.
  • Codacy findings are resolved in the source rather than ignored:
    • DefaultBalancingThreshold and MaximumBalancingThreshold are static properties.
    • The constructors are overloads instead of optional parameters. The parameterless one uses DefaultBalancingThreshold.
    • The AtomicElement fallback lock lives in a non-generic class, so all element types share one lock.
    • PaddedCounter and the element structs are record structs.
    • The test tree exposes Root by reference, as the other test trees do.
    • Balance(ref root) and Contains(node, ref root) suppress S3874 in their own file. Codacy compiles each file alone and does not see GlobalSuppressions.cs, and the root has to be read and replaced in place under the exclusive gate.
  • The new tree credits Chen Qifeng (size balanced tree) and the relaxed balancing work of Kung and Lehman and of Nurmi and Soisalon-Soininen, in its XML documentation, in the README credits and in check-credits.mjs.
  • All XML documentation of the new code (the tree methods, AtomicElement, PaddedCounter, the test tree and the tests) is bilingual, English then Russian, in <para> paragraphs, as the check-xml-docs.mjs check from Document every public C# and C++ element in English and Russian, and generate the C++ API documentation #111 requires. The CS1591 suppression in the tree methods is removed. The Doxygen coverage check also passes: the private comparer of pending nodes is documented, and the test tree constructor that calls base(...) has a block body, because Doxygen could not parse the expression body and moved the next member's docs.
  • main (including Document every public C# and C++ element in English and Russian, and generate the C++ API documentation #111 and Validate sizes, order, balance and threads of all trees like GLib's g_tree_node_check #112) is merged into the branch. The version conflict is resolved as 1.1.0, and the release notes keep the notes from main.
  • Like the other size balanced trees after Validate sizes, order, balance and threads of all trees like GLib's g_tree_node_check #112, the new tree overrides ValidateTree: it checks sizes and order and then the size balanced property. Sizes are exact only after balancing, so it throws InvalidOperationException while attached nodes wait for balancing. The ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION checks after Balance and Detach now call ValidateTree.

Research

The survey covers EFRB, Natarajan–Mittal, Howley–Jones, Ramachandran–Mittal/CASTLE, Bronson et al., logical ordering, LLX/SCX chromatic trees, CA trees, optimistic lock coupling, OCC (a,b)-trees, lock-free augmented trees (Fatourou–Ruppert 2024, CBAT 2026), wait-free augmented trees (Kokorin et al. 2024) and relaxed balancing.

Every lock-free tree that keeps subtree sizes is external and allocates descriptor or version objects. None of them fits this library: its nodes are fixed storage indices with plain numeric fields, and the trees are internal and augmented with sizes. What fits is relaxed balancing (update first, rebalance later) with a CAS-based attach path. A concurrent Detach would need a version word per node (optimistic lock coupling), which changes the storage format, so detach stays exclusive. This is listed as future work.

Failed attempts (recorded)

  1. bb183b7: plain writes guarded by a counter. experiments/old-partially-lock-free-stress breaks the tree in 9/10 and 10/10 rounds.
  2. b523130: CAS publication with atomic size increments of every ancestor. It is correct, but every thread contends on the root size, and it was slower than a lock (0.16 vs 0.41 M inserts/s on 6 threads).
  3. 2fc5e50: lazy sizes recomputed from both children. Reads scaled, but balancing cost more than the inserts it replaced.

Verification

  • PartiallyLockFreeSizeBalancedTreeTests has 20 tests:
    • Stress: 6–8 threads of attaches with thresholds 1/7/64/4096 for uint, ulong and the ushort lock fallback, plus concurrent attach, detach and Contains with thresholds 1/16/256. Threads start behind a barrier, each run has a timeout, and the tree is fully validated afterwards: links, order, sizes, the SBT property and that every node is found.
    • In the attach, detach and Contains stress test, the attachers wait until the reader has started. A CI run on a runner with fewer cores than threads failed checkedCount > 0: the attachers finished before the reader thread was first scheduled, so it checked nothing.
    • Deterministic interleavings: a balancing waits for in-flight attaches and blocks new ones, attaches wait when the pending capacity is full, and a 4096-node sorted chain is balanced on a thread with a 1 MB stack.
    • Duplicate keys, invalid thresholds and missing or already attached nodes.
    • ValidateTreeRequiresBalancedTreeTest: ValidateTree rejects a tree with pending nodes and accepts it when empty, after Balance and after each Detach.
    • BalancingNeverReadsSizeOfNullNodeTest: storage that throws on reading the size of node 0. Before 3a954bb the balancing of a pending leaf read it.
    • BalancingRecursionIsCompiledOptimizedTest: MaintainPaths is marked AggressiveOptimization. Run alone, the 1 MB stack test crashed the test host with a stack overflow: the first balancing recursed 8192 deep in unoptimized tier 0 code. In the full suite, other tests had already made the JIT optimize the method, which hid the crash. experiments/tier0-stack-overflow/run.sh reproduces it.
  • Local runs:
    • The full suite passes in Release with -warnaserror and coverage collection (131 tests), and the library is 100% line covered (1157 of 1157 lines).
    • node .github/scripts/check-xml-docs.mjs passes for all 76 files, and the Doxygen coverage check passes with Doxygen 1.18.0.
    • With -p:TreeValidation=true it also passes (128 passed, 1 skipped).
  • experiments/mutation-check/run.sh removes each synchronization step in turn. The tests catch all five mutations (result).

Benchmarks

experiments/concurrent-tree-benchmark, 1M uint nodes, millions of operations per second. The host is a shared 6-CPU machine, so multi-thread numbers vary by about 20%.

Tree 1 thread 2 threads 4 threads 6 threads
Insert: SBT + lock 0.53 0.33 0.34 0.36
Insert: partially lock-free, N=1024 0.42 0.45 0.43 0.45
Read mostly (90% Contains): SBT + lock 0.79 0.54 0.60 0.48
Read mostly: SBT + ReaderWriterLockSlim 0.81 0.52 0.44 0.37
Read mostly: partially lock-free, N=4096 0.80 1.50 2.13 1.90
  • Read-mostly workloads scale, reaching 2.4–4× the throughput of a lock.
  • Inserts beat a lock on 2+ threads but do not grow with the thread count. The split mode shows why: the serial balancing costs about as much per node as the lock-free descent (1.2–1.4 µs vs 1.1–1.4 µs), so by Amdahl's law inserts can at most double.

Limitations

  • Detach and Balance are exclusive.
  • Between balancings the root size misses the pending nodes. PendingBalancingCount reports how many.
  • IsLockFree is false for 8- and 16-bit elements, which fall back to a lock for the atomic operations.

Fixes #78

Adding CLAUDE.md with task information for AI processing.
This file will be removed when the task is complete.

Issue: #78
@konard konard self-assigned this Sep 13, 2025
This implementation addresses issue #78 by providing:

- Lock-free insertions: Multiple insertions (N) can be performed concurrently using ReaderWriterLockSlim read locks
- Delayed balancing: Balancing operations are delayed until a configurable threshold of insertions is reached
- Thread-safe operations: Uses atomic operations (Interlocked) for tracking insertion counts
- Exclusive locking for balancing: Tree balancing only locks when necessary using write locks

Key features:
- PartiallyLockFreeSizeBalancedTreeMethods<TElement>: Abstract base class extending SizeBalancedTreeMethods
- Configurable balancing threshold (default: 10 insertions)
- Manual balancing trigger via ForceBalancing() method
- Thread-safe insertion counter with atomic operations
- Custom delayed balancing logic that mirrors original maintain operations
- Comprehensive test suite including concurrent insertion tests

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@konard konard changed the title [WIP] Attempt to implement partially lock-free tree with delayed balancing Implement partially lock-free tree with delayed balancing Sep 13, 2025
@konard
konard marked this pull request as ready for review September 13, 2025 15:57
@konard

konard commented Dec 3, 2026 •

Copy link
Copy Markdown
Member Author

Double check it actually support any multiple operations on such tree, and it does not break under stress.

Also we need to check all latest experience in the internet and so on, so we can reimplement all best possible algorithms, which support concurrent operations on trees, if they actually exist, work, and are stable, or even totally lock free, that may allow us to have much more performant trees. And make access to them fully concurrent.

If now such solution exists, but we are feeling lucky, we can try implement one from scratch, but if we prove it does not work, we record it as failed attempt.

@konard
konard marked this pull request as draft December 4, 2026 00:01
@konard

konard commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

🤖 AI Work Session Started

Started at 2026-12-04T00:01:41.718Z. Please wait for it to finish before giving feedback.

Runtime: solve v2.50.0 · tool claude · model opus · task image konard/hive-mind-dind:2.50.0@sha256:39bda1084d8f7e24e6f1f758c32f40113f68d385759aa862c36b72e9b7570bb6

…mpt breaks under concurrent inserts

6 threads x 5000 concurrent Attach calls corrupt subtree sizes in 9 of 10 rounds
(non-atomic IncrementSize and non-atomic child-slot writes under a shared read lock).
…attaches with delayed balancing

- Attach links nodes with compare-and-swap on empty child slots and atomic size increments,
  concurrent attaches and reads never block each other.
- Balancing (every N attaches) and Detach take an exclusive gate; balancing restores
  the size balanced tree property along the paths of pending nodes with a general Maintain.
- Attach of an already attached node no longer corrupts the tree.
- Add concurrent stress tests for attach, detach and contains.
- Make the failed attempt #1 experiment reproducible against commit bb183b7.
The benchmark shows that eager atomic size increments on every attach make
the partially lock-free tree slower than a size balanced tree under a global lock.
…ounded pending slots

Attaches no longer increment the sizes of all ancestors (contended atomic
operations on the top nodes); the balancing recomputes sizes along the paths of
pending nodes. Shared mode uses per-processor padded counters instead of a
single counter. Pending slots are reserved inside the shared mode and attaches
wait when all of them are taken, so overflow handling is not needed. Adds
deterministic tests for the waiting paths, duplicate keys and the maximum
threshold recursion depth, and fixes nullability warnings.

Also makes setup-node version comments exact: the v7 tag has moved to v7.2.0,
so zizmor reported the v7.1.0 pin as mismatched.
…sults

- Balancing counts the pending nodes of every subtree instead of reading the
  child off the path, and checks only the grandchildren of a grown side
  (general Maintain stays the fallback and handles duplicate keys).
- Waiting attaches and reads spin read-only on the gate.
- Stress tests run on dedicated threads behind a barrier with a timeout, and
  catch only the expected exceptions (CodeQL).
- docs/concurrent-trees.md: survey of concurrent and lock-free trees, design,
  guarantees, verification, failed attempts and benchmarks; linted in CI.
- Benchmark: v2/v3 results and a split of attach vs balancing time.
- Mutation check rerun: all five synchronization mutations are detected.
- Version 1.1.0 with release notes; README lists the new tree.
@konard konard changed the title Implement partially lock-free tree with delayed balancing Add partially lock-free size balanced tree with delayed balancing Dec 4, 2026
A pending node without pending descendants is a leaf, but the balancing
still computed the sizes of its children and read GetSize(0), which a
storage without element 0 cannot serve. Such a leaf needs no maintenance.
BalancingNeverReadsSizeOfNullNodeTest fails without the fix.
docfx builds the README into the documentation site, where a relative link
to docs/ is invalid and fails the --warningsAsErrors build.
@konard
konard marked this pull request as ready for review December 4, 2026 02:03
Main now checks that every tree credits the original authors of its
algorithms; the partially lock-free tree builds on Chen's size balanced tree
and on the relaxed balancing of Kung and Lehman (1980) and Nurmi and
Soisalon-Soininen (1996).
@konard

konard commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Working session summary

I've added PartiallyLockFreeSizeBalancedTreeMethods, a size balanced tree where inserts and searches run without locks and the tree is locked only to balance. That's what issue #78 asked for. All CI checks pass on the latest commit (24bc60b). PR #109 is up to date with main and marked ready for review: #109

How it works

  • Each insert links its node into the tree with a single atomic compare-and-swap, with no lock and no balancing.
  • Every N inserts (N is the threshold, 1 to 4096), the next caller waits for in-flight inserts and searches to finish. It then fixes node sizes and balances only along the paths that grew.
  • Balance() and removals do the same balancing step; after them the tree is fully balanced and every node size is exact.

Your review comment

  • Concurrent operations under stress: stress tests mix concurrent inserts, searches, balancing and removals. I also broke the code on purpose in five ways (for example, a plain write instead of the compare-and-swap, or balancing without waiting for readers). The tests caught all five; results are in experiments/mutation-check/result.txt.
  • Survey of existing trees: docs/concurrent-trees.md compares the published concurrent and lock-free trees and explains why I built on relaxed balancing (Kung and Lehman; Nurmi and Soisalon-Soininen). It also records three of my own attempts that failed and why.
  • Credits: the code documentation, the README and the credits check now credit Chen Qifeng, Kung and Lehman, and Nurmi and Soisalon-Soininen.

Performance (1,000,000 nodes, 6 cores, million operations per second):

Workload Tree 1 thread 4 threads
90% search, 10% insert SBT + lock 0.79 0.60
90% search, 10% insert New tree, threshold 4096 0.80 2.13
Insert only SBT + lock 0.53 0.34
Insert only New tree, threshold 1024 0.42 0.43
  • Read-mostly work scales about 2.4–4× over a plain lock.
  • Insert-only work barely scales: balancing runs one thread at a time and costs about as much as the inserts themselves, which caps the gain at about 2×. The design note documents this limit.
  • Single thread: the new tree is slightly slower than the unsynchronized one.

Bug found during review: balancing read the size of the empty node (node 0) when it reached a newly added leaf. It's fixed, and a regression test fails before the fix and passes after.

Other changes

  • Attach and Detach in SizedBinaryTreeMethodsBase are now virtual.
  • The package version is 1.1.0.
  • The library targets .NET 8 and later.
  • CI now lints docs/**/*.md too.

Six CodeQL warnings were raised on earlier commits, and CodeQL now marks each of them as fixed. No other review bots have commented.


This summary was automatically extracted from the AI working session output.

@konard

konard commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

🤖 Solution Draft Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Public pricing estimate: $14.056203
  • Calculated by Anthropic: $14.228454
  • Difference: $0.172251 (+1.23%)

📊 Context and tokens usage:

Claude Opus 5.5: (6 sub-sessions)

  1. 116.0K / 1M (12%) input tokens, 57.4K / 128K (45%) output tokens
  2. 113.8K / 1M (11%) input tokens, 42.5K / 128K (33%) output tokens
  3. 115.6K / 1M (12%) input tokens, 29.6K / 128K (23%) output tokens
  4. 116.3K / 1M (12%) input tokens, 40.7K / 128K (32%) output tokens
  5. 116.9K / 1M (12%) input tokens, 33.5K / 128K (26%) output tokens
  6. 36.7K / 1M (4%) input tokens, 3.6K / 128K (3%) output tokens

Total: (13.2K new + 579.2K cache writes + 20.3M cache reads) input tokens, 259.0K output tokens, $13.747981 cost

Claude Haiku 5.5:

  • 577.6K / 1M (58%) input tokens, 40.9K / 128K (32%) output tokens

Total: 577.6K input tokens, 40.9K output tokens, $0.308222 cost

🤖 Models used:

  • Tool: Anthropic Claude Code
  • Requested: opus (claude-opus-5-5)
  • Thinking level: high (~23999 tokens)
  • Main model: Claude Opus 5.5 (claude-opus-5-5)
  • Additional models:
    • Claude Haiku 5.5 (claude-haiku-5-5)

📎 Log file uploaded as Gist (9554KB)


This AI session has ended. Monitoring of this pull request continues. Feel free to review and add feedback while checks are running.

@konard

konard commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

🔄 Auto-restart 1/5

Reason: CI failures detected

Evidence:

Starting a new session to address it.

@konard
konard marked this pull request as draft December 4, 2026 02:14
- The balancing thresholds are static properties and the constructors are
  overloads instead of public constants and optional parameters
  (S2339, S2360).
- Balance(ref root) and Contains(node, ref root) suppress S3874 in their own
  file: Codacy compiles each file alone and does not see GlobalSuppressions.cs,
  and the root must be read and replaced in place under the exclusive gate.
- The fallback lock of AtomicElement lives in a non-generic class, so it is
  one lock for all element types (S2743).
- PaddedCounter and the element structs are record structs, which implement
  IEquatable<T> (S3898).
- The test tree exposes Root by reference from a readonly one-element array
  and its hooks as properties, as the other test trees do (S1104, S2357).
- The experiments brace every statement and throw InvalidOperationException
  (S121, S112).
Codacy reported lines over 80 columns (MD013) and table separators without
spaces (MD060) in the experiment notes and recorded benchmark results. The
benchmark now prints its header on two lines and spaced separators, the
recorded results match that output, and the stress note is wrapped at 80
columns. The Markdown job also lints experiments/**/*.md, so these findings
fail in CI before Codacy reports them.
…ructor

With threshold 4096 sorted attaches form an 8192 node chain, and the first
balancing recursed along it in unoptimized tier 0 code, which overflowed a
1 MB stack (and a 1.5 MB one). The full test suite hid this because other
tests made the JIT optimize MaintainPaths first; run alone, or under coverage
instrumentation, the stack test crashed the test host. MaintainPaths is now
marked AggressiveOptimization, a test checks the flag, and
experiments/tier0-stack-overflow reproduces the crash.

The test tree's one argument constructor now uses the parameterless base
constructor, so the library stays fully covered.
On the 4 vCPU CI runner ConcurrentAttachDetachAndContainsStressTest(256)
failed at Assert.True(checkedCount > 0): its 6 threads outnumber the cores,
so the attachers finished before the reader was scheduled and the reader's
while loop never ran. The tree itself was valid. Now the reader marks that
it has started and checks at least once, and the attachers wait for that
mark before they finish.
# Conflicts:
#	csharp/Platform.Collections.Methods/Platform.Collections.Methods.csproj
@konard
konard marked this pull request as ready for review December 4, 2026 03:22
@konard

konard commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Working session summary

PR #109 is up to date with main, and all 32 CI checks pass on the latest commit (51f9d59), including Codacy, coverage and the Doxygen and XML-docs checks. The other 7 are skipped deploy/release/auto-merge jobs. The PR is mergeable, still marked ready, and the working tree is clean: #109

What changed this round:

  • Merged main (Validate sizes, order, balance and threads of all trees like GLib's g_tree_node_check #112). The only conflict was in Platform.Collections.Methods.csproj. I kept version 1.1.0, plus main's release notes followed by the note for this PR.
  • New ValidateTree for the partially lock-free tree. Validate sizes, order, balance and threads of all trees like GLib's g_tree_node_check #112 added a ValidateTree that the other size balanced trees override, so this tree now overrides it the same way. It checks node sizes, key order and the size-balance rule.
    • It throws InvalidOperationException while attached nodes are still waiting for balancing, because their sizes aren't counted yet. Callers need to call Balance first.
    • The debug-only self-checks after Balance and Detach now use ValidateTree instead of checking sizes only.
    • A new test, ValidateTreeRequiresBalancedTreeTest, covers the rejection and the valid cases: an empty tree, after Balance, and after each Detach.
  • README and PR description now explain this validation behaviour and show the new test counts.

Local checks before pushing:

  • Full test suite: 131 tests pass in Release with warnings treated as errors.
  • Line coverage: 100% (1157 of 1157 lines).
  • With the debug self-validation turned on (-p:TreeValidation=true): 128 pass, 1 skipped.
  • The XML-docs check passes for 76 files, the Doxygen check passes with Doxygen 1.18.0, and markdownlint finds no issues in the README.

No new comments or reviews have appeared on the PR or on issue #78 since the previous round. No human action is needed for any check, and the PR description still contains Fixes #78.


This summary was automatically extracted from the AI working session output.

@konard

konard commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

🔄 Auto-restart-until-mergeable Log 1/5

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Public pricing estimate: $7.635125
  • Calculated by Anthropic: $7.637702
  • Difference: $0.002577 (+0.03%)

📊 Context and tokens usage:

Claude Opus 5.5: (4 sub-sessions)

  1. 115.9K / 1M (12%) input tokens, 33.2K / 128K (26%) output tokens
  2. 112.8K / 1M (11%) input tokens, 39.5K / 128K (31%) output tokens
  3. 115.0K / 1M (11%) input tokens, 31.0K / 128K (24%) output tokens
  4. 42.9K / 1M (4%) input tokens, 5.8K / 128K (5%) output tokens

Total: (7.4K new + 320.4K cache writes + 12.5M cache reads) input tokens, 127.0K output tokens, $7.635125 cost

🤖 Models used:

  • Tool: Anthropic Claude Code
  • Requested: opus (claude-opus-5-5)
  • Thinking level: high (~23999 tokens)
  • Model: Claude Opus 5.5 (claude-opus-5-5)

📎 Log file uploaded as Gist (15489KB)


This AI session has ended. Monitoring of this pull request continues. Feel free to review and add feedback while checks are running.

@konard

konard commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

✅ Ready to merge

This pull request is now ready to be merged:

  • All CI checks have passed
  • No merge conflicts
  • No uncommitted changes

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Attempt to implement partially lock-free tree with delayed balancing

2 participants